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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
s-kawani/SKDesignableButton
|
SKDesignableButton/Classes/SKDesignableButton.swift
|
1
|
1282
|
//
// SKDesignableButton.swift
// SKDesignableButton
//
// Created by sk on 2017/04/02.
// Copyright © 2017 shin-kawani. All rights reserved.
//
import UIKit
@IBDesignable
final public class SKDesignableButton: UIButton {
@IBInspectable public var borderColor : UIColor = UIColor.blue
@IBInspectable public var borderWidth : CGFloat = 1.0
@IBInspectable public var cornerRadius : CGFloat = 5.0
override public func draw(_ rect: CGRect) {
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init(frame:CGRect, title: String, borderColor: UIColor?, borderWidth: CGFloat?, cornerRadius: CGFloat?) {
super.init(frame:frame)
if borderColor != nil {
self.borderColor = borderColor!
}
if borderColor != nil {
self.borderColor = borderColor!
}
if borderWidth != nil {
self.borderWidth = borderWidth!
}
if cornerRadius != nil {
self.cornerRadius = cornerRadius!
}
self.setTitle(title, for: .normal)
}
}
|
mit
|
e4780c566014d9dfd717ae4370b9b0a4
| 21.086207 | 114 | 0.652615 | 4.386986 | false | false | false | false |
Zewo/Epoch
|
Sources/HTTP/Message/Message.swift
|
1
|
3515
|
import Core
import Media
import Venice
// TODO: Make error CustomStringConvertible and ResponseRepresentable
public enum MessageError : Error {
case noReadableBody
case noContentTypeHeader
case unsupportedMediaType
case noDefaultContentType
case notContentRepresentable
case valueNotFound(key: String)
case incompatibleType(requestedType: Any.Type, actualType: Any.Type)
}
public typealias Storage = [String: Any]
public protocol Message : class {
var version: Version { get set }
var headers: Headers { get set }
var storage: Storage { get set }
var body: Body { get set }
}
extension Message {
public func set(_ value: Any?, key: String) {
storage[key] = value
}
public func get<T>(_ key: String) throws -> T {
guard let value = storage[key] else {
throw MessageError.valueNotFound(key: key)
}
guard let castedValue = value as? T else {
throw MessageError.incompatibleType(requestedType: T.self, actualType: type(of: value))
}
return castedValue
}
public var contentType: MediaType? {
get {
return headers["Content-Type"].flatMap({try? MediaType(string: $0)})
}
set(contentType) {
headers["Content-Type"] = contentType?.description
}
}
public var contentLength: Int? {
get {
return headers["Content-Length"].flatMap({Int($0)})
}
set(contentLength) {
headers["Content-Length"] = contentLength?.description
}
}
public var transferEncoding: String? {
get {
return headers["Transfer-Encoding"]
}
set(transferEncoding) {
headers["Transfer-Encoding"] = transferEncoding
}
}
public var isChunkEncoded: Bool {
return transferEncoding == "chunked"
}
public var connection: String? {
get {
return headers["Connection"]
}
set(connection) {
headers["Connection"] = connection
}
}
public var isKeepAlive: Bool {
if version.minor == 0 {
return connection?.lowercased() == "keep-alive"
}
return connection?.lowercased() != "close"
}
public var isUpgrade: Bool {
return connection?.lowercased() == "upgrade"
}
public var upgrade: String? {
return headers["Upgrade"]
}
public func content<Content : MediaDecodable>(
deadline: Deadline = 5.minutes.fromNow(),
userInfo: [CodingUserInfoKey: Any] = [:]
) throws -> Content {
guard let mediaType = self.contentType else {
throw MessageError.noContentTypeHeader
}
guard let readable = try? body.convertedToReadable() else {
throw MessageError.noReadableBody
}
let media = try Content.decodingMedia(for: mediaType)
return try media.decode(Content.self, from: readable, deadline: deadline, userInfo: userInfo)
}
public func content<Content : DecodingMedia>(
deadline: Deadline = 5.minutes.fromNow(),
userInfo: [CodingUserInfoKey: Any] = [:]
) throws -> Content {
guard let readable = try? body.convertedToReadable() else {
throw MessageError.noReadableBody
}
return try Content(from: readable, deadline: deadline)
}
}
|
mit
|
0bb950cb00a8240e12bd3768c59fb914
| 26.460938 | 101 | 0.590043 | 4.868421 | false | false | false | false |
STShenZhaoliang/Swift2Guide
|
Swift2Guide/Swift100Tips/Swift100Tips/CController.swift
|
1
|
2126
|
//
// CController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/30.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class CController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var pointer: UnsafeMutablePointer<MyClass3>!
pointer = UnsafeMutablePointer<MyClass3>.alloc(1)
pointer.initialize(MyClass3())
print(pointer.memory.a) // 1
pointer = nil
/*
虽然我们最后将 pointer 值为 nil,但是由于 UnsafeMutablePointer 并不会自动进行内存管理,因此其实 pointer 所指向的内存是没有被释放和回收的 (这可以从 MyClass 的 deinit 没有被调用来加以证实;这造成了内存泄露。
*/
var pointer1: UnsafeMutablePointer<MyClass3>!
pointer1 = UnsafeMutablePointer<MyClass3>.alloc(1)
pointer1.initialize(MyClass3())
print(pointer1.memory.a)
pointer1.destroy()
pointer1.dealloc(1)
pointer1 = nil
// 输出:
// 1
// deinit
/*
在手动处理这类指针的内存管理时,我们需要遵循的一个基本原则就是谁创建谁释放。destroy 与 dealloc 应该要与 alloc 成对出现,如果不是你创建的指针,那么一般来说你就不需要去释放它。一种最常见的例子就是如果我们是通过调用了某个方法得到的指针,那么除非文档或者负责这个方法的开发者明确告诉你应该由使用者进行释放,否则都不应该去试图管理它的内存状态:
*/
var x:UnsafeMutablePointer<tm>!
var t = time_t()
time(&t)
x = localtime(&t)
x = nil
/*
最后,虽然在本节的例子中使用的都是 alloc 和 dealloc 的情况,但是指针的内存申请也可以使用 malloc 或者 calloc 来完成,这种情况下在释放时我们需要对应使用 free 而不是 dealloc。
*/
}
}
class MyClass3 {
var a = 1
deinit {
print("deinit")
}
}
|
mit
|
3e188b4288151dcc28cc72f139100b7d
| 21.485294 | 193 | 0.616743 | 3.420582 | false | false | false | false |
dbahat/conventions-ios
|
Conventions/Conventions/model/UserInput.swift
|
1
|
2355
|
//
// UserInput.swift
// Conventions
//
// Created by David Bahat on 7/20/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
class UserInput {
class Feedback {
var answers: Array<FeedbackAnswer> = []
var isSent: Bool = false
init() {
}
init(json: Dictionary<String, AnyObject>) {
if let isSentString = json["isSent"] as? String {
self.isSent = NSString(string: isSentString).boolValue
}
if let answersArray = json["answers"] as? Array<Dictionary<String, AnyObject>> {
var result = Array<FeedbackAnswer>();
for answer in answersArray {
if let feedbackAnswer = FeedbackAnswer.parse(answer) {
result.append(feedbackAnswer)
}
}
self.answers = result
}
}
func toJson() -> Dictionary<String, AnyObject> {
return [
"isSent": isSent.description as AnyObject,
"answers": answers.map({$0.toJson()}) as AnyObject
]
}
}
class ConventionEventInput {
var attending: Bool
var feedbackUserInput: UserInput.Feedback
init(attending: Bool, feedbackUserInput: UserInput.Feedback) {
self.attending = attending
self.feedbackUserInput = feedbackUserInput
}
init(json: Dictionary<String, AnyObject>) {
if let attendingString = json["attending"] as? String {
self.attending = NSString(string: attendingString).boolValue
} else {
self.attending = false
}
if let feedbackObject = json["feedback"] as? Dictionary<String, AnyObject> {
self.feedbackUserInput = UserInput.Feedback(json: feedbackObject)
} else {
self.feedbackUserInput = UserInput.Feedback()
}
}
func toJson() -> Dictionary<String, AnyObject> {
return [
"attending": self.attending.description as AnyObject,
"feedback": self.feedbackUserInput.toJson() as AnyObject]
}
}
}
|
apache-2.0
|
cbf85cb11a4e3718e8022e0916bfe8d8
| 30.386667 | 92 | 0.519541 | 5.173626 | false | false | false | false |
devedbox/AXAnimationChain
|
AXAnimationChain/DecayAnimationViewController.swift
|
1
|
8312
|
//
// DecayAnimationViewController.swift
// AXAnimationChain
//
// Created by devedbox on 2017/4/1.
// Copyright © 2017年 devedbox. All rights reserved.
//
import UIKit
import ObjectiveC
import AXAnimationChainSwift
extension UIView {
private struct _AssociatedObjectKey {
static let touchsBeganKey = "touchsBegan"
}
internal var touchsBegan: ((Set<UITouch>, UIEvent?) -> Void)? {
get { return objc_getAssociatedObject(self, _AssociatedObjectKey.touchsBeganKey) as? ((Set<UITouch>, UIEvent?) -> Void) }
set { objc_setAssociatedObject(self, _AssociatedObjectKey.touchsBeganKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) }
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// print("\((String(#file) as NSString).lastPathComponent)")
touchsBegan?(touches, event)
}
}
class DecayAnimationViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var animatedView: UIView!
weak var panGesture: UIPanGestureRecognizer?
weak var longPressGesture: UILongPressGestureRecognizer?
var shouldBeginInactiveOfAnimatedView = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Add pan ges ture to the animated view.
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
pan.delegate = self
view.addGestureRecognizer(pan)
panGesture = pan
// let tap = UITapGestureRecognizer(target: self, action: #selector(handleTagGesture(_:)))
// tap.delegate = self
// view.addGestureRecognizer(tap)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
longPress.delegate = self
longPress.minimumPressDuration = 0.0001
// view.addGestureRecognizer(longPress)
// longPressGesture = longPress
view.touchsBegan = { [unowned self] touchs, event in
self._applyImmediateValueOfAnimatedView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions.
@objc
private func handleTagGesture(_ genture: UITapGestureRecognizer) {
// _applyImmediateValueOfAnimatedView()
print("State of tap gesture: \(genture.state.rawValue)")
}
@objc
private func handleLongPressGesture(_ genture: UILongPressGestureRecognizer) {
// _applyImmediateValueOfAnimatedView()
print("State of long press gesture: \(genture.state.rawValue)")
}
@objc
private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
var point = gesture.location(in: view)
switch gesture.state {
case .possible: fallthrough
case .began:
_applyImmediateValueOfAnimatedView()
point = gesture.location(in: view)
if animatedView.frame.contains(point) {
shouldBeginInactiveOfAnimatedView = true
} else {
shouldBeginInactiveOfAnimatedView = false
}
let pauseTime = animatedView.layer.convertTime(CACurrentMediaTime(), from: nil)
print("pause time: \(pauseTime)")
case .changed:
/*
point.x = max(animatedView.frame.width/2+64, point.x)
point.y = max(animatedView.frame.height/2+64, point.y)
point.x = min(view.frame.width-animatedView.frame.width/2, point.x)
point.y = min(view.frame.height-animatedView.frame.height/2, point.y)
*/
guard shouldBeginInactiveOfAnimatedView else { break }
animatedView.center = point
case .ended:
guard shouldBeginInactiveOfAnimatedView else { break }
point = gesture.location(in: view)
print("view's center:\(String(describing: animatedView.center)), layer's position:\(String(describing: animatedView.layer.position))")
let ve = gesture.velocity(in: animatedView)
let decayx = AXDecayAnimation(keyPath: "position.x")
decayx.fromValue = point.x
decayx.velocity = ve.x
decayx.isRemovedOnCompletion=false
decayx.fillMode=kCAFillModeForwards
// decayx.timingFunction = CAMediaTimingFunction.default()
// decayx.isAdditive = true
let decayy = AXDecayAnimation(keyPath: "position.y")
decayy.fromValue = point.y
decayy.velocity = ve.y
decayy.isRemovedOnCompletion=false
decayy.fillMode=kCAFillModeForwards
// decayy.timingFunction = CAMediaTimingFunction.default()
// decayy.isAdditive = true
CATransaction.setCompletionBlock({[weak self] () -> Void in
// print("view's center:\(String(describing: self?.animatedView.center)), layer's position:\(String(describing: self?.animatedView.layer.position))")
// self?.animatedView.layer.position = CGPoint(x: decayx.values?.last as! Double, y: decayy.values?.last as! Double)
// self?.animatedView.layer.removeAllAnimations()
// print("view's center:\(String(describing: self?.animatedView.center)), layer's position:\(String(describing: self?.animatedView.layer.position))")
self?._applyImmediateValueOfAnimatedView()
})
CATransaction.begin()
CATransaction.setDisableActions(false)
animatedView.layer.add(decayx, forKey: "position.x")
animatedView.layer.add(decayy, forKey: "position.y")
CATransaction.commit()
case .cancelled: break
case .failed: break
// default: break
}
}
// MARK: Private
private func _applyImmediateValueOfAnimatedView() {
defer {
animatedView.layer.removeAllAnimations()
}
guard let animationKeys = animatedView.layer.animationKeys() else { return }
for key in animationKeys {
guard let animation = animatedView.layer.animation(forKey: key) as? AXDecayAnimation else { continue }
let beginTime = animation.beginTime
// let timeOffset = animation.timeOffset
// print("begin time: \(beginTime), time offset: \(timeOffset)")
// print("current time: \(CACurrentMediaTime())")
let time = CACurrentMediaTime()-beginTime
guard let immediateValue = try? animation.immediateValue(atTime: time) else { continue }
animatedView.layer.setValue(immediateValue, forKeyPath: animation.keyPath!)
}
}
// MARK: UIGestureRecognizerDelegate.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UITapGestureRecognizer.self) {
return false
}
return false
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == longPressGesture && otherGestureRecognizer == panGesture {
return true
}
return false
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGesture && otherGestureRecognizer == longPressGesture {
return true
}
return false
}
/*
// 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
|
1828c3cdace34e98e9c27636beae4d5f
| 40.753769 | 165 | 0.641112 | 5.252212 | false | false | false | false |
mrdepth/Neocom
|
Neocom/Neocom/Database/NPCGroup.swift
|
2
|
2268
|
//
// NPCGroup.swift
// Neocom
//
// Created by Artem Shimanski on 24.12.2019.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
struct NPCGroup: View {
var parent: SDENpcGroup?
@Environment(\.managedObjectContext) var managedObjectContext
private func getGroups() -> FetchedResultsController<SDENpcGroup> {
let controller = managedObjectContext.from(SDENpcGroup.self)
.filter(/\SDENpcGroup.parentNpcGroup == parent)
.sort(by: \SDENpcGroup.npcGroupName, ascending: true)
.fetchedResultsController()
return FetchedResultsController(controller)
}
@StateObject private var groups = Lazy<FetchedResultsController<SDENpcGroup>, Never>()
private func content(for group: SDENpcGroup) -> some View {
HStack {
Icon(group.image)
Text(group.npcGroupName ?? "")
}
}
private func row(for group: SDENpcGroup) -> some View {
Group {
if (group.supNpcGroups?.count ?? 0) > 0 {
NavigationLink(destination: NPCGroup(parent: group)) {
self.content(for: group)
}
}
else {
NavigationLink(destination: Types(.npc(group))) {
self.content(for: group)
}
}
}
}
var body: some View {
let groups = self.groups.get(initial: getGroups())
let predicate = (/\SDEInvType.group?.npcGroups).count > 0
return List {
ForEach(groups.fetchedObjects, id: \.objectID, content: row)
}
.listStyle(GroupedListStyle())
.search { publisher in
TypesSearchResults(publisher: publisher, predicate: predicate) { type in
NavigationLink(destination: TypeInfo(type: type)) {
TypeCell(type: type)
}
}
}
.navigationBarTitle(parent?.npcGroupName ?? NSLocalizedString("NPC", comment: ""))
}
}
#if DEBUG
struct NPCGroup_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
NPCGroup()
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
|
lgpl-2.1
|
11a95345d9db6c86315c0a773d069a53
| 28.828947 | 90 | 0.58712 | 4.598377 | false | false | false | false |
CoderXiaoming/Ronaldo
|
SaleManager/SaleManager/Stock/Controller/SAMProductImageController.swift
|
1
|
13680
|
//
// SAMProductImageController.swift
// SaleManager
//
// Created by apple on 16/12/1.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
///operationView的高度
private let OperationViewHeight: CGFloat = 233.0
///operationView的动画时长
private let OperationViewShowHideAnimationDuration = 0.3
class SAMProductImageController: UIViewController {
///接收的数据模型
fileprivate var stockProductModel: SAMStockProductModel?
///接收的相同二维码名称数据模型数组
fileprivate var sameCodeNameModels: NSMutableArray?
///对外提供的类工厂方法
class func instance(stockModel: SAMStockProductModel, sameNameModels: NSMutableArray) -> SAMProductImageController {
let vc = SAMProductImageController()
vc.stockProductModel = stockModel
vc.sameCodeNameModels = sameNameModels
vc.hidesBottomBarWhenPushed = true
return vc
}
//MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//初始化UI
setupUI()
//添加右上角按钮
setupRightItem()
}
//MARK: - 初始化UI
fileprivate func setupUI() {
//设置主标题
navigationItem.title = "产品图片"
//添加scrollView 设置frame
let height = ScreenH - navigationController!.navigationBar.frame.maxY
scrollView?.frame = CGRect(x: 0, y: 0, width: ScreenW, height: height)
view.addSubview(scrollView!)
//设置产品图片
if stockProductModel?.imageUrl1 != "" {
productImage?.sd_setImage(with: URL.init(string: stockProductModel!.imageUrl1), placeholderImage: UIImage(named: "photo_loadding"))
}else {
productImage?.image = UIImage(named: "photo_loadding")
}
//设置产品图片尺寸
let y = (scrollView!.bounds.height - ScreenW) * 0.5
productImage?.frame = CGRect(x: 0, y: y, width: ScreenW, height: ScreenW)
//添加产品图片到scrollView
scrollView?.addSubview(productImage!)
}
//MARK: - 添加右上角按钮,有权限才添加
fileprivate func setupRightItem() {
let btn = UIButton(type: .custom)
btn.addTarget(self, action: #selector(SAMProductImageController.moreInfoBtnClick), for: .touchUpInside)
btn.setImage(UIImage(named: "productImageMoreOperetionImage"), for: UIControlState())
btn.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
}
//MARK: - viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//设置hudView
setupHUDView()
//设置oprationView
setupOperationView()
}
//MARK: - 初始化设置HUDView
fileprivate func setupHUDView() {
//添加到主窗口上
hudView = UIView()
hudView!.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
KeyWindow!.addSubview(hudView!)
//设置frame
hudView?.frame = UIScreen.main.bounds
hudView?.alpha = 0.00001
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SAMProductImageController.hideOperationView))
hudView?.addGestureRecognizer(tapGesture)
}
//MARK: - 初始化设置OperationView
fileprivate func setupOperationView() {
//添加operationView
operationView = SAMProductImageOpetationView.instacne()
operationView?.delegate = self
KeyWindow!.addSubview(operationView!)
//设置frame
let y = ScreenH - OperationViewHeight
operationView?.frame = CGRect(x: 0, y: y, width: ScreenW, height: OperationViewHeight)
//设置初始隐藏transform
operationView?.transform = CGAffineTransform(translationX: 0, y: OperationViewHeight)
}
//MARK: - 导航栏右上角按钮点击事件
func moreInfoBtnClick() {
//展示operationView
showOperationView()
}
//MARK: - 展示operationView
func showOperationView() {
UIView.animate(withDuration: OperationViewShowHideAnimationDuration, animations: {
self.operationView?.transform = CGAffineTransform.identity
self.hudView?.alpha = 1
}, completion: { (_) in
})
}
//MARK: - 隐藏operationView
func hideOperationView() {
UIView.animate(withDuration: OperationViewShowHideAnimationDuration, animations: {
self.operationView?.transform = CGAffineTransform(translationX: 0, y: OperationViewHeight)
self.hudView?.alpha = 0.0001
}, completion: { (_) in
})
}
//MARK: - 展示图片选择界面
fileprivate func showImagePickerController(_ type: UIImagePickerControllerSourceType) {
if UIImagePickerController.isSourceTypeAvailable(type) {
//设置类型
imagePickerController?.sourceType = type
//展示界面
navigationController!.present(imagePickerController!, animated: true, completion: {
})
}
}
//MARK: - 保存照片后的回调方法
func didFinishSaveImageWithError(_ image: UIImage?, error: NSError?, contextInfo: AnyObject) {
if error == nil {
let _ = SAMHUD.showMessage("保存成功", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}else {
let _ = SAMHUD.showMessage("保存失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}
//MARK: - 上传图片
fileprivate func unloadProductImage(_ image: UIImage) {
//展示提示信息
let hud = SAMHUD.showAdded(to: KeyWindow!, animated: true)!
hud.labelText = NSLocalizedString("正在上传...", comment: "HUD loading title")
//创建请求参数
let patameters = ["codeID": stockProductModel!.codeID, "imageIndex": 1] as [String : Any]
//子线程发送上传请求
SAMNetWorker.sharedUnloadImageNetWorker().post("uploadImage.ashx", parameters: patameters, constructingBodyWith: { (formData) in
//获取图片数据
let data = UIImageJPEGRepresentation(image, 1.0)!
formData.appendPart(withFileData: data, name: "1", fileName: "image.jpg", mimeType: "image/jpg")
}, progress: { (progress) in
}, success: {[weak self] (Task, json) in
let Json = json as! [String: AnyObject]
//回到主线程
DispatchQueue.main.async(execute: {
//获取返回信息
let messageDict = Json["head"] as! [String: String]
if messageDict["status"] == "success" { //上传成功
//重新设置数据模型
let urlDict = Json["body"] as! [[String: String]]
let model = self!.stockProductModel
model?.thumbUrl1 = urlDict[0]["thumbUrl"]!
model?.imageUrl1 = urlDict[0]["imageUrl"]!
self!.stockProductModel = model
//设置图片
self!.productImage?.sd_setImage(with: URL.init(string: self!.stockProductModel!.imageUrl1))
//隐藏loadingHUD
hud.hide(true)
//提示用户上传成功
let _ = SAMHUD.showMessage("上传成功", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
//记录上传状态
SAMStockHasUnloadProductImage = true
}else { //上传失败
//隐藏loadingHUD
hud.hide(true)
let _ = SAMHUD.showMessage("上传失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
})
}) { (Task, Error) in
//隐藏loadingHUD,展示提示信息
DispatchQueue.main.async(execute: {
hud.hide(true)
let _ = SAMHUD.showMessage("网络错误", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
})
}
}
//MARK: - 懒加载属性
///背景scrollview
fileprivate lazy var scrollView: UIScrollView? = {
let scrollView = UIScrollView()
scrollView.backgroundColor = UIColor(red: 241 / 255.0, green: 240 / 255.0, blue: 255 / 255.0, alpha: 1.0)
//设置缩放比例
scrollView.maximumZoomScale = 2.0
scrollView.minimumZoomScale = 1.0
//设置代理
scrollView.delegate = self
return scrollView
}()
///展示的大图
fileprivate lazy var productImage: UIImageView? = UIImageView()
///oprationView
fileprivate var operationView: SAMProductImageOpetationView?
///HUDView
fileprivate var hudView: UIView?
///图片选择器
fileprivate lazy var imagePickerController: UIImagePickerController? = {
let imageVC = UIImagePickerController()
imageVC.allowsEditing = true
imageVC.delegate = self
return imageVC
}()
//MARK: - 其他方法
fileprivate init() {
super.init(nibName: nil, bundle: nil)
}
fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - UIScrollViewDelegate
extension SAMProductImageController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return productImage
}
//确保 productImage 在 scrollView的中间
func scrollViewDidZoom(_ scrollView: UIScrollView) {
var centerX = scrollView.center.x
var centerY = scrollView.center.y
centerX = scrollView.contentSize.width > scrollView.frame.width ? scrollView.contentSize.width / 2 : centerX
centerY = scrollView.contentSize.height > scrollView.frame.height ? scrollView.contentSize.height / 2 : centerY
productImage!.center = CGPoint(x: centerX, y: centerY)
}
}
//MARK: - SAMProductImageOpetationViewDelegate
extension SAMProductImageController: SAMProductImageOpetationViewDelegate {
func opetationViewDidClickCameraBtn() {
//隐藏operationView
hideOperationView()
//展示控制器界面
showImagePickerController(UIImagePickerControllerSourceType.camera)
}
func opetationViewDidClickSelectBtn() {
//隐藏operationView
hideOperationView()
//展示控制器界面
showImagePickerController(UIImagePickerControllerSourceType.photoLibrary)
}
func opetationViewDidClickSaveBtn() {
//隐藏operationView
hideOperationView()
//保存照片
UIImageWriteToSavedPhotosAlbum(productImage!.image!, self, #selector(SAMProductImageController.didFinishSaveImageWithError(_:error:contextInfo:)), nil)
}
func opetationViewDidClickCancelBtn() {
//隐藏operationView
hideOperationView()
}
func opetationViewDidClickSaveProductStockImageBtn() {
//隐藏operationView
hideOperationView()
//生成图片
let productImageStockView = SAMProducutStockImageView.instace(stockModel: stockProductModel!, productModels: sameCodeNameModels!)
let height = ScreenW + 37.0 * CGFloat(sameCodeNameModels!.count)
productImageStockView.frame = CGRect(x: 0, y: 0, width: ScreenW, height: height)
view.insertSubview(productImageStockView, at: 0)
UIGraphicsBeginImageContextWithOptions(productImageStockView.bounds.size, false, 0)
let ctx = UIGraphicsGetCurrentContext()
productImageStockView.layer.render(in: ctx!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
//保存照片
UIImageWriteToSavedPhotosAlbum(image, self, #selector(SAMOrderDetailController.didFinishSaveImageWithError(_:error:contextInfo:)), nil)
UIGraphicsEndImageContext()
}
}
//MARK: - UIImagePickerControllerDelegate
extension SAMProductImageController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//获取图片
let selectedImage = info["UIImagePickerControllerEditedImage"] as? UIImage
//退出图片选择控制器控制器
picker.dismiss(animated: true) {
}
//如果图片不为空,上传图片
if selectedImage != nil {
unloadProductImage(selectedImage!)
}
}
}
|
apache-2.0
|
fb8793d7b89f6ab01ea883d4d560d320
| 33.752022 | 159 | 0.59986 | 5.153078 | false | false | false | false |
auth0/Lock.iOS-OSX
|
Lock/DatabaseOnlyView.swift
|
1
|
11866
|
// DatabaseOnlyView.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class DatabaseOnlyView: UIView, DatabaseView {
weak var form: Form?
weak var secondaryButton: SecondaryButton?
weak var primaryButton: PrimaryButton?
weak var switcher: DatabaseModeSwitcher?
weak var authCollectionView: AuthCollectionView?
weak var separator: UILabel?
weak var secondaryStrut: UIView?
weak var ssoBar: InfoBarView?
weak var spacer: UIView?
private var style: Style?
weak var showPasswordButton: IconButton?
weak var identityField: InputField?
weak var passwordField: InputField?
var allFields: [InputField]?
// FIXME: Remove this from the view since it should not even know it exists
var navigator: Navigable?
private weak var container: UIStackView?
let allowedModes: DatabaseMode
init(allowedModes: DatabaseMode = [.Login, .Signup, .ResetPassword]) {
let primaryButton = PrimaryButton()
let container = UIStackView()
self.allowedModes = allowedModes
self.primaryButton = primaryButton
self.container = container
super.init(frame: CGRect.zero)
self.addSubview(container)
self.addSubview(primaryButton)
container.alignment = .fill
container.axis = .vertical
container.distribution = .equalSpacing
container.spacing = 10
constraintEqual(anchor: container.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: container.topAnchor, toAnchor: self.topAnchor)
constraintEqual(anchor: container.rightAnchor, toAnchor: self.rightAnchor)
constraintEqual(anchor: container.bottomAnchor, toAnchor: primaryButton.topAnchor)
container.translatesAutoresizingMaskIntoConstraints = false
self.layoutSwitcher(allowedModes.contains(.Login) && allowedModes.contains(.Signup))
constraintEqual(anchor: primaryButton.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: primaryButton.rightAnchor, toAnchor: self.rightAnchor)
constraintEqual(anchor: primaryButton.bottomAnchor, toAnchor: self.bottomAnchor)
primaryButton.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
private let switcherIndex = 0
private let formOnlyIndex = 1
private let formBelowSocialIndex = 3
private let separatorIndex = 2
private let socialIndex = 1
func showLogin(withIdentifierStyle style: DatabaseIdentifierStyle, identifier: String? = nil, authCollectionView: AuthCollectionView? = nil, showPassword: Bool) {
let form = CredentialView()
let type: InputField.InputType
switch style {
case [.Email, .Username]:
type = .emailOrUsername
case [.Username]:
type = .username
default:
type = .email
}
form.identityField.text = identifier
form.identityField.type = type
form.identityField.returnKey = .next
form.identityField.nextField = form.passwordField
form.passwordField.returnKey = .done
primaryButton?.title = "LOG IN".i18n(key: "com.auth0.lock.submit.login.title", comment: "Login Button title")
self.layoutSecondaryButton(self.allowedModes.contains(.ResetPassword))
layoutInStack(form, authCollectionView: authCollectionView)
self.form = form
self.identityField = form.identityField
self.passwordField = form.passwordField
if showPassword, let passwordInput = form.passwordField.textField {
self.showPasswordButton = form.passwordField.addFieldButton(withIcon: "ic_show_password_hidden", color: Style.Auth0.inputIconColor)
self.showPasswordButton?.onPress = { [unowned self] button in
passwordInput.isSecureTextEntry = !passwordInput.isSecureTextEntry
button.icon = LazyImage(name: passwordInput.isSecureTextEntry ? "ic_show_password_hidden" : "ic_show_password_visible", bundle: Lock.bundle).image(compatibleWithTraits: self.traitCollection)
}
}
}
// swiftlint:disable:next function_parameter_count
func showSignUp(withUsername showUsername: Bool, username: String?, email: String?, authCollectionView: AuthCollectionView? = nil, additionalFields: [CustomTextField], passwordPolicyValidator: PasswordPolicyValidator? = nil, showPassword: Bool, showTerms: Bool) {
let form = SignUpView(additionalFields: additionalFields)
form.showUsername = showUsername
form.emailField.text = email
form.emailField.nextField = showUsername ? form.usernameField : form.passwordField
form.usernameField?.text = username
form.usernameField?.nextField = form.passwordField
primaryButton?.title = "SIGN UP".i18n(key: "com.auth0.lock.submit.signup.title", comment: "Signup Button title")
layoutInStack(form, authCollectionView: authCollectionView)
self.layoutSecondaryButton(showTerms)
self.form = form
self.identityField = showUsername ? form.usernameField : form.emailField
self.passwordField = form.passwordField
self.allFields = form.stackView.arrangedSubviews.compactMap { $0 as? InputField }
if let passwordPolicyValidator = passwordPolicyValidator {
let passwordPolicyView = PolicyView(rules: passwordPolicyValidator.policy.rules)
if let style = style {
passwordPolicyView.styleSubViews(style: style)
}
passwordPolicyValidator.delegate = passwordPolicyView
let passwordIndex = form.stackView.arrangedSubviews.firstIndex(of: form.passwordField)
form.stackView.insertArrangedSubview(passwordPolicyView, at: passwordIndex!)
passwordPolicyView.isHidden = true
form.passwordField.errorLabel?.removeFromSuperview()
form.passwordField.onBeginEditing = { [weak self, weak passwordPolicyView] _ in
guard let view = passwordPolicyView else { return }
Queue.main.async {
view.isHidden = false
self?.navigator?.scroll(toPosition: CGPoint(x: 0, y: view.intrinsicContentSize.height), animated: false)
}
}
form.passwordField.onEndEditing = { [weak passwordPolicyView] _ in
guard let view = passwordPolicyView else { return }
view.isHidden = true
}
}
if showPassword, let passwordInput = form.passwordField.textField {
self.showPasswordButton = form.passwordField.addFieldButton(withIcon: "ic_show_password_hidden", color: Style.Auth0.inputIconColor)
self.showPasswordButton?.onPress = { [unowned self] button in
passwordInput.isSecureTextEntry = !passwordInput.isSecureTextEntry
button.icon = LazyImage(name: passwordInput.isSecureTextEntry ? "ic_show_password_hidden" : "ic_show_password_visible", bundle: Lock.bundle).image(compatibleWithTraits: self.traitCollection)
}
}
}
func presentEnterprise() {
guard let form = self.form as? CredentialView else { return }
let ssoBar = InfoBarView.ssoInfoBar
let viewCount = self.container?.subviews.count ?? 0
let spacer = strutView(withHeight: 125 - CGFloat(viewCount) * 25)
ssoBar.isHidden = false
self.container?.insertArrangedSubview(ssoBar, at: 0)
self.container?.addArrangedSubview(spacer)
self.ssoBar = ssoBar
self.spacer = spacer
form.passwordField.isHidden = true
form.identityField.nextField = nil
form.identityField.returnKey = .done
form.identityField.onReturn = form.passwordField.onReturn
self.switcher?.isHidden = true
self.secondaryButton?.isHidden = true
}
func removeEnterprise() {
guard let ssoBar = self.ssoBar, let spacer = self.spacer, let form = self.form as? CredentialView else { return }
ssoBar.removeFromSuperview()
spacer.removeFromSuperview()
form.passwordField.isHidden = false
form.identityField.nextField = form.passwordField
form.identityField.returnKey = .next
self.switcher?.isHidden = false
self.secondaryButton?.isHidden = false
self.ssoBar = nil
self.spacer = nil
}
private func layoutSecondaryButton(_ enabled: Bool) {
self.secondaryStrut?.removeFromSuperview()
self.secondaryButton?.removeFromSuperview()
if enabled {
let secondaryButton = SecondaryButton()
self.secondaryButton = secondaryButton
self.container?.addArrangedSubview(secondaryButton)
} else {
let view = strutView()
self.secondaryStrut = view
self.container?.addArrangedSubview(view)
}
}
private func layoutSwitcher(_ enabled: Bool) {
self.container?.arrangedSubviews.first?.removeFromSuperview()
if enabled {
let switcher = DatabaseModeSwitcher()
self.container?.insertArrangedSubview(switcher, at: switcherIndex)
self.switcher = switcher
} else {
let view = strutView()
self.container?.insertArrangedSubview(view, at: switcherIndex)
}
}
private func layoutInStack(_ view: UIView, authCollectionView: AuthCollectionView?) {
if let current = self.form as? UIView {
current.removeFromSuperview()
}
self.authCollectionView?.removeFromSuperview()
self.separator?.removeFromSuperview()
if let social = authCollectionView {
let label = UILabel()
label.text = "or".i18n(key: "com.auth0.lock.database.separator", comment: "Social separator")
label.font = mediumSystemFont(size: 13.75)
label.textAlignment = .center
self.container?.insertArrangedSubview(social, at: socialIndex)
self.container?.insertArrangedSubview(label, at: separatorIndex)
self.container?.insertArrangedSubview(view, at: formBelowSocialIndex)
self.authCollectionView = social
self.separator = label
} else {
self.container?.insertArrangedSubview(view, at: formOnlyIndex)
}
if let style = self.style {
self.separator?.textColor = style.seperatorTextColor
self.container?.styleSubViews(style: style)
}
}
func apply(style: Style) {
self.style = style
self.separator?.textColor = style.seperatorTextColor
}
}
|
mit
|
e82d64b0818f62b9abae2c975fd2525d
| 41.992754 | 267 | 0.682117 | 4.94005 | false | false | false | false |
midjuly/cordova-plugin-iosrtc
|
src/PluginRTCPeerConnection.swift
|
1
|
16243
|
import Foundation
class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate {
var rtcPeerConnectionFactory: RTCPeerConnectionFactory
var rtcPeerConnection: RTCPeerConnection!
var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig
var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints
// PluginRTCDataChannel dictionary.
var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:]
var eventListener: (data: NSDictionary) -> Void
var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void
var eventListenerForRemoveStream: (id: String) -> Void
var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)!
var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)!
var onSetDescriptionSuccessCallback: (() -> Void)!
var onSetDescriptionFailureCallback: ((error: NSError) -> Void)!
init(
rtcPeerConnectionFactory: RTCPeerConnectionFactory,
pcConfig: NSDictionary?,
pcConstraints: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void,
eventListenerForRemoveStream: (id: String) -> Void
) {
NSLog("PluginRTCPeerConnection#init()")
self.rtcPeerConnectionFactory = rtcPeerConnectionFactory
self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig)
self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints)
self.eventListener = eventListener
self.eventListenerForAddStream = eventListenerForAddStream
self.eventListenerForRemoveStream = eventListenerForRemoveStream
}
deinit {
NSLog("PluginRTCPeerConnection#deinit()")
}
func run() {
NSLog("PluginRTCPeerConnection#run()")
self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers(
self.pluginRTCPeerConnectionConfig.getIceServers(),
constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(),
delegate: self
)
}
func createOffer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createOffer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createOfferWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func createAnswer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createAnswer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createAnswerWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func setLocalDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setLocalDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setLocalDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func setRemoteDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setRemoteDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func addIceCandidate(
candidate: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: () -> Void
) {
NSLog("PluginRTCPeerConnection#addIceCandidate()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let sdpMid = candidate.objectForKey("sdpMid") as? String ?? ""
let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0
let candidate = candidate.objectForKey("candidate") as? String ?? ""
let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate(
mid: sdpMid,
index: sdpMLineIndex,
sdp: candidate
))
var data: NSDictionary
if result == true {
if self.rtcPeerConnection.remoteDescription != nil {
data = [
"remoteDescription": [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
]
} else {
data = [
"remoteDescription": false
]
}
callback(data: data)
} else {
errback()
}
}
func addStream(pluginMediaStream: PluginMediaStream) -> Bool {
NSLog("PluginRTCPeerConnection#addStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return false
}
return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream)
}
func removeStream(pluginMediaStream: PluginMediaStream) {
NSLog("PluginRTCPeerConnection#removeStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream)
}
func createDataChannel(
dcId: Int,
label: String,
options: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#createDataChannel()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcPeerConnection: rtcPeerConnection,
label: label,
options: options,
eventListener: eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
}
func RTCDataChannel_setListener(
dcId: Int,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()")
weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
// Set the eventListener.
pluginRTCDataChannel!.setListener(eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
}
func close() {
NSLog("PluginRTCPeerConnection#close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.close()
}
func RTCDataChannel_sendString(
dcId: Int,
data: String,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendString(data, callback: callback)
}
func RTCDataChannel_sendBinary(
dcId: Int,
data: NSData,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendBinary(data, callback: callback)
}
func RTCDataChannel_close(dcId: Int) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.close()
// Remove the pluginRTCDataChannel from the dictionary.
self.pluginRTCDataChannels[dcId] = nil
}
/**
* Methods inherited from RTCPeerConnectionDelegate.
*/
func peerConnection(peerConnection: RTCPeerConnection!,
signalingStateChanged newState: RTCSignalingState) {
let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:\(state_str)]")
self.eventListener(data: [
"type": "signalingstatechange",
"signalingState": state_str
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceGatheringChanged newState: RTCICEGatheringState) {
let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:\(state_str)]")
self.eventListener(data: [
"type": "icegatheringstatechange",
"iceGatheringState": state_str
])
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
// Emit an empty candidate if iceGatheringState is "complete".
if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil {
self.eventListener(data: [
"type": "icecandidate",
// NOTE: Cannot set null as value.
"candidate": false,
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
gotICECandidate candidate: RTCICECandidate!) {
NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:\(candidate.sdpMid), sdpMLineIndex:\(candidate.sdpMLineIndex), candidate:\(candidate.sdp)]")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.eventListener(data: [
"type": "icecandidate",
"candidate": [
"sdpMid": candidate.sdpMid,
"sdpMLineIndex": candidate.sdpMLineIndex,
"candidate": candidate.sdp
],
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceConnectionChanged newState: RTCICEConnectionState) {
let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:\(state_str)]")
self.eventListener(data: [
"type": "iceconnectionstatechange",
"iceConnectionState": state_str
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
addedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onaddstream")
let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream)
pluginMediaStream.run()
// Let the plugin store it in its dictionary.
self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream)
// Fire the 'addstream' event so the JS will create a new MediaStream.
self.eventListener(data: [
"type": "addstream",
"stream": pluginMediaStream.getJSON()
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
removedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onremovestream")
// Let the plugin remove it from its dictionary.
self.eventListenerForRemoveStream(id: rtcMediaStream.label)
self.eventListener(data: [
"type": "removestream",
"streamId": rtcMediaStream.label // NOTE: No "id" property yet.
])
}
func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) {
NSLog("PluginRTCPeerConnection | onnegotiationeeded")
self.eventListener(data: [
"type": "negotiationneeded"
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
didOpenDataChannel rtcDataChannel: RTCDataChannel!) {
NSLog("PluginRTCPeerConnection | ondatachannel")
let dcId = PluginUtils.randomInt(10000, max:99999)
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcDataChannel: rtcDataChannel
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
// Fire the 'datachannel' event so the JS will create a new RTCDataChannel.
self.eventListener(data: [
"type": "datachannel",
"channel": [
"dcId": dcId,
"label": rtcDataChannel.label,
"ordered": rtcDataChannel.isOrdered,
"maxPacketLifeTime": rtcDataChannel.maxRetransmitTime,
"maxRetransmits": rtcDataChannel.maxRetransmits,
"protocol": rtcDataChannel.`protocol`,
"negotiated": rtcDataChannel.isNegotiated,
"id": rtcDataChannel.streamId,
"readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!,
"bufferedAmount": rtcDataChannel.bufferedAmount
]
])
}
/**
* Methods inherited from RTCSessionDescriptionDelegate.
*/
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) {
if error == nil {
self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription)
} else {
self.onCreateDescriptionFailureCallback(error: error)
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
didSetSessionDescriptionWithError error: NSError!) {
if error == nil {
self.onSetDescriptionSuccessCallback()
} else {
self.onSetDescriptionFailureCallback(error: error)
}
}
}
|
mit
|
85144503d161558ac41d30c516c1ff32
| 27.396853 | 150 | 0.755402 | 3.993853 | false | false | false | false |
playgroundscon/Playgrounds
|
Playgrounds/Link.swift
|
1
|
1714
|
//
// Link.swift
// Playgrounds
//
// Created by Bas Broek on 21/01/2017.
// Copyright © 2017 Andyy Hope. All rights reserved.
//
import Foundation
import SwiftyJSON
final class Link: NSObject, NSCoding {
fileprivate enum Key {
static let type = "type"
static let label = "label"
static let url = "url"
}
init(type: Type, label: String, url: URL) {
self.type = type
self.label = label
self.url = url
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(type.rawValue, forKey: Key.type)
aCoder.encode(label, forKey: Key.label)
aCoder.encode(url.absoluteString, forKey: Key.url)
}
required convenience init(coder aDecoder: NSCoder) {
guard
let typeValue = aDecoder.decodeObject(forKey: Key.type) as? String,
let type = Type(rawValue: typeValue),
let label = aDecoder.decodeObject(forKey: Key.label) as? String,
let urlString = aDecoder.decodeObject(forKey: Key.url) as? String,
let url = URL(string: urlString)
else { fatalError("Could not decode object `Link`.") }
self.init(type: type, label: label, url: url)
}
enum `Type`: String {
case twitter, website
}
let type: Type
let label: String
let url: URL
init?(json: JSON) {
guard
let type = Type(rawValue: json["type"].stringValue),
let label = json["label"].string,
let url = URL(string: json["link"].stringValue)
else { return nil }
self.type = type
self.label = label
self.url = url
}
}
|
gpl-3.0
|
28617c8893146181d7d51748ff887a61
| 26.190476 | 79 | 0.569761 | 4.198529 | false | false | false | false |
xoyip/AzureStorageApiClient
|
Pod/Classes/AzureStorage/Queue/Request/PutMessageRequest.swift
|
1
|
1230
|
//
// PutMessageRequest.swift
// AzureStorageApiClient
//
// Created by Hiromasa Ohno on 2015/08/06.
// Copyright (c) 2015 Hiromasa Ohno. All rights reserved.
//
import Foundation
public extension AzureQueue {
public class PutMessagesRequest: PutMessagesRequestBase {
override public var method : String { get { return "POST" } }
var messageTTL : Int?
var visibilityTimeout : Int?
public typealias Response = Bool
public init(queue : String, message: String, messageTTL: Int?, visibilityTimeout: Int?) {
self.messageTTL = messageTTL
self.visibilityTimeout = visibilityTimeout
super.init(queue: queue, message: message)
}
override internal func parameters() -> [String] {
var params : [String] = []
if let ttl = messageTTL {
params.append("messagettl=\(ttl)")
}
if let visibility = visibilityTimeout {
params.append("visibilitytimeout=\(visibility)")
}
return params
}
override internal func basePath() -> String {
return "/\(queue)/messages"
}
}
}
|
mit
|
35d25679b723701b18c2120b5ce4af2d
| 29.75 | 97 | 0.576423 | 5 | false | false | false | false |
yinhaofrancis/YHAlertView
|
YHKit/YHViewStyle.swift
|
1
|
2694
|
//
// YHViewStyle.swift
// YHAlertView
//
// Created by hao yin on 2017/5/28.
// Copyright © 2017年 yyk. All rights reserved.
//
import UIKit
public typealias YHViewStyle<T> = (T)->Void
/**
链接多个style
*/
public func + <T:UIView>(lv:@escaping YHViewStyle<T>,rv:@escaping YHViewStyle<T>)->YHViewStyle<T>{
return { v in
lv(v)
rv(v)
}
}
public func makeStyle<T>(style:@escaping YHViewStyle<T>)->YHViewStyle<T>{
return style
}
public enum layoutMarginDirection:Int{
case top = 2
case right = -1
case bottom = -2
case left = 1
}
extension UIView{
public func margin(view:UIView?,value:CGFloat,direct:layoutMarginDirection){
let tra = trans(direct: direct)
let tra2 = view == nil ? trans(direct: direct) : trans(direct: reflect(option: direct))
if self.translatesAutoresizingMaskIntoConstraints{
self.translatesAutoresizingMaskIntoConstraints = false
}
let cons = NSLayoutConstraint(item: self, attribute: tra.0, relatedBy: .equal, toItem: view ?? self.superview!, attribute: tra2.0, multiplier: 1, constant: value * tra.1)
self.superview?.addConstraint(cons)
}
public func edge(value:CGFloat){
self.margin(view: nil, value: value, direct: .top)
self.margin(view: nil, value: value, direct: .bottom)
self.margin(view: nil, value: value, direct: .left)
self.margin(view: nil, value: value, direct: .right)
}
public func equal(v:UIView?,attr:NSLayoutAttribute){
if self.translatesAutoresizingMaskIntoConstraints{
self.translatesAutoresizingMaskIntoConstraints = false
}
let cons = NSLayoutConstraint(item: self, attribute: attr, relatedBy: .equal, toItem: v ?? self.superview!, attribute: attr, multiplier: 1, constant: 0)
self.superview?.addConstraint(cons)
}
public func equal(Value:CGFloat,attr:NSLayoutAttribute){
if self.translatesAutoresizingMaskIntoConstraints{
self.translatesAutoresizingMaskIntoConstraints = false
}
let cons = NSLayoutConstraint(item: self, attribute: attr, relatedBy: .equal, toItem: nil, attribute: attr, multiplier: 1, constant: Value)
self.superview?.addConstraint(cons)
}
func trans(direct:layoutMarginDirection)->(NSLayoutAttribute,CGFloat){
switch direct {
case .left: return (.left,1)
case .right: return (.right,-1)
case .top: return (.top,1)
case .bottom: return(.bottom,-1)
}
}
func reflect(option:layoutMarginDirection)->layoutMarginDirection{
return layoutMarginDirection(rawValue: option.rawValue * -1)!
}
}
|
mit
|
0fbf96553edd93eb22519f877b087336
| 34.773333 | 178 | 0.664182 | 4.127692 | false | false | false | false |
iOSWizards/MVUIHacks
|
MVUIHacks/Classes/Designable/DesignableImageView.swift
|
1
|
751
|
//
// DesignableImageView.swift
// MV UI Hacks
//
// Created by Evandro Harrison Hoffmann on 08/07/2016.
// Copyright © 2016 It's Day Off. All rights reserved.
//
import UIKit
@IBDesignable
open class DesignableImageView: UIImageView {
// MARK: - Shapes
@IBInspectable open var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
}
|
mit
|
f41a63cbba29ab2010c4d33c7a4377b0
| 19.833333 | 66 | 0.593333 | 4.77707 | false | false | false | false |
abury/ABPadLockScreen
|
ABPadLockScreenSwiftDemo/ABPadLockScreenSwiftDemo/ViewController.swift
|
1
|
4165
|
//
// ViewController.swift
// ABPadLockScreenSwiftDemo
//
// Created by Aron Bury on 13/09/2015.
// Copyright © 2015 Aron Bury. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ABPadLockScreenSetupViewControllerDelegate, ABPadLockScreenViewControllerDelegate {
@IBOutlet weak var setPinButton: UIButton!
@IBOutlet weak var lockAppButton: UIButton!
private(set) var thePin: String?
//MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Your Amazing App!"
ABPadLockScreenView.appearance().backgroundColor = UIColor(hue:0.61, saturation:0.55, brightness:0.64, alpha:1)
ABPadLockScreenView.appearance().labelColor = UIColor.whiteColor()
let buttonLineColor = UIColor(red: 229/255, green: 180/255, blue: 46/255, alpha: 1)
ABPadButton.appearance().backgroundColor = UIColor.clearColor()
ABPadButton.appearance().borderColor = buttonLineColor
ABPadButton.appearance().selectedColor = buttonLineColor
ABPinSelectionView.appearance().selectedColor = buttonLineColor
}
//MARK: Action methods
@IBAction func lockAppSelected(sender: AnyObject) {
if thePin == nil {
let alertController = UIAlertController(title: "You must set a pin first", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
return
}
let lockScreen = ABPadLockScreenViewController(delegate: self, complexPin: false)
lockScreen.setAllowedAttempts(3)
lockScreen.modalPresentationStyle = UIModalPresentationStyle.FullScreen
lockScreen.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
presentViewController(lockScreen, animated: true, completion: nil)
}
@IBAction func setPinSelected(sender: AnyObject) {
let lockSetupScreen = ABPadLockScreenSetupViewController(delegate: self, complexPin: false, subtitleLabelText: "Select a pin")
lockSetupScreen.tapSoundEnabled = true
lockSetupScreen.errorVibrateEnabled = true
lockSetupScreen.modalPresentationStyle = UIModalPresentationStyle.FullScreen
lockSetupScreen.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
presentViewController(lockSetupScreen, animated: true, completion: nil)
}
//MARK: Lock Screen Setup Delegate
func pinSet(pin: String!, padLockScreenSetupViewController padLockScreenViewController: ABPadLockScreenSetupViewController!) {
thePin = pin
dismissViewControllerAnimated(true, completion: nil)
}
func unlockWasCancelledForSetupViewController(padLockScreenViewController: ABPadLockScreenAbstractViewController!) {
dismissViewControllerAnimated(true, completion: nil)
}
//MARK: Lock Screen Delegate
func padLockScreenViewController(padLockScreenViewController: ABPadLockScreenViewController!, validatePin pin: String!) -> Bool {
print("Validating Pin \(pin)")
return thePin == pin
}
func unlockWasSuccessfulForPadLockScreenViewController(padLockScreenViewController: ABPadLockScreenViewController!) {
print("Unlock Successful!")
dismissViewControllerAnimated(true, completion: nil)
}
func unlockWasUnsuccessful(falsePin: String!, afterAttemptNumber attemptNumber: Int, padLockScreenViewController: ABPadLockScreenViewController!) {
print("Failed Attempt \(attemptNumber) with incorrect pin \(falsePin)")
}
func unlockWasCancelledForPadLockScreenViewController(padLockScreenViewController: ABPadLockScreenViewController!) {
print("Unlock Cancled")
dismissViewControllerAnimated(true, completion: nil)
}
func forgotPinForPadLockScreenViewController(padLockScreenViewController: ABPadLockScreenViewController!) {
print("User forgot their pin!")
}
}
|
mit
|
59512127e4ff8260610dee843aa3c704
| 42.831579 | 151 | 0.728146 | 5.318008 | false | false | false | false |
wenghengcong/Coderpursue
|
BeeFun/BeeFun/ToolKit/JSToolKit/JSFoundation/String+Extension.swift
|
1
|
30150
|
//
// String+Extension.swift
// LoveYou
//
// Created by WengHengcong on 2017/3/12.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
// MARK: - Localized
extension String {
//http://stackoverflow.com/questions/25081757/whats-nslocalizedstring-equivalent-in-swift
//https://github.com/nixzhu/dev-blog/blob/master/2014-04-24-internationalization-tutorial-for-ios-2014.md
/// 获取APP语言字符串
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.appBundle, value: "", comment: "")
}
/// 获取英文国际化字符串
var enLocalized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.enBundle, value: "", comment: "")
}
/// 获取中文国际化字符串
var cnLocalized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.cnBundle, value: "", comment: "")
}
/// 获取APP语言字符串
func localized(withComment: String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.appBundle, value: "", comment: withComment)
}
/// 获取英文国际化字符串
func enLocalized(withComment: String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.enBundle, value: "", comment: withComment)
}
/// 获取中文国际化字符串
func cnLocalized(withComment: String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.cnBundle, value: "", comment: withComment)
}
}
// MARK: - count
extension String {
/// 字符串长度
var length: Int {
return characters.count
}
/// 按UTF16标准的字符串长度
var utf16Length: Int {
return self.utf16.count
}
// MARK: - index
/// 返回Index类型
///
/// - Parameter from: <#from description#>
/// - Returns: <#return value description#>
func index(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
}
// MARK: - substring
extension String {
//http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3
/// 裁剪字符串from
///
/// - Parameter from: <#from description#>
/// - Returns: <#return value description#>
func substring(from: Int) -> String {
let fromIndex = index(from: from)
return substring(from: fromIndex)
}
/// 裁剪字符串to
///
/// - Parameter to: <#to description#>
/// - Returns: <#return value description#>
func substring(to: Int) -> String {
let toIndex = index(from: to)
return substring(to: toIndex)
}
/// 裁剪字符串range
///
/// - Parameter r: <#r description#>
/// - Returns: <#return value description#>
func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return substring(with: startIndex..<endIndex)
}
}
extension String {
/// 随机字符串,包含大小写字母、数字
///
/// - Parameter length: 长度应小于62
/// - Returns: <#return value description#>
static func randomCharsNums(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return random(length: length, letters: letters)
}
/// 随机字符串,只包含大小写字母
///
/// - Parameter length: 长度应小于52
/// - Returns: <#return value description#>
static func randomChars(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return random(length: length, letters: letters)
}
/// 随机字符串,只包含数字
///
/// - Parameter length: 长度应小于10
static func randomNums(length: Int) -> String {
let letters = "0123456789"
return random(length: length, letters: letters)
}
/// 随机字符串
///
/// - Parameters:
/// - length: 生成的字符串长度
/// - letters: 用语生成随机字符串的字符串数据集
/// - Returns: <#return value description#>
static func random(length: Int, letters: String) -> String {
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
let nextCharIndex = letters.index(letters.startIndex, offsetBy: Int(rand))
let nextChar = String(letters[nextCharIndex])
randomString += nextChar
}
return randomString
}
}
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension String {
/// SwifterSwift: String decoded from base64 (if applicable).
public var base64Decoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
guard let decodedData = Data(base64Encoded: self) else {
return nil
}
return String(data: decodedData, encoding: .utf8)
}
/// SwifterSwift: String encoded in base64 (if applicable).
public var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
/// SwifterSwift: Array of characters of a string.
public var charactersArray: [Character] {
return Array(characters)
}
/// SwifterSwift: CamelCase of string.
public var camelCased: String {
let source = lowercased()
if source.characters.contains(" ") {
let first = source.substring(to: source.index(after: source.startIndex))
let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "")
let rest = String(camel.characters.dropFirst())
return first + rest
}
let first = source.lowercased().substring(to: source.index(after: source.startIndex))
let rest = String(source.characters.dropFirst())
return first + rest
}
/// SwifterSwift: Check if string contains one or more emojis.
public var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
public var firstCharacter: String? {
guard let first = characters.first else {
return nil
}
return String(first)
}
/// SwifterSwift: Check if string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// SwifterSwift: Check if string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// SwifterSwift: Check if string contains only letters.
public var isAlphabetic: Bool {
return hasLetters && !hasNumbers
}
/// SwifterSwift: Check if string contains at least one letter and one number.
public var isAlphaNumeric: Bool {
return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers
}
/// SwifterSwift: Check if string is valid email format.
public var isEmail: Bool {
// http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
return matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
}
/// SwifterSwift: Check if string is a valid URL.
public var isValidUrl: Bool {
return URL(string: self) != nil
}
/// SwifterSwift: Check if string is a valid schemed URL.
public var isValidSchemedUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme != nil
}
/// SwifterSwift: Check if string is a valid https URL.
public var isValidHttpsUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme == "https"
}
/// SwifterSwift: Check if string is a valid http URL.
public var isValidHttpUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme == "http"
}
/// SwifterSwift: Check if string contains only numbers.
public var isNumeric: Bool {
return !hasLetters && hasNumbers
}
/// Check if string contains only digits.
public var isOnlyNumeric: Bool {
//remove . symbol ,because some number written "1,000" or "1,000,000"
let removeDot = self.replacing(",", with: "")
let onlyDigits: CharacterSet = CharacterSet.decimalDigits.inverted
if removeDot.rangeOfCharacter(from: onlyDigits) == nil {
// String only consist digits 0-9
return true
}
return false
}
/// SwifterSwift: Last character of string (if applicable).
public var lastCharacter: String? {
guard let last = characters.last else {
return nil
}
return String(last)
}
/// SwifterSwift: Latinized string.
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
/// SwifterSwift: Array of strings separated by new lines.
public var lines: [String] {
var result = [String]()
enumerateLines { line, _ in
result.append(line)
}
return result
}
/// SwifterSwift: The most common character in string.
public var mostCommonCharacter: String {
let mostCommon = withoutSpacesAndNewLines.characters.reduce([Character: Int]()) {
var counts = $0
counts[$1] = ($0[$1] ?? 0) + 1
return counts
}.max { $0.1 < $1.1 }?.0
return mostCommon?.string ?? ""
}
/// SwifterSwift: Reversed string.
public var reversed: String {
return String(characters.reversed())
}
/// SwifterSwift: Bool value from string (if applicable).
public var bool: Bool? {
let selfLowercased = trimmed.lowercased()
switch selfLowercased {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}
/// SwifterSwift: Date object from "yyyy-MM-dd" formatted string
public var date: Date? {
let selfLowercased = trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string.
public var dateTime: Date? {
let selfLowercased = trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Double value from string (if applicable).
public var double: Double? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Double
}
/// SwifterSwift: Float value from string (if applicable).
public var float: Float? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float
}
/// SwifterSwift: Float32 value from string (if applicable).
public var float32: Float32? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float32
}
/// SwifterSwift: Float64 value from string (if applicable).
public var float64: Float64? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float64
}
/// SwifterSwift: Integer value from string (if applicable).
public var int: Int? {
return Int(self)
}
/// SwifterSwift: Int16 value from string (if applicable).
public var int16: Int16? {
return Int16(self)
}
/// SwifterSwift: Int32 value from string (if applicable).
public var int32: Int32? {
return Int32(self)
}
/// SwifterSwift: Int64 value from string (if applicable).
public var int64: Int64? {
return Int64(self)
}
/// SwifterSwift: Int8 value from string (if applicable).
public var int8: Int8? {
return Int8(self)
}
/// SwifterSwift: URL from string (if applicable).
public var url: URL? {
return URL(string: self)
}
/// SwifterSwift: String with no spaces or new lines in beginning and end.
public var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
/// SwifterSwift: Array with unicodes for all characters in a string.
public var unicodeArray: [Int] {
return unicodeScalars.map({$0.hashValue})
}
/// SwifterSwift: Readable string from a URL string.
public var urlDecoded: String {
return removingPercentEncoding ?? self
}
/// SwifterSwift: URL escaped string.
public var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
/// SwifterSwift: String without spaces and new lines.
public var withoutSpacesAndNewLines: String {
return replacing(" ", with: "").replacing("\n", with: "")
}
}
// MARK: - Methods
public extension String {
/// SwifterSwift: Safely subscript string with index.
///
/// - Parameter i: index.
public subscript(i: Int) -> String? {
guard i >= 0 && i < characters.count else {
return nil
}
return String(self[index(startIndex, offsetBy: i)])
}
#if os(iOS) || os(macOS)
/// SwifterSwift: Copy string to global pasteboard.
public func copyToPasteboard() {
#if os(iOS)
UIPasteboard.general.string = self
#elseif os(macOS)
NSPasteboard.general().clearContents()
NSPasteboard.general().setString(self, forType: NSPasteboardTypeString)
#endif
}
#endif
/// SwifterSwift: Converts string format to CamelCase.
public mutating func camelize() {
self = camelCased
}
/// SwifterSwift: Check if string contains one or more instance of substring.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
public func contains(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
/// SwifterSwift: Count of substring in string.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: count of appearance of substring in string.
public func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string.lowercased()).count - 1
}
return components(separatedBy: string).count - 1
}
/// SwifterSwift: Check if string ends with substring.
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// SwifterSwift: First index of substring in string.
///
/// - Parameter string: substring to search for.
/// - Returns: first index of substring in string (if applicable).
public func firstIndex(of string: String) -> Int? {
return Array(characters).map({String($0)}).index(of: string)
}
/// SwifterSwift: Latinize string.
public mutating func latinize() {
self = latinized
}
/// SwifterSwift: String by replacing part of string with another string.
///
/// - Parameters:
/// - substring: old substring to find and replace.
/// - newString: new string to insert in old string place.
/// - Returns: string after replacing substring with newString.
public func replacing(_ substring: String, with newString: String) -> String {
return replacingOccurrences(of: substring, with: newString)
}
/// SwifterSwift: Reverse string.
public mutating func reverse() {
self = String(characters.reversed())
}
/// SwifterSwift: Array of strings separated by given string.
///
/// - Parameter separator: separator to split string by.
/// - Returns: array of strings separated by given string.
public func splitted(by separator: Character) -> [String] {
return characters.split{$0 == separator}.map(String.init)
}
/// SwifterSwift: Check if string starts with substring.
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// SwifterSwift: Date object from string of date format.
///
/// - Parameter format: date format.
/// - Returns: Date object from string (if applicable).
public func date(withFormat format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
/// SwifterSwift: Removes spaces and new lines in beginning and end of string.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// SwifterSwift: Truncate string (cut it to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string (default is "...").
public mutating func truncate(toLength: Int, trailing: String? = "...") {
guard toLength > 0 else {
return
}
if characters.count > toLength {
self = substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
}
/// SwifterSwift: Truncated string (limited to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string.
/// - Returns: truncated string (this is an extr...).
public func truncated(toLength: Int, trailing: String? = "...") -> String {
guard 1..<characters.count ~= toLength else { return self }
return substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
/// SwifterSwift: Convert URL string to readable string.
public mutating func urlDecode() {
if let decoded = removingPercentEncoding {
self = decoded
}
}
/// SwifterSwift: Escape string.
public mutating func urlEncode() {
if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
self = encoded
}
}
/// SwifterSwift: Verify if string matches the regex pattern.
///
/// - Parameter pattern: Pattern to verify.
/// - Returns: true if string matches the pattern.
func matches(pattern: String) -> Bool {
return range(of: pattern,
options: String.CompareOptions.regularExpression,
range: nil, locale: nil) != nil
}
}
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: new string with given string repeated n times.
public static func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else {
return ""
}
return String(repeating: lhs, count: rhs)
}
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: new string with given string repeated n times.
public static func * (lhs: Int, rhs: String) -> String {
guard lhs > 0 else {
return ""
}
return String(repeating: rhs, count: lhs)
}
}
// MARK: - Initializers
public extension String {
/// SwifterSwift: Create a new string from a base64 string (if applicable).
///
/// - Parameter base64: base64 string.
public init?(base64: String) {
guard let str = base64.base64Decoded else {
return nil
}
self.init(str)
}
}
// MARK: - NSAttributedString extensions
public extension String {
#if !os(tvOS) && !os(watchOS)
/// SwifterSwift: Bold string.
public var bold: NSAttributedString {
#if os(macOS)
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize())])
#else
return NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
#endif
}
#endif
/// SwifterSwift: Underlined string
public var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])
}
/// SwifterSwift: Strikethrough string.
public var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSAttributedStringKey.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)])
}
#if os(iOS)
/// SwifterSwift: Italic string.
public var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if os(macOS)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: NSColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
}
#else
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.foregroundColor: color])
}
#endif
}
//MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string.
public var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: NSString lastPathComponent.
public var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension.
public var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent.
public var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension.
public var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents.
public var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: NSString appendingPathComponent(str: String)
///
/// - Parameter str: the path component to append to the receiver.
/// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
public func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String)
///
/// - Parameter str: The extension to append to the receiver.
/// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
public func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
}
extension String {
/// EZSE: Checks if string is empty or consists only of whitespace and newline characters
public var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
/// EZSE: split string using a spearator string, returns an array of string
public func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed.isEmpty
}
}
/// EZSE: split string with delimiters, returns an array of string
public func split(_ characters: CharacterSet) -> [String] {
return self.components(separatedBy: characters).filter {
!$0.trimmed.isEmpty
}
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [URL] {
var urls: [URL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch _ as NSError {
detector = nil
}
let text = self
if let detector = detector {
detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: {
(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, let url = result.url {
urls.append(url)
}
})
}
return urls
}
/// EZSE: Checking if String contains input with comparing options
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
#if os(iOS)
/// EZSE: copy string to pasteboard
public func addToPasteboard() {
let pasteboard = UIPasteboard.general
pasteboard.string = self
}
#endif
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).character(at: i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
}
return false
}
}
extension String {
init(_ value: Float, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
init(_ value: Double, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
}
/// EZSE: Pattern matching of strings via defined functions
public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool {
return pattern(value)
}
/// EZSE: Can be used in switch-case
public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasPrefix(prefix)
}
}
/// EZSE: Can be used in switch-case
public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasSuffix(suffix)
}
}
extension String {
var numbers: String {
return String(characters.filter { "0"..."9" ~= $0 })
}
}
|
mit
|
cda84814a466e2dddcd6ff2273f46dc4
| 32.262277 | 166 | 0.618193 | 4.680854 | false | false | false | false |
wolf81/Nimbl3Survey
|
Nimbl3Survey/UIImageExtensions.swift
|
1
|
1603
|
//
// UIImageExtensions.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 22/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func averageColor(alpha: CGFloat) -> UIColor {
let rawImageRef: CGImage = self.cgImage!
let data: CFData = rawImageRef.dataProvider!.data!
let rawPixelData = CFDataGetBytePtr(data);
let imageHeight = rawImageRef.height
let imageWidth = rawImageRef.width
let bytesPerRow = rawImageRef.bytesPerRow
let stride = rawImageRef.bitsPerPixel / 6
var r = 0
var g = 0
var b = 0
for row in 0 ... imageHeight {
var rowPtr = rawPixelData! + bytesPerRow * row
for _ in 0...imageWidth {
r += Int(rowPtr[0])
g += Int(rowPtr[1])
b += Int(rowPtr[2])
rowPtr += Int(stride)
}
}
let f: CGFloat = 1.0 / (255.0 * CGFloat(imageWidth) * CGFloat(imageHeight))
return UIColor(red: f * CGFloat(r), green: f * CGFloat(g), blue: f * CGFloat(b), alpha: alpha)
}
}
|
bsd-2-clause
|
2aa5da84ec630b85ceecc956938736d6
| 30.411765 | 102 | 0.574282 | 4.401099 | false | false | false | false |
WeltN24/Carlos
|
Tests/CarlosTests/NormalizationTests.swift
|
1
|
4737
|
import Foundation
import Nimble
import Quick
import Carlos
import Combine
struct NormalizedCacheSharedExamplesContext {
static let CacheToTest = "normalizedCache"
static let OriginalCache = "originalCache"
}
final class NormalizationSharedExamplesConfiguration: QuickConfiguration {
override class func configure(_: Configuration) {
sharedExamples("no-op if the original cache is a BasicCache") { (sharedExampleContext: @escaping SharedExampleContext) in
var cacheToTest: BasicCache<String, Int>!
var originalCache: BasicCache<String, Int>!
beforeEach {
cacheToTest = sharedExampleContext()[NormalizedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
originalCache = sharedExampleContext()[NormalizedCacheSharedExamplesContext.OriginalCache] as? BasicCache<String, Int>
}
it("should have a valid cache to test") {
expect(cacheToTest).notTo(beNil())
}
it("should return the same value for the normalized cache") {
expect(cacheToTest) === originalCache
}
}
sharedExamples("wrap the original cache into a BasicCache") { (sharedExampleContext: @escaping SharedExampleContext) in
var cacheToTest: BasicCache<String, Int>!
var originalCache: CacheLevelFake<String, Int>!
var cancellable: AnyCancellable?
beforeEach {
cacheToTest = sharedExampleContext()[NormalizedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
originalCache = sharedExampleContext()[NormalizedCacheSharedExamplesContext.OriginalCache] as? CacheLevelFake<String, Int>
}
afterEach {
cancellable?.cancel()
cancellable = nil
}
context("when calling get") {
let key = "key to test"
var expectedRequest: PassthroughSubject<Int, Error>!
beforeEach {
expectedRequest = PassthroughSubject()
originalCache.getSubject = expectedRequest
cancellable = cacheToTest.get(key).sink(receiveCompletion: { _ in }, receiveValue: { _ in })
}
it("should call the closure") {
expect(originalCache.numberOfTimesCalledGet) == 1
}
it("should pass the right key") {
expect(originalCache.didGetKey) == key
}
}
context("when calling set") {
let key = "test key"
let value = 101
beforeEach {
_ = cacheToTest.set(value, forKey: key)
}
it("should call the closure") {
expect(originalCache.numberOfTimesCalledSet) == 1
}
it("should pass the right key") {
expect(originalCache.didSetKey) == key
}
it("should pass the right value") {
expect(originalCache.didSetValue) == value
}
}
context("when calling clear") {
beforeEach {
cacheToTest.clear()
}
it("should call the closure") {
expect(originalCache.numberOfTimesCalledClear) == 1
}
}
context("when calling onMemoryWarning") {
beforeEach {
cacheToTest.onMemoryWarning()
}
it("should call the closure") {
expect(originalCache.numberOfTimesCalledOnMemoryWarning) == 1
}
}
}
}
}
final class NormalizationTests: QuickSpec {
override func spec() {
var cacheToTest: BasicCache<String, Int>!
describe("Normalization through the protocol extension") {
context("when normalizing a BasicCache") {
var originalCache: BasicCache<String, Int>!
var keyTransformer: OneWayTransformationBox<String, String>!
beforeEach {
keyTransformer = OneWayTransformationBox(transform: { Just($0).setFailureType(to: Error.self).eraseToAnyPublisher() })
originalCache = CacheLevelFake<String, Int>().transformKeys(keyTransformer)
cacheToTest = originalCache.normalize()
}
itBehavesLike("no-op if the original cache is a BasicCache") {
[
NormalizedCacheSharedExamplesContext.OriginalCache: originalCache as Any,
NormalizedCacheSharedExamplesContext.CacheToTest: cacheToTest as Any
]
}
}
context("when normalizing another type of cache") {
var originalCache: CacheLevelFake<String, Int>!
beforeEach {
originalCache = CacheLevelFake()
cacheToTest = originalCache.normalize()
}
itBehavesLike("wrap the original cache into a BasicCache") {
[
NormalizedCacheSharedExamplesContext.OriginalCache: originalCache as Any,
NormalizedCacheSharedExamplesContext.CacheToTest: cacheToTest as Any
]
}
}
}
}
}
|
mit
|
3d501dcbc3e3aeab5147267c21363c0b
| 30.164474 | 130 | 0.649145 | 5.352542 | false | true | false | false |
zeroc-ice/ice-demos
|
swift/IceDiscovery/replication/Sources/Server/main.swift
|
1
|
1217
|
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Foundation
import Ice
// Automatically flush stdout
setbuf(__stdoutp, nil)
class HelloI: Hello {
var name: String
init(_ name: String) {
self.name = name
}
func getGreeting(current _: Ice.Current) throws -> String {
return "\(name) says Hello World!"
}
func shutdown(current: Ice.Current) throws {
print("Shutting down...")
current.adapter!.getCommunicator().shutdown()
}
}
func run() -> Int32 {
do {
var args = CommandLine.arguments
let communicator = try Ice.initialize(&args)
defer {
communicator.destroy()
}
guard args.count == 1 else {
print("too many arguments\n")
return 1
}
let adapter = try communicator.createObjectAdapter("Hello")
try adapter.add(servant: HelloDisp(HelloI(communicator.getProperties().getProperty("Ice.ProgramName"))),
id: Ice.stringToIdentity("hello"))
try adapter.activate()
communicator.waitForShutdown()
return 0
} catch {
print("Error: \(error)\n")
return 1
}
}
exit(run())
|
gpl-2.0
|
5d676ae78eae5023c94d9ad38fc30d18
| 21.537037 | 112 | 0.580937 | 4.377698 | false | false | false | false |
grd888/ios_uicollectionview_2nd_edition_source_code
|
Chapter 2/Swift/Chapter 2 Project 4/Chapter 2 Project 4/AFViewController.swift
|
1
|
2214
|
//
// AFViewController.swift
// Chapter 2 Project 4
//
// Created by Greg Delgado on 26/10/2017.
// Copyright © 2017 Greg Delgado. All rights reserved.
//
import UIKit
private let CellIdentifier = "Cell Identifier"
class AFViewController: UICollectionViewController {
var datesArray = [Date]()
var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "h:mm:ss a", options: 0, locale: NSLocale.current)
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.minimumInteritemSpacing = 40.0
flowLayout.minimumLineSpacing = 40.0
flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
flowLayout.itemSize = CGSize(width: 200, height: 200)
self.collectionView!.register(AFCollectionViewCell.self, forCellWithReuseIdentifier: CellIdentifier)
self.collectionView?.indicatorStyle = .white
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(userTappedAddButton))
navigationItem.rightBarButtonItem = addButton
navigationItem.title = "Our Time Machine"
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datesArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! AFCollectionViewCell
cell.text = dateFormatter.string(from: datesArray[indexPath.item])
return cell
}
@objc func userTappedAddButton(sender: Any) {
collectionView?.performBatchUpdates({
let newDate = Date()
datesArray.insert(newDate, at: 0)
collectionView?.insertItems(at: [IndexPath(item: 0, section: 0)])
}, completion: nil)
}
}
|
apache-2.0
|
864ee797c1fccc139aad01c48d7862e9
| 34.126984 | 131 | 0.693629 | 5.319712 | false | false | false | false |
sinss/LCFramework
|
LCFramework/Extensions/NSString+extension.swift
|
1
|
3751
|
//
// NSString+extension.swift
// extensionSample
//
// Created by Leo Chang on 7/8/14.
// Copyright (c) 2014 Perfectidea. All rights reserved.
//
import Foundation
extension NSString {
class func getDisplayApplicationName() -> NSString {
var info : NSDictionary = NSBundle.mainBundle().infoDictionary!
return info["CFBundleDisplayName"] as! NSString
}
/**
*/
func toDate() -> NSDate {
var formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
return formatter.dateFromString(self as String)!
}
/**
*/
func toEndOfDate() -> NSDate {
var formatter : NSDateFormatter = NSDateFormatter();
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
let dateString = NSString(format: "%@ 23:59:59", self)
return formatter.dateFromString(dateString as String)!
}
/**
return a date object from a full date string
*/
func toFullDate() -> NSDate {
var formatter : NSDateFormatter = NSDateFormatter();
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
return formatter.dateFromString(self as String)!
}
/**
Check this string is pure integer or not
*/
func isPureInt() -> Bool {
let scan : NSScanner = NSScanner(string: self as String)
var val : Int = 0
return scan.scanInteger(&val) && scan.atEnd
}
/**
Check this string is pure float or not
*/
func isPureDouble() -> Bool {
let scan : NSScanner = NSScanner(string: self as String)
var val : Float = 0.0
return scan.scanFloat(&val) && scan.atEnd
}
func isBlank() -> Bool {
return self.isEqualToString("") ? true : false
}
/**
*/
func numberOfWords() -> NSInteger {
var scanner : NSScanner = NSScanner(string: self as String)
var space = NSCharacterSet .whitespaceAndNewlineCharacterSet()
var count : NSInteger = 0
while scanner.scanUpToCharactersFromSet(space, intoString: nil) { count += 1}
return count
}
/**
*/
func containString(string : NSString) -> Bool {
return self.rangeOfString(string as String).location == NSNotFound ? false : true
}
/**
*/
func addString(string : NSString) -> NSString {
if string.isBlank() {
return self
}
return string.stringByAppendingString(string as String)
}
/**
*/
func removeSubString(string : NSString) -> NSString {
if self.containsString(string as String) {
var range : NSRange = self.rangeOfString(string as String)
return self.stringByReplacingCharactersInRange(range, withString: string as String)
}
return self
}
/**
Check email
*/
func isValidEmail() -> Bool {
var regex : NSString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluateWithObject(self)
}
/**
phone number
*/
func isValidPhoneNumber() -> Bool {
var regex : NSString = "[235689][0-9]{6}([0-9]{3})?"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluateWithObject(self)
}
/**
url
*/
func isValidUrl() -> Bool {
var regex : NSString = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluateWithObject(self)
}
}
|
mit
|
879d7f43198bcc392e3aa6377f1834fe
| 25.992806 | 111 | 0.565982 | 4.602454 | false | false | false | false |
zom/Zom-iOS
|
Zom/Zom/Classes/View Controllers/ZomMainTabbedViewController.swift
|
1
|
13957
|
//
// ZomMainTabbedViewController.swift
// Zom
//
// Created by N-Pex on 2016-11-14.
//
//
import Foundation
open class ZomMainTabbedViewController: UITabBarController, OTRComposeViewControllerDelegate, ZomMigrationInfoViewControllerDelegateProtocol, ZomAccountMigrationViewControllerAutoDelegateProtocol {
private var chatsViewController:ZomConversationViewController? = nil
private var friendsViewController:ZomComposeViewController? = nil
private var meViewController:ZomProfileViewController? = nil
private var observerContext = 0
private var observersRegistered:Bool = false
private var barButtonSettings:UIBarButtonItem?
private var barButtonAddChat:UIBarButtonItem?
private var chatsViewControllerTitleView:UIView?
private var friendsViewControllerTitleView:UIView?
private var automaticMigrationViewController:UIViewController?
convenience init() {
self.init(nibName:nil, bundle:nil)
}
@objc open func createTabs() {
if let appDelegate = UIApplication.shared.delegate as? OTRAppDelegate {
var newControllers:[UIViewController] = [];
for child in childViewControllers {
if (child.restorationIdentifier == "chats") {
chatsViewController = (appDelegate.conversationViewController as! ZomConversationViewController)
chatsViewController!.tabBarItem = child.tabBarItem
newControllers.append(chatsViewController!)
} else if (child.restorationIdentifier == "friends") {
friendsViewController = ZomComposeViewController()
if (friendsViewController!.view != nil) {
friendsViewController!.tabBarItem = child.tabBarItem
}
friendsViewController?.delegate = self
newControllers.append(friendsViewController!)
} else if (child.restorationIdentifier == "me") {
meViewController = ZomProfileViewController(nibName: nil, bundle: nil)
meViewController?.tabBarItem = child.tabBarItem
//meViewController = child as? ZomProfileViewController
newControllers.append(meViewController!)
}
else {
newControllers.append(child)
}
}
setViewControllers(newControllers, animated: false)
}
// Create bar button items
self.barButtonSettings = UIBarButtonItem(image: UIImage(named: "14-gear"), style: .plain, target: self, action: #selector(self.settingsButtonPressed(_:)))
self.barButtonAddChat = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(self.didPressAddButton(_:)))
// Hide the tab item text, but don't null it (we use it to build the top title)
for item:UITabBarItem in self.tabBar.items! {
item.selectedImage = item.image
item.image = item.image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
item.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.clear,
NSAttributedStringKey.font:UIFont.systemFont(ofSize: 1)], for: .normal)
item.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
}
// Show current tab by a small white top border
tabBar.selectionIndicatorImage = createSelectionIndicator(UIColor.white, size: CGSize(width:tabBar.frame.width/CGFloat(tabBar.items!.count),height:tabBar.frame.height), lineHeight: 3.0)
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
updateRightButtons()
NetworkSnackBarManager.shared.addSnackViewContainer(self.view,bottomOffset:self.tabBar.frame.size.height)
}
private func registerObservers() {
if (!observersRegistered) {
observersRegistered = true
OTRProtocolManager.sharedInstance().addObserver(self, forKeyPath: "numberOfConnectedProtocols", options: NSKeyValueObservingOptions.new, context: &observerContext)
OTRProtocolManager.sharedInstance().addObserver(self, forKeyPath: "numberOfConnectingProtocols", options: NSKeyValueObservingOptions.new, context: &observerContext)
if (selectedViewController == meViewController) {
populateMeTabController()
}
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
registerObservers()
updateTitle()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NetworkSnackBarManager.shared.addSnackViewContainer(self.view,bottomOffset:self.tabBar.frame.size.height)
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NetworkSnackBarManager.shared.removeSnackViewContainer(self.view)
}
override open func viewDidDisappear(_ animated: Bool) {
if (observersRegistered) {
observersRegistered = false
OTRProtocolManager.sharedInstance().removeObserver(self, forKeyPath: "numberOfConnectedProtocols", context: &observerContext)
OTRProtocolManager.sharedInstance().removeObserver(self, forKeyPath: "numberOfConnectingProtocols", context: &observerContext)
}
super.viewDidDisappear(animated)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &observerContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if (selectedViewController == meViewController) {
// Maybe we need to update this!
populateMeTabController()
}
}
override open var selectedViewController: UIViewController? {
didSet {
updateTitle()
updateRightButtons()
}
}
override open var selectedIndex: Int {
didSet {
updateTitle()
updateRightButtons()
}
}
private func updateTitle() {
if (selectedViewController != nil) {
let appName = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
self.navigationItem.title = appName + " | " + selectedViewController!.tabBarItem.title!
if (selectedViewController == meViewController) {
populateMeTabController()
}
if selectedViewController == chatsViewController {
// Get the title view from the child
if chatsViewControllerTitleView == nil {
chatsViewControllerTitleView = chatsViewController?.navigationItem.titleView
if let titleView = chatsViewControllerTitleView {
for subview:UIView in titleView.subviews {
subview.tintColor = UIColor.white
}
}
}
self.navigationItem.titleView = chatsViewControllerTitleView
} else if selectedViewController == friendsViewController {
// Get the title view from the child
if friendsViewControllerTitleView == nil {
friendsViewControllerTitleView = friendsViewController?.navigationItem.titleView
if let titleView = friendsViewControllerTitleView {
for subview:UIView in titleView.subviews {
subview.tintColor = UIColor.white
}
}
}
self.navigationItem.titleView = friendsViewControllerTitleView
} else {
self.navigationItem.titleView = nil
}
} else {
self.navigationItem.titleView = nil
}
}
private func updateRightButtons() {
if let add = barButtonAddChat, let settings = barButtonSettings {
if (selectedIndex == 0 || selectedIndex == 1) {
navigationItem.rightBarButtonItems = [add]
} else if (selectedIndex == 3) {
navigationItem.rightBarButtonItems = [settings]
} else {
navigationItem.rightBarButtonItems = []
}
}
}
private func createSelectionIndicator(_ color: UIColor, size: CGSize, lineHeight: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: lineHeight))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
@IBAction func settingsButtonPressed(_ sender: AnyObject) {
self.chatsViewController?.settingsButtonPressed(sender)
}
@IBAction func didPressAddButton(_ sender: AnyObject) {
if let appDelegate = UIApplication.shared.delegate as? ZomAppDelegate {
appDelegate.splitViewCoordinator.conversationViewController(appDelegate.conversationViewController, didSelectCompose: self)
}
}
private func populateMeTabController() {
if (meViewController != nil) {
if let appDelegate = UIApplication.shared.delegate as? ZomAppDelegate,let account = appDelegate.getDefaultAccount() {
let otrKit = OTRProtocolManager.encryptionManager.otrKit
let info = ZomProfileViewControllerInfo.createInfo(account, protocolString: account.protocolTypeString(), otrKit: otrKit)
self.meViewController?.setupWithInfo(info: info)
}
}
}
// MARK: - OTRComposeViewControllerDelegate
open func controller(_ viewController: OTRComposeViewController, didSelectBuddies buddies: [String]?, accountId: String?, name: String?) {
guard let buds = buddies else { return }
if (buds.count == 1) {
guard let accountKey = accountId else { return }
if let buddyKey = buds.first {
var buddy:OTRBuddy? = nil
var account:OTRAccount? = nil
OTRDatabaseManager.shared.readConnection?.read { (transaction) -> Void in
buddy = OTRBuddy.fetchObject(withUniqueID: buddyKey, transaction: transaction)
account = OTRAccount.fetchObject(withUniqueID: accountKey, transaction: transaction)
}
if let b = buddy, let a = account {
let profileVC = ZomProfileViewController(nibName: nil, bundle: nil)
let otrKit = OTRProtocolManager.encryptionManager.otrKit
let info = ZomProfileViewControllerInfo.createInfo(b, accountName: a.username, protocolString: a.protocolTypeString(), otrKit: otrKit, hasSession: false, calledFromGroup: false, showAllFingerprints: false)
profileVC.setupWithInfo(info: info)
self.navigationController?.pushViewController(profileVC, animated: true)
}
}
} else if (buds.count > 1) {
let delegate = ZomAppDelegate.appDelegate.splitViewCoordinator
viewController.navigationController?.popViewController(animated: true)
delegate.controller(viewController, didSelectBuddies: buddies, accountId: accountId, name: name)
}
}
open func controllerDidCancel(_ viewController: OTRComposeViewController) {
}
@IBAction func startAutoMigrationButtonPressed(_ sender: AnyObject) {
startAutomaticMigration()
}
@IBAction func showMigrationInfoButtonPressed(_ sender: AnyObject) {
performSegue(withIdentifier: "showMigrationInfo", sender: self)
}
public func startAutomaticMigration() {
guard let migrationView = chatsViewController?.migrationInfoHeaderView as? ZomMigrationInfoHeaderView, let oldAccount = migrationView.account, self.automaticMigrationViewController == nil else { return }
chatsViewController?.migrationStep = 1
let migrateVC = OTRAccountMigrationViewController(oldAccount: oldAccount)
migrateVC.showsCancelButton = true
migrateVC.modalPresentationStyle = .none
automaticMigrationViewController = UINavigationController(rootViewController: migrateVC)
self.addChildViewController(automaticMigrationViewController!)
migrateVC.viewDidLoad()
if let zomMigrate = migrateVC as? ZomAccountMigrationViewController {
zomMigrate.useAutoMode = true
zomMigrate.autoDelegate = self
}
migrateVC.viewWillAppear(false)
migrateVC.loginButtonPressed(self)
}
public func startAssistedMigration() {
chatsViewController?.didPressStartMigrationButton(self)
}
@IBAction func migrationDoneButtonPressed(_ sender: AnyObject) {
chatsViewController?.migrationStep = 0
if let vc = self.automaticMigrationViewController {
vc.removeFromParentViewController()
}
self.automaticMigrationViewController = nil
}
public func automaticMigrationDone(error: Error?) {
chatsViewController?.migrationStep = 2
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let migrationViewController = segue.destination as? ZomMigrationInfoViewController {
migrationViewController.delegate = self
}
}
}
|
mpl-2.0
|
3c9b0e8591d61e03047725ba8115e192
| 44.911184 | 225 | 0.645268 | 5.800914 | false | false | false | false |
bugnitude/SamplePDFViewer
|
SamplePDFViewer/PDFDocumentController.swift
|
1
|
3913
|
import Foundation
import UIKit
import QuartzCore
class PDFDocumentController {
// MARK: - Property
private var fileURL: URL
private var password: String?
private var pageBackgroundColor: UIColor
private var _document: CGPDFDocument?
private var document: CGPDFDocument? {
if self._document != nil {
return self._document
}
// Read PDF File
if let document = CGPDFDocument(self.fileURL as CFURL) {
if document.isEncrypted {
self.password?.withCString {
_ = document.unlockWithPassword($0)
}
}
if document.isUnlocked {
self._document = document
return document
}
}
return nil
}
private(set) var numberOfPages = 0
private let box: CGPDFBox = .cropBox
private var viewControllerCache = [Int: PDFPageViewController]()
// MARK: - Initializer
init?(fileURL: URL, password: String?, pageBackgroundColor: UIColor) {
self.fileURL = fileURL
self.password = password
self.pageBackgroundColor = pageBackgroundColor
if let document = self.document {
let numberOfPages = document.numberOfPages
if numberOfPages > 0 {
self.numberOfPages = numberOfPages
NotificationCenter.default.addObserver(self, selector: #selector(handleMemoryWarning), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
return
}
}
return nil
}
// MARK: - Deinitializer
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Notification Handler
@objc func handleMemoryWarning(notification: Notification) {
// Remove Recreatable Resources
self._document = nil
self.clearCache()
}
// MARK: - Page Size
var maxPageSize: CGSize {
var maxPageSize = CGSize.zero
for pageNumber in 1...self.numberOfPages {
if let page = self.document!.page(at: pageNumber) {
let pageSize = page.size(for: self.box)
maxPageSize.width = max(maxPageSize.width, pageSize.width)
maxPageSize.height = max(maxPageSize.height, pageSize.height)
}
}
return maxPageSize
}
// MARK: - Get PDF Page View Controller
func pageViewController(at pageNumber: Int) -> PDFPageViewController? {
// Manage Cache
let numberOfCachesInOneDirection = 4
let numberOfCachesInOneDirectionToCreate = numberOfCachesInOneDirection - 1
let minCachePageNumber = pageNumber - numberOfCachesInOneDirection > 1 ? pageNumber - numberOfCachesInOneDirection : 1
let maxCachePageNumber = pageNumber + numberOfCachesInOneDirection < self.numberOfPages ? pageNumber + numberOfCachesInOneDirection : self.numberOfPages
var newViewControllerCache = [Int: PDFPageViewController]()
for cache in self.viewControllerCache {
if cache.key >= minCachePageNumber && cache.key <= maxCachePageNumber {
newViewControllerCache[cache.key] = cache.value
}
}
// Instantiate Uncached PDF Page View Controllers
let minCachePageNumberToCreate = pageNumber - numberOfCachesInOneDirectionToCreate > 1 ? pageNumber - numberOfCachesInOneDirectionToCreate : 1
let maxCachePageNumberToCreate = pageNumber + numberOfCachesInOneDirectionToCreate < self.numberOfPages ? pageNumber + numberOfCachesInOneDirectionToCreate : self.numberOfPages
let pageNumbers = Array(minCachePageNumberToCreate ... maxCachePageNumberToCreate).sorted { abs($0 - pageNumber) < abs($1 - pageNumber) }
for pageNumber in pageNumbers {
if newViewControllerCache[pageNumber] == nil {
newViewControllerCache[pageNumber] = PDFPageViewController(page: self.document!.page(at: pageNumber), box: self.box, backgroundColor: self.pageBackgroundColor)
}
}
// Set New Cache
self.viewControllerCache = newViewControllerCache
// Return Page View Controller
return self.viewControllerCache[pageNumber]
}
var emptyPageViewController: PDFPageViewController {
return PDFPageViewController(page: nil, box: self.box, backgroundColor: UIColor.clear)
}
// MARK: - Clear Cache
func clearCache() {
self.viewControllerCache = [:]
}
}
|
mit
|
d2ec2c01491d8d35ddc7bd276be41891
| 31.07377 | 178 | 0.748275 | 4.050725 | false | false | false | false |
stephentyrone/swift
|
test/type/opaque.swift
|
3
|
15388
|
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify %s
protocol P {
func paul()
mutating func priscilla()
}
protocol Q { func quinn() }
extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} }
extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} }
extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} }
class C {}
class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {} }
let property: some P = 1
let deflessLet: some P // expected-error{{has no initializer}}
var deflessVar: some P // expected-error{{has no initializer}}
struct GenericProperty<T: P> {
var x: T
var property: some P {
return x
}
}
let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}}
var computedProperty: some P {
get { return 1 }
set { _ = newValue + 1 } // expected-error{{cannot convert value of type 'some P' to expected argument type 'Int'}}
}
struct SubscriptTest {
subscript(_ x: Int) -> some P {
return x
}
}
func bar() -> some P {
return 1
}
func bas() -> some P & Q {
return 1
}
func zim() -> some C {
return D()
}
func zang() -> some C & P & Q {
return D()
}
func zung() -> some AnyObject {
return D()
}
func zoop() -> some Any {
return D()
}
func zup() -> some Any & P {
return D()
}
func zip() -> some AnyObject & P {
return D()
}
func zorp() -> some Any & C & P {
return D()
}
func zlop() -> some C & AnyObject & P {
return D()
}
// Don't allow opaque types to propagate by inference into other global decls'
// types
struct Test {
let inferredOpaque = bar() // expected-error{{inferred type}}
let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}}
let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}}
}
//let zingle = {() -> some P in 1 } // FIXME ex/pected-error{{'some' types are only implemented}}
// Invalid positions
typealias Foo = some P // expected-error{{'some' types are only implemented}}
func blibble(blobble: some P) {} // expected-error{{'some' types are only implemented}}
let blubble: () -> some P = { 1 } // expected-error{{'some' types are only implemented}}
func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}}
func blab() -> (P, some Q) { return (1, 2) } // expected-error{{'some' types are only implemented}}
func blob() -> (some P) -> P { return { $0 } } // expected-error{{'some' types are only implemented}}
func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only implemented}}
func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only implemented}} expected-error{{cannot convert}}
protocol OP: some P {} // expected-error{{'some' types are only implemented}}
func foo() -> some P {
let x = (some P).self // expected-error*{{}}
return 1
}
// Invalid constraints
let zug: some Int = 1 // FIXME expected-error{{must specify only}}
let zwang: some () = () // FIXME expected-error{{must specify only}}
let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}}
// Type-checking of expressions of opaque type
func alice() -> some P { return 1 }
func bob() -> some P { return 1 }
func grace<T: P>(_ x: T) -> some P { return x }
func typeIdentity() {
do {
var a = alice()
a = alice()
a = bob() // expected-error{{}}
a = grace(1) // expected-error{{}}
a = grace("two") // expected-error{{}}
}
do {
var af = alice
af = alice
af = bob // expected-error{{}}
af = grace // expected-error{{generic parameter 'T' could not be inferred}}
// expected-error@-1 {{cannot assign value of type '(T) -> some P' to type '() -> some P'}}
}
do {
var b = bob()
b = alice() // expected-error{{}}
b = bob()
b = grace(1) // expected-error{{}}
b = grace("two") // expected-error{{}}
}
do {
var gi = grace(1)
gi = alice() // expected-error{{}}
gi = bob() // expected-error{{}}
gi = grace(2)
gi = grace("three") // expected-error{{}}
}
do {
var gs = grace("one")
gs = alice() // expected-error{{}}
gs = bob() // expected-error{{}}
gs = grace(2) // expected-error{{}}
gs = grace("three")
}
// The opaque type should conform to its constraining protocols
do {
let gs = grace("one")
var ggs = grace(gs)
ggs = grace(gs)
}
// The opaque type should expose the members implied by its protocol
// constraints
do {
var a = alice()
a.paul()
a.priscilla()
}
}
func recursion(x: Int) -> some P {
if x == 0 {
return 0
}
return recursion(x: x - 1)
}
func noReturnStmts() -> some P {} // expected-error {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}}
func returnUninhabited() -> some P { // expected-note {{opaque return type declared here}}
fatalError() // expected-error{{return type of global function 'returnUninhabited()' requires that 'Never' conform to 'P'}}
}
func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}}
if x {
return y // expected-note{{underlying type 'Int'}}
} else {
return z // expected-note{{underlying type 'String'}}
}
}
var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}}
if true {
return 0 // expected-note{{underlying type 'Int'}}
} else {
return "" // expected-note{{underlying type 'String'}}
}
}
struct MismatchedReturnTypesSubscript {
subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}}
if x {
return y // expected-note{{underlying type 'Int'}}
} else {
return z // expected-note{{underlying type 'String'}}
}
}
}
func jan() -> some P {
return [marcia(), marcia(), marcia()]
}
func marcia() -> some P {
return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}}
}
protocol R {
associatedtype S: P, Q // expected-note*{{}}
func r_out() -> S
func r_in(_: S)
}
extension Int: R {
func r_out() -> String {
return ""
}
func r_in(_: String) {}
}
func candace() -> some R {
return 0
}
func doug() -> some R {
return 0
}
func gary<T: R>(_ x: T) -> some R {
return x
}
func sameType<T>(_: T, _: T) {}
func associatedTypeIdentity() {
let c = candace()
let d = doug()
var cr = c.r_out()
cr = candace().r_out()
cr = doug().r_out() // expected-error{{}}
var dr = d.r_out()
dr = candace().r_out() // expected-error{{}}
dr = doug().r_out()
c.r_in(cr)
c.r_in(c.r_out())
c.r_in(dr) // expected-error{{}}
c.r_in(d.r_out()) // expected-error{{}}
d.r_in(cr) // expected-error{{}}
d.r_in(c.r_out()) // expected-error{{}}
d.r_in(dr)
d.r_in(d.r_out())
cr.paul()
cr.priscilla()
cr.quinn()
dr.paul()
dr.priscilla()
dr.quinn()
sameType(cr, c.r_out())
sameType(dr, d.r_out())
sameType(cr, dr) // expected-error {{conflicting arguments to generic parameter 'T' ('(some R).S' (associated type of protocol 'R') vs. '(some R).S' (associated type of protocol 'R'))}}
sameType(gary(candace()).r_out(), gary(candace()).r_out())
sameType(gary(doug()).r_out(), gary(doug()).r_out())
// TODO(diagnostics): This is not great but the problem comes from the way solver discovers and attempts bindings, if we could detect that
// `(some R).S` from first reference to `gary()` in incosistent with the second one based on the parent type of `S` it would be much easier to diagnose.
sameType(gary(doug()).r_out(), gary(candace()).r_out())
// expected-error@-1:3 {{conflicting arguments to generic parameter 'T' ('(some R).S' (associated type of protocol 'R') vs. '(some R).S' (associated type of protocol 'R'))}}
// expected-error@-2:12 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}}
// expected-error@-3:34 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}}
}
func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}}
func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}}
func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}}
func redeclaration() -> P { return 0 }
func redeclaration() -> Any { return 0 }
var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}}
var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}}
var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}}
var redeclaredProp: P { return 0 } // expected-error{{redeclaration}}
struct RedeclarationTest {
func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}}
func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}}
func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}}
func redeclaration() -> P { return 0 }
var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}}
var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}}
var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}}
var redeclaredProp: P { return 0 } // expected-error{{redeclaration}}
subscript(redeclared _: Int) -> some P { return 0 } // expected-note 2{{previously declared}}
subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}}
subscript(redeclared _: Int) -> some Q { return 0 } // expected-error{{redeclaration}}
subscript(redeclared _: Int) -> P { return 0 }
}
func diagnose_requirement_failures() {
struct S {
var foo: some P { return S() } // expected-note {{declared here}}
// expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}}
subscript(_: Int) -> some P { // expected-note {{declared here}}
return S()
// expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}}
}
func bar() -> some P { // expected-note {{declared here}}
return S()
// expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}}
}
static func baz(x: String) -> some P { // expected-note {{declared here}}
return S()
// expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}}
}
}
func fn() -> some P { // expected-note {{declared here}}
return S()
// expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}}
}
}
func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}}
return 42 as Double
// expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}}
}
func recursive_func_is_invalid_opaque() {
func rec(x: Int) -> some P {
// expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}}
if x == 0 {
return rec(x: 0)
}
return rec(x: x - 1)
}
}
func closure() -> some P {
_ = {
return "test"
}
return 42
}
protocol HasAssocType {
associatedtype Assoc
func assoc() -> Assoc
}
struct GenericWithOpaqueAssoc<T>: HasAssocType {
func assoc() -> some Any { return 0 }
}
struct OtherGeneric<X, Y, Z> {
var x: GenericWithOpaqueAssoc<X>.Assoc
var y: GenericWithOpaqueAssoc<Y>.Assoc
var z: GenericWithOpaqueAssoc<Z>.Assoc
}
protocol P_51641323 {
associatedtype T
var foo: Self.T { get }
}
func rdar_51641323() {
struct Foo: P_51641323 {
var foo: some P_51641323 { // expected-note {{required by opaque return type of property 'foo'}}
{} // expected-error {{type '() -> ()' cannot conform to 'P_51641323'; only struct/enum/class types can conform to protocols}}
}
}
}
// Protocol requirements cannot have opaque return types
protocol OpaqueProtocolRequirement {
// expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{20-26=<#AssocType#>}}
func method() -> some P
// expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{13-19=<#AssocType#>}}
var prop: some P { get }
// expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{18-24=<#AssocType#>}}
subscript() -> some P { get }
}
func testCoercionDiagnostics() {
var opaque = foo()
opaque = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}}
opaque = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}}
opaque = computedProperty // expected-error {{cannot assign value of type 'some P' (type of 'computedProperty') to type 'some P' (result of 'foo()')}} {{none}}
opaque = SubscriptTest()[0] // expected-error {{cannot assign value of type 'some P' (result of 'SubscriptTest.subscript(_:)') to type 'some P' (result of 'foo()')}} {{none}}
var opaqueOpt: Optional = opaque
opaqueOpt = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}}
opaqueOpt = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}}
}
var globalVar: some P = 17
let globalLet: some P = 38
struct Foo {
static var staticVar: some P = 17
static let staticLet: some P = 38
var instanceVar: some P = 17
let instanceLet: some P = 38
}
protocol P_52528543 {
init()
associatedtype A: Q_52528543
var a: A { get }
}
protocol Q_52528543 {
associatedtype B // expected-note 2 {{associated type 'B'}}
var b: B { get }
}
extension P_52528543 {
func frob(a_b: A.B) -> some P_52528543 { return self }
}
func foo<T: P_52528543>(x: T) -> some P_52528543 {
return x
.frob(a_b: x.a.b)
.frob(a_b: x.a.b) // expected-error {{cannot convert}}
}
struct GenericFoo<T: P_52528543, U: P_52528543> {
let x: some P_52528543 = T()
let y: some P_52528543 = U()
mutating func bump() {
var xab = f_52528543(x: x)
xab = f_52528543(x: y) // expected-error{{cannot assign}}
}
}
func f_52528543<T: P_52528543>(x: T) -> T.A.B { return x.a.b }
func opaque_52528543<T: P_52528543>(x: T) -> some P_52528543 { return x }
func invoke_52528543<T: P_52528543, U: P_52528543>(x: T, y: U) {
let x2 = opaque_52528543(x: x)
let y2 = opaque_52528543(x: y)
var xab = f_52528543(x: x2)
xab = f_52528543(x: y2) // expected-error{{cannot assign}}
}
protocol Proto {}
struct I : Proto {}
dynamic func foo<S>(_ s: S) -> some Proto {
return I()
}
@_dynamicReplacement(for: foo)
func foo_repl<S>(_ s: S) -> some Proto {
return I()
}
protocol SomeProtocolA {}
protocol SomeProtocolB {}
struct SomeStructC: SomeProtocolA, SomeProtocolB {}
let someProperty: SomeProtocolA & some SomeProtocolB = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{35-40=}}{{19-19=some }}
|
apache-2.0
|
1caee3012f419f366baa7e90955acb9c
| 30.597536 | 187 | 0.634715 | 3.381235 | false | false | false | false |
rakaramos/StarButton
|
StarBounce/StarButton.swift
|
1
|
10786
|
//
// StatButton.swift
// FavoriteStar
//
// Created by Rafael Machado on 14/11/14.
// Copyright (c) 2014 Rafael Machado. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class StarButton: UIButton, CAAnimationDelegate {
fileprivate var starShape: CAShapeLayer!
fileprivate var outerRingShape: CAShapeLayer!
fileprivate var fillRingShape: CAShapeLayer!
fileprivate let starKey = "FAVANIMKEY"
fileprivate let favoriteKey = "FAVORITE"
fileprivate let notFavoriteKey = "NOTFAVORITE"
@IBInspectable
var lineWidth: CGFloat = 1 {
didSet {
updateLayerProperties()
}
}
@IBInspectable
var favoriteColor: UIColor = UIColor(hex:"eecd34") {
didSet {
updateLayerProperties()
}
}
@IBInspectable
var notFavoriteColor: UIColor = UIColor(hex:"9e9b9b") {
didSet {
updateLayerProperties()
}
}
@IBInspectable
var starFavoriteColor: UIColor = UIColor(hex:"9e9b9b") {
didSet {
updateLayerProperties()
}
}
var isFavorite: Bool = false {
didSet {
if self.isFavorite {
favorite()
} else {
notFavorite()
}
}
}
fileprivate func updateLayerProperties() {
if fillRingShape != nil {
fillRingShape.fillColor = favoriteColor.cgColor
}
if outerRingShape != nil {
outerRingShape.lineWidth = lineWidth
outerRingShape.strokeColor = notFavoriteColor.cgColor
}
if starShape != nil {
if isFavorite {
starShape.fillColor = starFavoriteColor.cgColor
} else {
starShape.fillColor = notFavoriteColor.cgColor
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
createLayersIfNeeded()
updateLayerProperties()
}
fileprivate func createLayersIfNeeded() {
if fillRingShape == nil {
fillRingShape = CAShapeLayer()
fillRingShape.path = Paths.circle(frameWithInset())
fillRingShape.bounds = (fillRingShape.path?.boundingBox)!
fillRingShape.fillColor = favoriteColor.cgColor
fillRingShape.lineWidth = lineWidth
fillRingShape.position = CGPoint(x: fillRingShape.bounds.width/2, y: fillRingShape.bounds.height/2)
fillRingShape.transform = CATransform3DMakeScale(0.2, 0.2, 0.2)
fillRingShape.opacity = 0
self.layer.addSublayer(fillRingShape)
}
if outerRingShape == nil {
outerRingShape = CAShapeLayer()
outerRingShape.path = Paths.circle(frameWithInset())
outerRingShape.bounds = frameWithInset()
outerRingShape.lineWidth = lineWidth
outerRingShape.strokeColor = notFavoriteColor.cgColor
outerRingShape.fillColor = UIColor.clear.cgColor
outerRingShape.position = CGPoint(x: self.bounds.width/2, y: self.bounds.height/2)
outerRingShape.transform = CATransform3DIdentity
outerRingShape.opacity = 0.5
self.layer.addSublayer(outerRingShape)
}
if starShape == nil {
var starFrame = self.bounds
starFrame.size.width = starFrame.width/2.5
starFrame.size.height = starFrame.height/2.5
starShape = CAShapeLayer()
starShape.path = CGPath.rescaleForFrame(path: Paths.star, frame: starFrame)
starShape.bounds = (starShape.path?.boundingBoxOfPath)!
starShape.fillColor = notFavoriteColor.cgColor
starShape.position = CGPoint(x: (outerRingShape.path?.boundingBox.width)!/2,
y: (outerRingShape.path?.boundingBox.height)!/2)
starShape.transform = CATransform3DIdentity
starShape.opacity = 0.5
self.layer.addSublayer(starShape)
}
}
fileprivate func frameWithInset() -> CGRect {
return self.bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2)
}
fileprivate func notFavorite() {
let starFillColor = CABasicAnimation(keyPath: "fillColor")
starFillColor.toValue = notFavoriteColor.cgColor
starFillColor.duration = 0.3
let starOpacity = CABasicAnimation(keyPath: "opacity")
starOpacity.toValue = 0.5
starOpacity.duration = 0.3
let starGroup = CAAnimationGroup()
starGroup.animations = [starFillColor, starOpacity]
starShape.add(starGroup, forKey: nil)
starShape.fillColor = notFavoriteColor.cgColor
starShape.opacity = 0.5
let fillCircle = CABasicAnimation(keyPath: "opacity")
fillCircle.toValue = 0
fillCircle.duration = 0.3
fillCircle.setValue(notFavoriteKey, forKey: starKey)
fillCircle.delegate = self
fillRingShape.add(fillCircle, forKey: nil)
fillRingShape.opacity = 0
let outerCircle = CABasicAnimation(keyPath: "opacity")
outerCircle.toValue = 0.5
outerCircle.duration = 0.3
outerRingShape.add(outerCircle, forKey: nil)
outerRingShape.opacity = 0.5
}
fileprivate func favorite() {
var starGoUp = CATransform3DIdentity
starGoUp = CATransform3DScale(starGoUp, 1.5, 1.5, 1.5)
var starGoDown = CATransform3DIdentity
starGoDown = CATransform3DScale(starGoDown, 0.01, 0.01, 0.01)
let starKeyFrames = CAKeyframeAnimation(keyPath: "transform")
starKeyFrames.values = [NSValue(caTransform3D:CATransform3DIdentity),
NSValue(caTransform3D:starGoUp),
NSValue(caTransform3D:starGoDown)]
starKeyFrames.keyTimes = [0.0, 0.4, 0.6]
starKeyFrames.duration = 0.4
starKeyFrames.beginTime = CACurrentMediaTime() + 0.05
starKeyFrames.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
starKeyFrames.fillMode = kCAFillModeBackwards
starKeyFrames.setValue(favoriteKey, forKey: starKey)
starKeyFrames.delegate = self
starShape.add(starKeyFrames, forKey: favoriteKey)
starShape.transform = starGoDown
var grayGoUp = CATransform3DIdentity
grayGoUp = CATransform3DScale(grayGoUp, 1.5, 1.5, 1.5)
var grayGoDown = CATransform3DIdentity
grayGoDown = CATransform3DScale(grayGoDown, 0.01, 0.01, 0.01)
let outerCircleAnimation = CAKeyframeAnimation(keyPath: "transform")
outerCircleAnimation.values = [NSValue(caTransform3D:CATransform3DIdentity),
NSValue(caTransform3D:grayGoUp),
NSValue(caTransform3D:grayGoDown)]
outerCircleAnimation.keyTimes = [0.0, 0.4, 0.6]
outerCircleAnimation.duration = 0.4
outerCircleAnimation.beginTime = CACurrentMediaTime() + 0.01
outerCircleAnimation.fillMode = kCAFillModeBackwards
outerCircleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
outerRingShape.add(outerCircleAnimation, forKey: "Gray circle Animation")
outerRingShape.transform = grayGoDown
var favoriteFillGrow = CATransform3DIdentity
favoriteFillGrow = CATransform3DScale(favoriteFillGrow, 1.5, 1.5, 1.5)
let fillCircleAnimation = CAKeyframeAnimation(keyPath: "transform")
fillCircleAnimation.values = [NSValue(caTransform3D:fillRingShape.transform),
NSValue(caTransform3D:favoriteFillGrow),
NSValue(caTransform3D:CATransform3DIdentity)]
fillCircleAnimation.keyTimes = [0.0, 0.4, 0.6]
fillCircleAnimation.duration = 0.4
fillCircleAnimation.beginTime = CACurrentMediaTime() + 0.22
fillCircleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
fillCircleAnimation.fillMode = kCAFillModeBackwards
let favoriteFillOpacity = CABasicAnimation(keyPath: "opacity")
favoriteFillOpacity.toValue = 1
favoriteFillOpacity.duration = 1
favoriteFillOpacity.beginTime = CACurrentMediaTime()
favoriteFillOpacity.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
favoriteFillOpacity.fillMode = kCAFillModeBackwards
fillRingShape.add(favoriteFillOpacity, forKey: "Show fill circle")
fillRingShape.add(fillCircleAnimation, forKey: "fill circle Animation")
fillRingShape.transform = CATransform3DIdentity
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if let key = anim.value(forKey: starKey) as? String {
switch key {
case favoriteKey:
endFavorite()
case notFavoriteKey:
prepareForFavorite()
default:
break
}
}
enableTouch()
}
fileprivate func endFavorite() {
executeWithoutActions {
self.starShape.fillColor = self.starFavoriteColor.cgColor
self.starShape.opacity = 1
self.fillRingShape.opacity = 1
self.outerRingShape.transform = CATransform3DIdentity
self.outerRingShape.opacity = 0
}
var starGoUp = CATransform3DIdentity
starGoUp = CATransform3DScale(starGoUp, 2, 2, 2)
let starKeyFrames = CAKeyframeAnimation(keyPath: "transform")
starKeyFrames.values = [NSValue(caTransform3D: starShape.transform),
NSValue(caTransform3D:starGoUp),
NSValue(caTransform3D:CATransform3DIdentity)]
starKeyFrames.keyTimes = [0.0, 0.4, 0.6]
starKeyFrames.duration = 0.2
starKeyFrames.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
starShape.add(starKeyFrames, forKey: nil)
starShape.transform = CATransform3DIdentity
}
fileprivate func prepareForFavorite() {
executeWithoutActions {
self.fillRingShape.opacity = 0
self.fillRingShape.transform = CATransform3DMakeScale(0.2, 0.2, 0.2)
}
}
fileprivate func executeWithoutActions(_ closure: () -> Void) {
CATransaction.begin()
CATransaction.setDisableActions(true)
closure()
CATransaction.commit()
}
func animationDidStart(_ anim: CAAnimation) {
disableTouch()
}
fileprivate func disableTouch() {
self.isUserInteractionEnabled = false
}
fileprivate func enableTouch() {
self.isUserInteractionEnabled = true
}
}
|
mit
|
fa9c2296c9db51c380c111a3ac5a7a06
| 35.938356 | 111 | 0.64046 | 4.77891 | false | false | false | false |
zybug/firefox-ios
|
Sync/StorageClient.swift
|
1
|
26076
|
/* 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 Alamofire
import Shared
import Account
import XCGLogger
private let log = Logger.syncLogger
// Not an error that indicates a server problem, but merely an
// error that encloses a StorageResponse.
public class StorageResponseError<T>: MaybeErrorType {
public let response: StorageResponse<T>
public init(_ response: StorageResponse<T>) {
self.response = response
}
public var description: String {
return "Error."
}
}
public class RequestError: MaybeErrorType {
public var description: String {
return "Request error."
}
}
public class BadRequestError<T>: StorageResponseError<T> {
public let request: NSURLRequest?
public init(request: NSURLRequest?, response: StorageResponse<T>) {
self.request = request
super.init(response)
}
override public var description: String {
return "Bad request."
}
}
public class ServerError<T>: StorageResponseError<T> {
override public var description: String {
return "Server error."
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class NotFound<T>: StorageResponseError<T> {
override public var description: String {
return "Not found. (\(T.self))"
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class RecordParseError: MaybeErrorType {
public var description: String {
return "Failed to parse record."
}
}
public class MalformedMetaGlobalError: MaybeErrorType {
public var description: String {
return "Supplied meta/global for upload did not serialize to valid JSON."
}
}
/**
* Raised when the storage client is refusing to make a request due to a known
* server backoff.
* If you want to bypass this, remove the backoff from the BackoffStorage that
* the storage client is using.
*/
public class ServerInBackoffError: MaybeErrorType {
private let until: Timestamp
public var description: String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
let s = formatter.stringFromDate(NSDate.fromTimestamp(self.until))
return "Server in backoff until \(s)."
}
public init(until: Timestamp) {
self.until = until
}
}
// Returns milliseconds. Handles decimals.
private func optionalSecondsHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
if let timestamp = decimalSecondsStringToTimestamp(val) {
return timestamp
}
}
if let seconds: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(seconds * 1000)
}
if let seconds: NSNumber = input as? NSNumber {
// Who knows.
return seconds.unsignedLongLongValue * 1000
}
return nil
}
private func optionalIntegerHeader(input: AnyObject?) -> Int64? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Int64(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.longLongValue
}
return nil
}
private func optionalUIntegerHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanUnsignedLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.unsignedLongLongValue
}
return nil
}
public enum SortOption: String {
case Newest = "newest"
case Index = "index"
}
public struct ResponseMetadata {
public let status: Int
public let alert: String?
public let nextOffset: String?
public let records: UInt64?
public let quotaRemaining: Int64?
public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request.
public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp.
public let backoffMilliseconds: UInt64?
public let retryAfterMilliseconds: UInt64?
public init(response: NSHTTPURLResponse) {
self.init(status: response.statusCode, headers: response.allHeaderFields)
}
init(status: Int, headers: [NSObject : AnyObject]) {
self.status = status
alert = headers["X-Weave-Alert"] as? String
nextOffset = headers["X-Weave-Next-Offset"] as? String
records = optionalUIntegerHeader(headers["X-Weave-Records"])
quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"])
timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"]) ?? 0
lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"])
backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"]) ??
optionalSecondsHeader(headers["X-Backoff"])
retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"])
}
}
public struct StorageResponse<T> {
public let value: T
public let metadata: ResponseMetadata
init(value: T, metadata: ResponseMetadata) {
self.value = value
self.metadata = metadata
}
init(value: T, response: NSHTTPURLResponse) {
self.value = value
self.metadata = ResponseMetadata(response: response)
}
}
public struct POSTResult {
public let modified: Timestamp
public let success: [GUID]
public let failed: [GUID: [String]]
public static func fromJSON(json: JSON) -> POSTResult? {
if json.isError {
return nil
}
if let mDecimalSeconds = json["modified"].asDouble,
let s = json["success"].asArray,
let f = json["failed"].asDictionary {
var failed = false
let asStringOrFail: JSON -> String = { $0.asString ?? { failed = true; return "" }() }
let asArrOrFail: JSON -> [String] = { $0.asArray?.map(asStringOrFail) ?? { failed = true; return [] }() }
// That's the basic structure. Now let's transform the contents.
let successGUIDs = s.map(asStringOrFail)
if failed {
return nil
}
let failedGUIDs = mapValues(f, f: asArrOrFail)
if failed {
return nil
}
let msec = Timestamp(1000 * mDecimalSeconds)
return POSTResult(modified: msec, success: successGUIDs, failed: failedGUIDs)
}
return nil
}
}
public typealias Authorizer = (NSMutableURLRequest) -> NSMutableURLRequest
public typealias ResponseHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void
// TODO: don't be so naïve. Use a combination of uptime and wall clock time.
public protocol BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? { get set }
func clearServerBackoff()
func isInBackoff(now: Timestamp) -> Timestamp? // Returns 'until' for convenience.
}
// Don't forget to batch downloads.
public class Sync15StorageClient {
private let authorizer: Authorizer
private let serverURI: NSURL
var backoff: BackoffStorage
let workQueue: dispatch_queue_t
let resultQueue: dispatch_queue_t
public init(token: TokenServerToken, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
// This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain.
self.serverURI = NSURL(string: token.api_endpoint)!
self.authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
}
public init(serverURI: NSURL, authorizer: Authorizer, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.serverURI = serverURI
self.authorizer = authorizer
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
}
func updateBackoffFromResponse<T>(response: StorageResponse<T>) {
// N.B., we would not have made this request if a backoff were set, so
// we can safely avoid doing the write if there's no backoff in the
// response.
// This logic will have to change if we ever invalidate that assumption.
if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds {
log.info("Backing off for \(ms)ms.")
self.backoff.serverBackoffUntilLocalTimestamp = ms + NSDate.now()
}
}
func errorWrap<T>(deferred: Deferred<Maybe<T>>, handler: ResponseHandler) -> ResponseHandler {
return { (request, response, result) in
log.verbose("Response is \(response).")
/**
* Returns true if handled.
*/
func failFromResponse(response: NSHTTPURLResponse?) -> Bool {
guard let response = response else {
// TODO: better error.
log.error("No response")
let result = Maybe<T>(failure: RecordParseError())
deferred.fill(result)
return true
}
log.debug("Status code: \(response.statusCode).")
let storageResponse = StorageResponse(value: response, metadata: ResponseMetadata(response: response))
self.updateBackoffFromResponse(storageResponse)
if response.statusCode >= 500 {
log.debug("ServerError.")
let result = Maybe<T>(failure: ServerError(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode == 404 {
log.debug("NotFound<\(T.self)>.")
let result = Maybe<T>(failure: NotFound(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode >= 400 {
log.debug("BadRequestError.")
let result = Maybe<T>(failure: BadRequestError(request: request, response: storageResponse))
deferred.fill(result)
return true
}
return false
}
// Check for an error from the request processor.
if result.isFailure {
log.error("Response: \(response?.statusCode ?? 0). Got error \(result.error).")
// If we got one, we don't want to hit the response nil case above and
// return a RecordParseError, because a RequestError is more fitting.
if let response = response {
if failFromResponse(response) {
log.error("This was a failure response. Filled specific error type.")
return
}
}
log.error("Filling generic RequestError.")
deferred.fill(Maybe<T>(failure: RequestError()))
return
}
if failFromResponse(response) {
return
}
handler(request, response, result)
}
}
lazy private var alamofire: Alamofire.Manager = {
let ua = UserAgent.syncUserAgent
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
return Alamofire.Manager.managerWithUserAgent(ua, configuration: configuration)
}()
func requestGET(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.GET.rawValue
req.setValue("application/json", forHTTPHeaderField: "Accept")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
.validate(contentType: ["application/json"])
}
func requestDELETE(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.DELETE.rawValue
req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestWrite(url: NSURL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = method
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
let authorized: NSMutableURLRequest = self.authorizer(req)
if let ifUnmodifiedSince = ifUnmodifiedSince {
req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since")
}
req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)!
return alamofire.request(authorized)
}
func requestPUT(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.PUT.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.POST.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request {
let body = body.map { $0.toString(false) }.joinWithSeparator("\n")
return self.requestWrite(url, method: Method.POST.rawValue, body: body, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince)
}
/**
* Returns true and fills the provided Deferred if our state shows that we're in backoff.
* Returns false otherwise.
*/
private func checkBackoff<T>(deferred: Deferred<Maybe<T>>) -> Bool {
if let until = self.backoff.isInBackoff(NSDate.now()) {
deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until)))
return true
}
return false
}
private func doOp<T>(op: (NSURL) -> Request, path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = op(self.serverURI.URLByAppendingPathComponent(path))
let handler = self.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
if let v = f(json) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
req.responseParsedJSON(true, completionHandler: handler)
return deferred
}
// Sync storage responds with a plain timestamp to a PUT, not with a JSON body.
private func putResource<T>(path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let url = self.serverURI.URLByAppendingPathComponent(path)
return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser)
}
private func putResource<T>(URL: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince)
let handler = self.errorWrap(deferred) { (_, response, result) in
if let data = result.value as? String {
if let v = parser(data) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
let stringHandler = { (a: NSURLRequest?, b: NSHTTPURLResponse?, c: Result<String>) in
return handler(a, b, c.isSuccess ? Result.Success(c.value!) : Result.Failure(c.data, c.error!))
}
req.responseString(encoding: nil, completionHandler: stringHandler)
return deferred
}
private func getResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestGET, path: path, f: f)
}
private func deleteResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestDELETE, path: path, f: f)
}
func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> {
return getResource("info/collections", f: InfoCollections.fromJSON)
}
func getMetaGlobal() -> Deferred<Maybe<StorageResponse<GlobalEnvelope>>> {
return getResource("storage/meta/global", f: { GlobalEnvelope($0) })
}
func uploadMetaGlobal(metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let payload = metaGlobal.toPayload()
if payload.isError {
return Deferred(value: Maybe(failure: MalformedMetaGlobalError()))
}
// TODO finish this!
let record: JSON = JSON(["payload": payload, "id": "global"])
return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> {
// In Sync 1.5 it's preferred that we delete the root, not /storage.
return deleteResource("", f: { $0 })
}
// TODO: it would be convenient to have the storage client manage Keys,
// but of course we need to use a different set of keys to fetch crypto/keys
// itself.
func clientForCollection<T: CleartextPayloadJSON>(collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> {
let storage = self.serverURI.URLByAppendingPathComponent("storage", isDirectory: true)
return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter)
}
}
/**
* We'd love to nest this in the overall storage client, but Swift
* forbids the nesting of a generic class inside another class.
*/
public class Sync15CollectionClient<T: CleartextPayloadJSON> {
private let client: Sync15StorageClient
private let encrypter: RecordEncrypter<T>
private let collectionURI: NSURL
private let collectionQueue = dispatch_queue_create("com.mozilla.sync.collectionclient", DISPATCH_QUEUE_SERIAL)
init(client: Sync15StorageClient, serverURI: NSURL, collection: String, encrypter: RecordEncrypter<T>) {
self.client = client
self.encrypter = encrypter
self.collectionURI = serverURI.URLByAppendingPathComponent(collection, isDirectory: false)
}
private func uriForRecord(guid: String) -> NSURL {
return self.collectionURI.URLByAppendingPathComponent(guid)
}
public func post(records: [Record<T>], ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<POSTResult>>> {
let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
// TODO: charset
// TODO: if any of these fail, we should do _something_. Right now we just ignore them.
let json = optFilter(records.map(self.encrypter.serializer))
let req = client.requestPOST(self.collectionURI, body: json, ifUnmodifiedSince: nil)
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON,
let result = POSTResult.fromJSON(json) {
let storageResponse = StorageResponse(value: result, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
public func put(record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
if let body = self.encrypter.serializer(record) {
log.debug("Body is \(body)")
log.debug("Original record is \(record)")
return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
return deferMaybe(RecordParseError())
}
public func get(guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> {
let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(uriForRecord(guid))
req.responsePartialParsedJSON(queue:collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
let envelope = EnvelopeJSON(json)
let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
if let record = record {
let storageResponse = StorageResponse(value: record, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
}
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
/**
* Unlike every other Sync client, we use the application/json format for fetching
* multiple requests. The others use application/newlines. We don't want to write
* another Serializer, and we're loading everything into memory anyway.
*/
public func getSince(since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> {
let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue)
// Fills the Deferred for us.
if self.client.checkBackoff(deferred) {
return deferred
}
var params: [NSURLQueryItem] = [
NSURLQueryItem(name: "full", value: "1"),
]
if let offset = offset {
params.append(NSURLQueryItem(name: "offset", value: offset))
} else {
params.append(NSURLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)))
}
if let limit = limit {
params.append(NSURLQueryItem(name: "limit", value: "\(limit)"))
}
if let sort = sort {
params.append(NSURLQueryItem(name: "sort", value: sort.rawValue))
}
log.debug("Issuing GET with newer = \(since).")
let req = client.requestGET(self.collectionURI.withQueryParams(params))
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
log.debug("Response is \(response).")
guard let json: JSON = result.value as? JSON else {
log.warning("Non-JSON response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
guard let arr = json.asArray else {
log.warning("Non-array response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
func recordify(json: JSON) -> Record<T>? {
let envelope = EnvelopeJSON(json)
return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
}
let records = optFilter(arr.map(recordify))
let response = StorageResponse(value: records, response: response!)
deferred.fill(Maybe(success: response))
})
return deferred
}
}
|
mpl-2.0
|
fbec4a94065f642ce33e110ec9db1ec6
| 36.735166 | 180 | 0.633941 | 4.856584 | false | false | false | false |
tutao/tutanota
|
app-ios/tutanota/Sources/AppDelegate.swift
|
1
|
3771
|
import UIKit
@UIApplicationMain
class AppDelegate : UIResponder,
UIApplicationDelegate,
UNUserNotificationCenterDelegate {
var window: UIWindow?
private var pushTokenCallback: ResponseCallback<String>?
private let userPreferences = UserPreferenceFacade()
private var alarmManager: AlarmManager!
private var viewController: ViewController!
func registerForPushNotifications() async throws -> String {
#if targetEnvironment(simulator)
return ""
#else
return try await withCheckedThrowingContinuation { continuation in
UNUserNotificationCenter.current()
.requestAuthorization(
options: [.alert, .badge, .sound]) { granted, error in
if error == nil {
DispatchQueue.main.async {
self.pushTokenCallback = continuation.resume(with:)
UIApplication.shared.registerForRemoteNotifications()
}
} else {
continuation.resume(with: .failure(error!))
}
}
}
#endif
}
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?
) -> Bool {
TUTSLog("Start Tutanota \(String(describing: launchOptions))")
let keychainManager = KeychainManager(keyGenerator: KeyGenerator())
self.alarmManager = AlarmManager(keychainManager: keychainManager, userPreference: userPreferences)
self.window = UIWindow(frame: UIScreen.main.bounds)
let credentialsEncryption = IosNativeCredentialsFacade(keychainManager: keychainManager)
self.viewController = ViewController(
crypto: IosNativeCryptoFacade(),
themeManager: ThemeManager(),
keychainManager: keychainManager,
userPreferences: userPreferences,
alarmManager: self.alarmManager,
credentialsEncryption: credentialsEncryption,
blobUtils: BlobUtil()
)
self.window!.rootViewController = viewController
UNUserNotificationCenter.current().delegate = self
window!.makeKeyAndVisible()
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let callback = self.pushTokenCallback {
let stringToken = deviceTokenAsString(deviceToken: deviceToken)
callback(.success(stringToken!))
self.pushTokenCallback = nil
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
self.pushTokenCallback?(.failure(error))
self.pushTokenCallback = nil
}
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let apsDict = userInfo["aps"] as! Dictionary<String, Any>
TUTSLog("Received notification \(userInfo)")
let contentAvailable = apsDict["content-available"]
if contentAvailable as? Int == 1 {
self.alarmManager.fetchMissedNotifications { result in
TUTSLog("Fetched missed notificaiton after notification \(String(describing: result))")
switch result {
case .success():
completionHandler(.newData)
case .failure(_):
completionHandler(.failed)
}
}
}
}
}
fileprivate func deviceTokenAsString(deviceToken: Data) -> String? {
if deviceToken.isEmpty {
return nil
}
var result = ""
for byte in deviceToken {
result = result.appendingFormat("%02x", byte)
}
return result
}
|
gpl-3.0
|
9b8f1ac3ec064e90a7be84b3aacc2c6f
| 32.669643 | 118 | 0.698488 | 5.611607 | false | false | false | false |
tgyhlsb/RxSwiftExt
|
Source/RxSwift/cascade.swift
|
3
|
3658
|
//
// cascade.swift
// RxSwiftExtDemo
//
// Created by Florent Pillet on 17/04/16.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension Observable where Element : ObservableType {
public typealias T = Element.E
/**
Cascade through a sequence of observables: every observable that sends a `next` value becomes the "current"
observable (like in `switchLatest`), and the subscription to all previous observables in the sequence is disposed.
This allows subscribing to multiple observable sequences while irrevocably switching to the next when it starts emitting. If any of the
currently subscribed-to sequences errors, the error is propagated to the observer and the sequence terminates.
- parameter observables: a sequence of observables which will all be immediately subscribed to
- returns: An observable sequence that contains elements from the latest observable sequence that emitted elements
*/
public static func cascade<S : Sequence>(_ observables : S) -> Observable<T> where S.Iterator.Element == Element, S.Iterator.Element.E == T {
let flow = Array(observables)
if flow.isEmpty {
return Observable<T>.empty()
}
return Observable<T>.create { observer in
var current = 0, initialized = false
var subscriptions: [SerialDisposable?] = flow.map { _ in SerialDisposable() }
let lock = NSRecursiveLock()
lock.lock()
defer { lock.unlock() }
for i in 0 ..< flow.count {
let index = i
let disposable = flow[index].subscribe { event in
lock.lock()
defer { lock.unlock() }
switch event {
case .next(let element):
while current < index {
subscriptions[current]?.dispose()
subscriptions[current] = nil
current += 1
}
if index == current {
assert(subscriptions[index] != nil)
observer.onNext(element)
}
case .completed:
if index >= current {
if (initialized) {
subscriptions[index]?.dispose()
subscriptions[index] = nil
for next in current ..< subscriptions.count {
if subscriptions[next] != nil {
return
}
}
observer.onCompleted()
}
}
case .error(let error):
observer.onError(error)
}
}
if let serialDisposable = subscriptions[index] {
serialDisposable.disposable = disposable
} else {
disposable.dispose()
}
}
initialized = true
for i in 0 ..< flow.count {
if subscriptions[i] != nil {
return Disposables.create {
subscriptions.forEach { $0?.dispose() }
}
}
}
observer.onCompleted()
return Disposables.create()
}
}
}
extension ObservableType {
/**
Cascade through a sequence of observables: every observable that sends a `next` value becomes the "current"
observable (like in `switchLatest`), and the subscription to all previous observables in the sequence is disposed.
This allows subscribing to multiple observable sequences while irrevocably switching to the next when it starts emitting. If any of the
currently subscribed-to sequences errors, the error is propagated to the observer and the sequence terminates.
- parameter observables: a sequence of observables which will all be immediately subscribed to
- returns: An observable sequence that contains elements from the latest observable sequence that emitted elements
*/
public func cascade<S : Sequence>(_ next : S) -> Observable<E> where S.Iterator.Element == Self {
return Observable.cascade([self.asObservable()] + Array(next).map { $0.asObservable() })
}
}
|
mit
|
226dfe099362d85903aad127f5b8870d
| 29.991525 | 142 | 0.682527 | 4.237543 | false | false | false | false |
lotz84/__.swift
|
__.swift/Dictionaries/__Dictionaries.swift
|
1
|
3049
|
//
// __Dictionaries.swift
// __.swift
//
// Copyright (c) 2014 Tatsuya Hirose
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension __ {
/**
* Dictionaries Functions
*/
public class func invert<K, V>(dict: [K:V]) -> [V:K] {
var result : [V:K] = [:]
for (key, value) in dict {
result[value] = key
}
return result
}
public class func extend<K, V>(var dict: [K:V], to dictionaries: [K:V]...) -> [K:V] {
for item in dictionaries {
for (key, value) in item {
dict[key] = value
}
}
return dict
}
public class func pick<K, V>(from dict: [K:V], keys: K...) -> [K:V] {
var result : [K:V] = [:]
for key in keys {
if let value = dict[key] {
result[key] = value
}
}
return result
}
public class func omit<K, V>(var from dict: [K:V], keys: K...) -> [K:V] {
for key in keys {
dict.removeValueForKey(key)
}
return dict
}
public class func defaults<K, V>(var dict: [K:V], defaults: [K:V]...) -> [K:V] {
for option in defaults {
for key in option.keys {
if dict[key] == nil {
dict[key] = option[key]
}
}
}
return dict
}
public class func has<K, V>(dict: [K:V], key: K) -> Bool {
return dict[key] != nil
}
public class func property<K, V>(key: K)(dict: [K:V]) -> V? {
return dict[key]
}
public class func matches<K, V: Equatable>(attrs: [K:V])(dict: [K:V]) -> Bool {
let eqList = map(attrs) { (key: K, value: V) -> Bool in
if let v = dict[key] {
return v == value
} else {
return false
}
}
return Array(eqList).reduce(true) { $0 && $1 }
}
}
|
mit
|
99382de39c1bbd9c6d9ccfcb40b2f60b
| 30.112245 | 89 | 0.55264 | 3.903969 | false | false | false | false |
Blackjacx/SwiftTrace
|
Sources/Raytracer.swift
|
1
|
5336
|
//
// Raytracer.swift
// SwiftTrace
//
// Created by Stefan Herold on 13/08/16.
//
//
import Foundation
struct Constants {
static let RAD_2_DEG: Double = 180.0 / Double.pi
static let DEG_2_RAD: Double = Double.pi / 180.0
}
class Raytracer {
private(set) var scene: Scene
private(set) var glassnerH: Vector3 = Vector3.zero
private(set) var glassnerV: Vector3 = Vector3.zero
private(set) var glassnerMidPoint: Point3 = Point3.zero
public init(filePath: String) throws {
guard let fileData = FileManager.default.contents(atPath: filePath) else {
throw FileError.fileNotFound(filePath)
}
let json = try JSONSerialization.jsonObject(with: fileData, options: []) as! [String:AnyObject]
scene = try Scene(json: json)
setupSimpleViewingGeometry(forWidth: scene.width, height: scene.height)
}
/**
* Calculates the color for an infividual ray.
*/
private func trace(ray: Ray3) -> Color {
var t: Double = 0.0
var min_t: Double = 0.0
var object: Object?
// Find hit object and distance
for obj in scene.objects {
if obj.intersect(ray: ray, t: &t) != 0 && (object == nil || t < min_t) {
min_t = t
object = obj
}
}
guard let hitObject = object else {
return Color(gray: 0)
}
let hit = ray.at(t: min_t) // the hit point
let V = -ray.direction // the view vector
return phongColor(for: hitObject, hit: hit, V: V)
}
/**
* Traces the scene into an image.
*/
public func trace() -> Image {
let W = scene.width
let H = scene.height
let image = Image(width: W, height: H)
/*
* Approach Concurrent
*/
let queue = DispatchQueue(label: "com.dispatchQueue.concurrent", attributes: .concurrent)
let group = DispatchGroup()
let taskCount: UInt = 4 // Must be >= 4 and a power of 2 - best results achieved when == number of cores
let X: UInt = UInt(sqrt(Float(taskCount))) // tasks for one row or column
let HX = H / X
let WX = W / X
for i in 0..<X {
for j in 0..<X {
// Create a task per square of pixels
queue.async(group: group) {
for y in (i*HX)..<((i+1)*HX) {
for x in (j*WX)..<((j+1)*WX) {
image[x, y] = self.computeColorAt(x: x, y: y, W: W, H: H)
}
}
}
}
}
group.wait()
/*
* Approach: Stupid
*/
// for y in 0..<H {
// for x in 0..<W {
// image[x, y] = self.computeColorAt(x: x, y: y, W: W, H: H)
// }
// }
return image
}
func computeColorAt(x: UInt, y: UInt, W: UInt, H: UInt) -> Color {
let pixel = self.getGlassnerPixel(x: x, y: H-y-1)
let ray = Ray3(p1: self.scene.eye, p2: pixel)
var color = self.trace(ray: ray)
color.clamp()
return color
}
/**
* Glassner's Simple Viewing Geometry (https://graphics.stanford.edu/courses/cs348b-98/gg/viewgeom.html)
*/
private func setupSimpleViewingGeometry(forWidth width: UInt, height: UInt) {
let aspect = Double(scene.width) / Double(scene.height)
let A = scene.gaze.cross(scene.up)
let B = A.cross(scene.gaze)
let phiRad = scene.phi * 0.5 * Constants.DEG_2_RAD
let thetaRad = atan( tan(phiRad) / aspect)
glassnerH = A.normalized() * scene.gaze.length() * tan(phiRad)
glassnerV = B.normalized() * scene.gaze.length() * tan(thetaRad)
glassnerMidPoint = scene.eye + scene.gaze
}
private func getGlassnerPixel(x: UInt, y: UInt) -> Point3 {
let sx = Double(x) / Double(scene.width-1)
let sy = Double(y) / Double(scene.height-1)
let point = glassnerMidPoint + (2.0*sx - 1.0)*glassnerH + (2.0*sy - 1.0)*glassnerV
return point
}
/**
* Returns a color using the Phong Reflection Model
*/
private func phongColor(for hitObject: Object, hit: Point3, V: Vector3) -> Color {
let material = hitObject.material // the hit objects material
let ka = material.ambient // ambient factor
let kd = material.diffuse // diffuse factor
let ks = material.specular // specular factor
let phong = material.phong // shiny exponent
let N = hitObject.normal(P: hit) // the normal
var color = material.color * ka // ambient component
for light in scene.lights {
let L = (light.center - hit).normalized() // hit -> light vector
let LN = L.dot(N)
let R = 2.0 * N * LN - L // reflection vector
let VR = V.dot(R)
color += light.color * material.color * kd * max(0.0, LN) // diffuse component
color += light.color * ks * pow(max(0.0, VR), phong) // specular component
}
return color
}
}
|
mit
|
f2b8514e08fde2c553f58e9639525ca1
| 31.938272 | 112 | 0.5253 | 3.792466 | false | false | false | false |
silt-lang/silt
|
Sources/Lithosphere/SourceLength.swift
|
1
|
2244
|
//===------------------ SourceLength.swift - Source Length ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// swiftlint:disable shorthand_operator
/// The length a syntax node spans in the source code. From any AbsolutePosition
/// you reach a node's end location by adding its UTF-8 length.
public struct SourceLength: Comparable {
public let utf8Length: Int
/// Construct the source length of a given text
public init(of text: String) {
self.utf8Length = text.utf8.count
}
public init(utf8Length: Int) {
self.utf8Length = utf8Length
}
/// A zero-length source length
public static let zero: SourceLength =
SourceLength(utf8Length: 0)
public static func < (lhs: SourceLength, rhs: SourceLength) -> Bool {
return lhs.utf8Length < rhs.utf8Length
}
/// Combine the length of two source length.
public static func + (lhs: SourceLength, rhs: SourceLength) -> SourceLength {
let utf8Length = lhs.utf8Length + rhs.utf8Length
return SourceLength(utf8Length: utf8Length)
}
public static func += (lhs: inout SourceLength, rhs: SourceLength) {
lhs = lhs + rhs
}
public static func - (lhs: SourceLength, rhs: SourceLength) -> SourceLength {
let utf8Length = lhs.utf8Length - rhs.utf8Length
return SourceLength(utf8Length: utf8Length)
}
public static func -= (lhs: inout SourceLength, rhs: SourceLength) {
lhs = lhs - rhs
}
}
extension AbsolutePosition {
/// Determine the AbsolutePosition by advancing the `lhs` by the given source
/// length.
public static func + (lhs: AbsolutePosition, rhs: SourceLength)
-> AbsolutePosition {
let utf8Offset = lhs.utf8Offset + rhs.utf8Length
return AbsolutePosition(utf8Offset: utf8Offset)
}
public static func += (lhs: inout AbsolutePosition, rhs: SourceLength) {
lhs = lhs + rhs
}
}
|
mit
|
55ff40dc58cc995705d0f863c6379905
| 32 | 80 | 0.672906 | 4.194393 | false | false | false | false |
andykog/RAC-MutableCollectionProperty
|
MutableCollectionPropertyTests/MutableCollectionPropertyTests.swift
|
1
|
25641
|
import XCTest
import Quick
import Nimble
import ReactiveCocoa
@testable import MutableCollectionProperty
class TestSection: MutableCollectionProperty<String> {
override init(_ a: [String]) {
super.init(a)
}
}
extension TestSection: Equatable {}
func ==(a: TestSection, b: TestSection) -> Bool {
return a.value == b.value
}
class MutableCollectionPropertyTests: QuickSpec {
override func spec() {
describe("initialization") {
it("should properly update the value once initialized") {
let array: [String] = ["test1, test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
expect(property.value) == array
}
}
describe("flat updates") {
context("full update") {
it("should notify the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test2", "test3"]
done()
}
property.value = ["test2", "test3"]
})
}
it("should notify the flatChanges producer with the right sequence of changes") {
let array: [String] = ["test0", "test1", "test2", "test3" ]
let newArray: [String] = [ "test1", "test2-changed", "test3", "test4-new"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Composite(let changes) = change {
let indexes = changes.map({$0.index!})
let elements = changes.map({$0.oldElement ?? $0.newElement!})
let operations = changes.map({$0.operation!})
expect(indexes) == [0, 2, 1, 3]
expect(elements) == ["test0", "test2", "test2-changed", "test4-new"]
expect(operations) == [.Removal, .Removal, .Insertion, .Insertion]
done()
}
}
property.value = newArray
})
}
it("should continue notifying the deepChanges producer after full update") {
let initialValue = [TestSection(["test0"])]
let nextValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
property.value = nextValue
waitUntil(action: { done in
property.changes.startWithNext { change in
if case .Insert(let indexPath, let element) = change {
expect(indexPath) == [0, 0]
expect(element as? String) == "test0"
done()
}
}
property.insert("test0", atIndexPath: [0, 0])
})
}
}
}
describe("flat deletion") {
context("delete at a given index") {
it("should notify the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test1"]
done()
}
property.removeAtIndex(1)
})
}
it("should notify the flatChanges producer with the right type") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Remove(let index, let element) = change {
expect(index) == 1
expect(element) == "test2"
done()
}
}
property.removeAtIndex(1)
})
}
}
context("deleting the last element", {
it("should notify the deletion to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test1"]
done()
}
property.removeLast()
})
}
it("should notify the deletion to the flatChanges producer with the right type") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Remove(let index, let element) = change {
expect(index) == 1
expect(element) == "test2"
done()
}
}
property.removeLast()
})
}
})
context("deleting the first element", {
it("should notify the deletion to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test2"]
done()
}
property.removeFirst()
})
}
it("should notify the deletion to the flatChanges producer with the right type") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Remove(let index, let element) = change {
expect(index) == 0
expect(element) == "test1"
done()
}
}
property.removeFirst()
})
}
})
context("remove all elements", {
it("should notify the deletion to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == []
done()
}
property.removeAll()
})
}
it("should notify the deletion to the flatChanges producer with the right type") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Composite(let changes) = change {
let indexes = changes.map({$0.index!})
let elements = changes.map({$0.oldElement!})
let operations = changes.map({$0.operation!})
expect(indexes) == [0, 1]
expect(elements) == ["test1", "test2"]
expect(operations) == [.Removal, .Removal]
done()
}
}
property.removeAll()
})
}
})
context("update or insert with subscript", {
it("should notify the deletion to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test0", "test2"]
done()
}
property[0] = "test0"
})
}
it("should notify the changes producer with the update") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Update(let indexPath, let oldElement, let newElement) = change {
expect(indexPath) == [0]
expect(oldElement as? String) == "test1"
expect(newElement as? String) == "test0"
done()
}
}
property[0] = "test0"
})
}
it("should notify the changes producer with the insertion") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Insert(let indexPath, let newElement) = change {
expect(indexPath) == [2]
expect(newElement as? String) == "test0"
done()
}
}
property[2] = "test0"
})
}
})
}
describe("deep deletion") {
context("delete at a given indexPath") {
it("should notify the main producer") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: {
done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == []
done()
}
property.removeAtIndex(0)
})
}
it("should notify the deepChanges producer") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Remove(let indexPath, let element) = change {
expect(indexPath) == [0, 1]
expect(element as? String) == "test2"
done()
}
}
property.removeAtIndexPath([0, 1])
})
}
}
}
context("flat adding elements") {
context("appending elements individually", { () -> Void in
it("should notify about the change to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test1", "test2", "test3"]
done()
}
property.append("test3")
})
}
it("should notify the flatChanges producer about the adition") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Insert(let index, let element) = change {
expect(index) == 2
expect(element) == "test3"
done()
}
}
property.append("test3")
})
}
})
context("appending elements from another array", {
it("should notify about the change to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test1", "test2", "test3", "test4"]
done()
}
property.appendContentsOf(["test3", "test4"])
})
}
it("should notify the flatChanges producer about the adition") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Composite(let changes) = change {
let indexes = changes.map({$0.index!})
let elements = changes.map({$0.newElement!})
let operations = changes.map({$0.operation!})
expect(indexes) == [2, 3]
expect(elements) == ["test3", "test4"]
expect(operations) == [.Insertion, .Insertion]
done()
}
}
property.appendContentsOf(["test3", "test4"])
})
}
})
context("inserting elements", {
it("should notify about the change to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test0", "test1", "test2"]
done()
}
property.insert("test0", atIndex: 0)
})
}
it("should notify the flatChanges producer about the adition") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Insert(let index, let element) = change {
expect(index) == 0
expect(element) == "test0"
done()
}
}
property.insert("test0", atIndex: 0)
})
}
})
context("replacing elements", {
it("should notify about the change to the main producer") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == ["test3", "test4"]
done()
}
property.replace(Range<Int>(start: 0, end: 1), with: ["test3", "test4"])
})
}
it("should notify the flatChanges producer about the adition") {
let array: [String] = ["test1", "test2"]
let property: MutableCollectionProperty<String> = MutableCollectionProperty(array)
waitUntil(action: { done in
property.flatChanges.take(1).startWithNext { change in
if case .Composite(let changes) = change {
let indexes = changes.map({$0.index!})
let oldElements = changes.map({$0.oldElement!})
let newElements = changes.map({$0.newElement!})
let operations = changes.map({$0.operation!})
expect(indexes) == [0, 1]
expect(oldElements) == ["test1", "test2"]
expect(newElements) == ["test3", "test4"]
expect(operations) == [.Update, .Update]
done()
}
}
property.replace(Range<Int>(start: 0, end: 1), with: ["test3", "test4"])
})
}
})
}
context("deep adding elements") {
context("inserting elements", {
it("should notify about the change to the main producer") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == [TestSection(["test0", "test1", "test2"])]
done()
}
property.insert("test0", atIndexPath: [0, 0])
})
}
it("should notify the deepChanges producer about the adition") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Insert(let indexPath, let element) = change {
expect(indexPath) == [0, 0]
expect(element as? String) == "test0"
done()
}
}
property.insert("test0", atIndexPath: [0, 0])
})
}
})
context("replacing elements", {
it("should notify about the change to the main producer") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == [TestSection(["test8", "test2"])]
done()
}
property.replace(elementAtIndexPath: [0, 0], withElement: "test8")
})
}
it("should notify the deepChanges producer about the adition") {
let initialValue = [TestSection(["test1", "test2"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Update(let indexPath, let oldElement, let newElement) = change {
expect(indexPath) == [0, 0]
expect(oldElement as? String) == "test1"
expect(newElement as? String) == "test0"
done()
}
}
property.replace(elementAtIndexPath: [0, 0], withElement: "test0")
})
}
})
context("moving elements", {
it("should notify about the change to the main producer") {
let initialValue = [TestSection(["test1", "test2", "test3", "test4"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.producer.take(1).startWithNext { newValue in
expect(newValue) == [TestSection(["test1", "test3", "test2", "test4"])]
done()
}
property.move(fromIndexPath: [0, 1], toIndexPath: [0, 2])
})
}
it("should notify the deepChanges producer about the adition") {
let initialValue = [TestSection(["test1", "test2", "test3", "test4"])]
let property = MutableCollectionProperty(initialValue)
waitUntil(action: { done in
property.changes.take(1).startWithNext { change in
if case .Composite(let changes) = change {
let indexPaths = changes.map({$0.indexPath!})
let elements = changes.map({$0.oldElement as? String ?? $0.newElement as! String})
let operations = changes.map({$0.operation!})
expect(indexPaths) == [[0, 1], [0, 2]]
expect(elements) == ["test2", "test2"]
expect(operations) == [.Removal, .Insertion]
done()
}
}
property.move(fromIndexPath: [0, 1], toIndexPath: [0, 2])
})
}
})
}
}
}
|
mit
|
af1a41889227783a7da039e2bce3b176
| 45.875686 | 114 | 0.413712 | 6.154825 | false | true | false | false |
lieonCX/TodayHeadline
|
TodayHealine/View/Home/HomeViewController.swift
|
1
|
6478
|
//
// HomeViewController.swift
// TodayHealine
//
// Created by lieon on 2017/1/16.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
private let bannerHeight: CGFloat = 64 + 150
private let titleViewHeight: CGFloat = 44
class HomeViewController: BaseViewController {
fileprivate lazy var homeVM: HomeViewModel = HomeViewModel()
fileprivate lazy var tableViewArray: [UITableView] = [UITableView]()
fileprivate var lastTableViewOffsetY: CGFloat = CGFloat()
fileprivate lazy var bannerView: CycleView = {
let bannerView = CycleView.cycleView()
bannerView.backgroundColor = UIColor.yellow
bannerView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: bannerHeight)
return bannerView
}()
fileprivate lazy var contentView: PageContentView = { [unowned self] in
var childVCs = [UIViewController]()
for _ in 0 ... 5 {
let recommendVC = RecommendViewController()
childVCs.append(recommendVC)
recommendVC.tableView.contentInset = UIEdgeInsets(top: self.titleView.frame.maxY, left: 0, bottom: 0, right: 0)
recommendVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
/// 让每个view进行一次预加载
recommendVC.view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)
self.tableViewArray.append(recommendVC.tableView)
}
let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = UIScreen.height
let width: CGFloat = UIScreen.width
let contentView = PageContentView(frame: CGRect(x: x, y: y, width: width, height: height), childVCs: childVCs, parentVC: self)
return contentView
}()
fileprivate lazy var titleView: PageTitleView = { [unowned self] in
let x: CGFloat = 0
let y: CGFloat = self.bannerView.frame.maxY
let height: CGFloat = titleViewHeight
let width: CGFloat = UIScreen.width
let titleView = PageTitleView(frame: CGRect(x: x, y: y, width: width, height: height), titles: ["推荐", "热点", "成都", "视屏", "社会", "科技", "火山直播"])
titleView.normalColor = (0, 0, 0)
titleView.selectColor = (255, 0, 0)
titleView.backgroundColor = UIColor.white
return titleView
}()
fileprivate lazy var naviBar: HomeNaviBar = {
let naivBar = HomeNaviBar.naviBar()
naivBar.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 64)
return naivBar
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setTapAction()
loadBanner()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
deinit {
for tableView in tableViewArray {
tableView.removeObserver(self, forKeyPath: "contentOffset")
}
}
}
extension HomeViewController {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentOffset", let tableView = object as? UITableView {
let offsetY = tableView.contentOffset.y
lastTableViewOffsetY = offsetY
if offsetY > -bannerHeight - titleViewHeight && offsetY < -(bannerHeight - titleViewHeight - 64) {
bannerView.frame.origin.y = 0 - bannerHeight - titleViewHeight - offsetY
let tatio = -((1 / (-2 * titleViewHeight - 64)) * offsetY - (bannerHeight + titleViewHeight) / (2 * titleViewHeight + 64))
naviBar.setup(opacity: tatio)
} else if offsetY >= -(bannerHeight - titleViewHeight - 64) {
bannerView.frame.origin.y = -(bannerHeight - 64)
naviBar.setup(opacity: 1)
} else {
bannerView.frame.origin.y = 0
naviBar.setup(opacity: 0)
}
titleView.frame.origin.y = bannerView.frame.maxY
}
}
}
extension HomeViewController {
fileprivate func setupUI() {
automaticallyAdjustsScrollViewInsets = false
view.addSubview(contentView)
view.addSubview(bannerView)
view.addSubview(titleView)
view.addSubview(naviBar)
}
fileprivate func setTapAction() {
titleView.titleTapAction = { [unowned self ] selectedIndex in
for tableView in self.tableViewArray {
tableView.contentOffset = CGPoint(x: 0, y: self.lastTableViewOffsetY)
let offsetY = self.lastTableViewOffsetY
if offsetY > -bannerHeight - titleViewHeight && offsetY < -(bannerHeight - titleViewHeight - 64) {
tableView.contentOffset = CGPoint(x: 0, y: self.lastTableViewOffsetY)
} else if offsetY >= -(bannerHeight - titleViewHeight - 64) {
tableView.contentOffset = CGPoint(x: 0, y: -(bannerHeight - 64 - titleViewHeight))
} else {
tableView.contentOffset = CGPoint(x: 0, y: -(bannerHeight + titleViewHeight))
}
}
self.contentView.selected(index: selectedIndex)
}
contentView.tapAction = { [unowned self ]progress, sourceIndex, targetIndx in
for tableView in self.tableViewArray {
tableView.contentOffset = CGPoint(x: 0, y: self.lastTableViewOffsetY)
let offsetY = self.lastTableViewOffsetY
if offsetY > -bannerHeight - titleViewHeight && offsetY < -(bannerHeight - titleViewHeight - 64) {
tableView.contentOffset = CGPoint(x: 0, y: self.lastTableViewOffsetY)
} else if offsetY >= -(bannerHeight - titleViewHeight - 64) {
tableView.contentOffset = CGPoint(x: 0, y: -(bannerHeight - 64 - titleViewHeight))
} else {
tableView.contentOffset = CGPoint(x: 0, y: -(bannerHeight + titleViewHeight))
}
}
self.titleView.setTitle(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndx)
}
}
fileprivate func loadBanner() {
homeVM.loadBanner { [unowned self] in
self.bannerView.banners = self.homeVM.banners
}
}
}
|
mit
|
a5b8b26854adde8540d6439ef7f5b4ff
| 41.82 | 151 | 0.61669 | 4.69861 | false | false | false | false |
Beninho85/BBDesignable
|
BBDesignable/BBDesignable/UIView/GradientView.swift
|
1
|
1915
|
//
// GradientView.swift
// BBDesignable
//
// Created by Benjamin Bourasseau on 2017-06-14.
// Copyright © 2017 Benjamin. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class GradientView: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}
override class var layerClass: AnyClass { return CAGradientLayer.self }
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
func update() {
updatePoints()
updateLocations()
updateColors()
}
override func layoutSubviews() {
super.layoutSubviews()
update()
}
override func prepareForInterfaceBuilder() {
update()
super.prepareForInterfaceBuilder()
}
}
|
mit
|
d68090e291dc5513eb9af397a367b2b3
| 32 | 97 | 0.633751 | 4.524823 | false | false | false | false |
roecrew/AudioKit
|
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Phasor Operation.xcplaygroundpage/Contents.swift
|
1
|
809
|
//: ## Phasor Operation
//: Using the phasor to sweep amplitude and frequencies
import XCPlayground
import AudioKit
let interval: Double = 2
let noteCount: Double = 24
let startingNote: Double = 48 // C
let generator = AKOperationGenerator() { _ in
let frequency = (floor(AKOperation.phasor(frequency: 0.5) * noteCount) * interval + startingNote)
.midiNoteToFrequency()
var amplitude = (AKOperation.phasor(frequency: 0.5) - 1).portamento() // prevents the click sound
var oscillator = AKOperation.sineWave(frequency: frequency, amplitude: amplitude)
let reverb = oscillator.reverberateWithChowning()
return mixer(oscillator, reverb, balance: 0.6)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
|
mit
|
8a7296f2db3c8200f87ae33b369be928
| 30.115385 | 102 | 0.745365 | 4.106599 | false | false | false | false |
nathawes/swift
|
test/SILGen/opaque_ownership.swift
|
9
|
11134
|
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s
public typealias AnyObject = Builtin.AnyObject
precedencegroup AssignmentPrecedence {}
precedencegroup CastingPrecedence {}
precedencegroup ComparisonPrecedence {}
public protocol _ObjectiveCBridgeable {}
public protocol UnkeyedDecodingContainer {
var isAtEnd: Builtin.Int1 { get }
}
public protocol Decoder {
func unkeyedContainer() throws -> UnkeyedDecodingContainer
}
// Test open_existential_value ownership
// ---
// CHECK-LABEL: sil [ossa] @$ss11takeDecoder4fromBi1_s0B0_p_tKF : $@convention(thin) (@in_guaranteed Decoder) -> (Builtin.Int1, @error Error) {
// CHECK: bb0(%0 : @guaranteed $Decoder):
// CHECK: [[OPENED:%.*]] = open_existential_value %0 : $Decoder to $@opened("{{.*}}") Decoder
// CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %3 : $@opened("{{.*}}") Decoder : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error)
// CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error), normal bb2, error bb1
//
// CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer):
// CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer
// CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer
// CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1
// CHECK: end_borrow [[BORROW2]] : $UnkeyedDecodingContainer
// CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer
// CHECK-NOT: destroy_value %0 : $Decoder
// CHECK: return [[RET2]] : $Builtin.Int1
// CHECK-LABEL: } // end sil function '$ss11takeDecoder4fromBi1_s0B0_p_tKF'
public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 {
let container = try decoder.unkeyedContainer()
return container.isAtEnd
}
// Test unsafe_bitwise_cast nontrivial ownership.
// ---
// CHECK-LABEL: sil [ossa] @$ss13unsafeBitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $T, [[ARG1:%.*]] : $@thick U.Type):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG0]] : $T
// CHECK: [[RESULT:%.*]] = unchecked_bitwise_cast [[ARG_COPY]] : $T to $U
// CHECK: [[RESULT_COPY:%.*]] = copy_value [[RESULT]] : $U
// CHECK: destroy_value [[ARG_COPY]] : $T
// CHECK: return [[RESULT_COPY]] : $U
// CHECK-LABEL: } // end sil function '$ss13unsafeBitCast_2toq_x_q_mtr0_lF'
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
return Builtin.reinterpretCast(x)
}
// A lot of standard library support is necessary to support raw enums.
// --------------------------------------------------------------------
infix operator == : ComparisonPrecedence
infix operator ~= : ComparisonPrecedence
public struct Bool {
var _value: Builtin.Int1
public init() {
let zero: Int64 = 0
self._value = Builtin.trunc_Int64_Int1(zero._value)
}
internal init(_ v: Builtin.Int1) { self._value = v }
public init(_ value: Bool) {
self = value
}
}
extension Bool {
public func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}
}
public protocol Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func == (lhs: Self, rhs: Self) -> Bool
}
public func ~= <T : Equatable>(a: T, b: T) -> Bool {
return a == b
}
public protocol RawRepresentable {
associatedtype RawValue
init?(rawValue: RawValue)
var rawValue: RawValue { get }
}
public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue == rhs.rawValue
}
public typealias _MaxBuiltinIntegerType = Builtin.IntLiteral
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
public protocol ExpressibleByIntegerLiteral {
associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral
init(integerLiteral value: IntegerLiteralType)
}
extension ExpressibleByIntegerLiteral
where Self : _ExpressibleByBuiltinIntegerLiteral {
@_transparent
public init(integerLiteral value: Self) {
self = value
}
}
public protocol ExpressibleByStringLiteral {}
public protocol ExpressibleByFloatLiteral {}
public protocol ExpressibleByUnicodeScalarLiteral {}
public protocol ExpressibleByExtendedGraphemeClusterLiteral {}
public struct Int64 : ExpressibleByIntegerLiteral, _ExpressibleByBuiltinIntegerLiteral, Equatable {
public var _value: Builtin.Int64
public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) {
_value = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(x).0
}
public typealias IntegerLiteralType = Int64
public init(integerLiteral value: Int64) {
self = value
}
public static func ==(_ lhs: Int64, rhs: Int64) -> Bool {
return Bool(Builtin.cmp_eq_Int64(lhs._value, rhs._value))
}
}
// Test ownership of multi-case Enum values in the context of to @in thunks.
// ---
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW :
// CHECK: bb0(%0 : $FloatingPointSign, %1 : $FloatingPointSign, %2 : $@thick FloatingPointSign.Type):
// CHECK: %3 = function_ref @$ss2eeoiySbx_xtSYRzSQ8RawValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// CHECK: %4 = apply %3<FloatingPointSign>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// CHECK: return %4 : $Bool
// CHECK-LABEL: } // end sil function '$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW'
public enum FloatingPointSign: Int64 {
/// The sign for a positive value.
case plus
/// The sign for a negative value.
case minus
}
#if os(macOS)
// Test open_existential_value used in a conversion context.
// (the actual bridging call is dropped because we don't import Swift).
// ---
// CHECK-OSX-LABEL: sil [ossa] @$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF : $@convention(thin) (@in_guaranteed Any) -> @owned AnyObject {
// CHECK-OSX: bb0(%0 : @guaranteed $Any):
// CHECK-OSX: [[COPY:%.*]] = copy_value %0 : $Any
// CHECK-OSX: [[BORROW2:%.*]] = begin_borrow [[COPY]] : $Any
// CHECK-OSX: [[VAL:%.*]] = open_existential_value [[BORROW2]] : $Any to $@opened
// CHECK-OSX: [[COPY2:%.*]] = copy_value [[VAL]] : $@opened
// CHECK-OSX: end_borrow [[BORROW2]] : $Any
// CHECK-OSX: destroy_value [[COPY2]] : $@opened
// CHECK-OSX: destroy_value [[COPY]] : $Any
// CHECK-OSX-NOT: destroy_value %0 : $Any
// CHECK-OSX: return undef : $AnyObject
// CHECK-OSX-LABEL: } // end sil function '$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF'
public func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
return any as AnyObject
}
#endif
public protocol Error {}
#if os(macOS)
// Test open_existential_box_value in a conversion context.
// ---
// CHECK-OSX-LABEL: sil [ossa] @$ss3foo1eys5Error_pSg_tF : $@convention(thin) (@guaranteed Optional<Error>) -> () {
// CHECK-OSX: [[BORROW:%.*]] = begin_borrow %{{.*}} : $Error
// CHECK-OSX: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened
// CHECK-OSX: [[COPY:%.*]] = copy_value [[VAL]] : $@opened
// CHECK-OSX: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened
// CHECK-OSX: end_borrow [[BORROW]] : $Error
// CHECK-OSX-LABEL: } // end sil function '$ss3foo1eys5Error_pSg_tF'
public func foo(e: Error?) {
if let u = e {
let a: Any = u
_ = a
}
}
#endif
public enum Optional<Wrapped> {
case none
case some(Wrapped)
}
public protocol IP {}
public protocol Seq {
associatedtype Iterator : IP
func makeIterator() -> Iterator
}
extension Seq where Self.Iterator == Self {
public func makeIterator() -> Self {
return self
}
}
public struct EnumIter<Base : IP> : IP, Seq {
internal var _base: Base
public typealias Iterator = EnumIter<Base>
}
// Test passing a +1 RValue to @in_guaranteed.
// ---
// CHECK-LABEL: sil [ossa] @$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> {
// CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>):
// CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type
// CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base
// CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base
// CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[COPY]]) : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
// CHECK: destroy_value [[COPY]] : $Base
// CHECK: [[FN:%.*]] = function_ref @$ss8EnumIterV5_baseAByxGx_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
// CHECK: return [[RET]] : $EnumIter<Base.Iterator>
// CHECK-LABEL: } // end sil function '$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF'
public struct EnumSeq<Base : Seq> : Seq {
public typealias Iterator = EnumIter<Base.Iterator>
internal var _base: Base
public func makeIterator() -> Iterator {
return EnumIter(_base: _base.makeIterator())
}
}
|
apache-2.0
|
7f07cbd8aa4eb9b20fad5eddaa4ca195
| 42.167315 | 403 | 0.671985 | 3.552354 | false | false | false | false |
jfosterdavis/Charles
|
Charles/DataViewController+LevelProgress.swift
|
1
|
27997
|
//
// DataViewController+LevelProgress.swift
// Charles
//
// Created by Jacob Foster Davis on 5/29/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
import CoreData
/******************************************************/
/*******************///MARK: Extension for all level progress logic and presentation
/******************************************************/
extension DataViewController {
/******************************************************/
/*******************///MARK: Level Progress
/******************************************************/
func refreshLevelProgress(_ justAnimatedPlayerFinishingLevel: Bool = false) {
//figure out what level the player is on
let userXP = calculateUserXP()
let currentLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
//if the player isn't working on objectives, hide this progress bar
if getCurrentScore() < minimumScoreToUnlockObjective {
levelProgressView.isHidden = true
thisLevelLabel.alpha = 0.0
nextLevelLabel.alpha = 0
levelDescriptionLabel.alpha = 0
//play sounds if needed
compareLevelAndProgressAndPlaySounds(given: currentLevelAndProgress)
} else {
//show the level progress
levelProgressView.isHidden = false
//if just got done animating player to a full bar, set the progressbar progress to zero so it can finish animating to current progress
if justAnimatedPlayerFinishingLevel {
levelProgressView.setProgress(0, animated: false)
}
if let progress = calculateProgressValue() {
var thisLevelColor: UIColor
var nextLevelColor: UIColor
//there are 11 sections of the progress bar and the width of each label is 1/11 of the progress bar. 1/11 = 0.0909090909
switch progress {
case let x where x < 0.091:
thisLevelColor = UIColor.darkGray
nextLevelColor = UIColor.darkGray
case let x where x >= 0.91:
thisLevelColor = progressViewLightTextColor.textColor
nextLevelColor = progressViewLightTextColor.textColor
default:
thisLevelColor = progressViewLightTextColor.textColor
nextLevelColor = UIColor.darkGray
}
//if progress is in between the 1/11ths, activate background color
switch progress {
case let x where x > 0 && x < 0.091:
thisLevelColor = progressViewLightTextColor.textColor
thisLevelLabel.backgroundColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 0.5) //dark gray background color
thisLevelLabel.roundCorners(with: 4)
case let x where x < 1 && x >= 0.91:
nextLevelLabel.backgroundColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 0.5) //dark gray background color
nextLevelLabel.roundCorners(with: 4)
default:
thisLevelLabel.backgroundColor = .clear
nextLevelLabel.backgroundColor = .clear
}
/******************************************************/
/*******************///MARK: PERK INCREASED XP
/******************************************************/
//if an increased XP perk is active, change the color of the progressview
let xpPerks = getAllPerks(ofType: .increasedXP, withStatus: .unlocked)
if xpPerks.isEmpty {
//no perks are active, set to normal color
levelProgressView.progressTintColor = progressViewProgressTintColorDefault
} else { //a perk is active so put the special color on
//TODO: flash the bar to the perk color then back
self.levelProgressView.progressTintColor = self.progressViewProgressTintColorXPPerkActive
}
//only animate if the user is progressing on the same level or degressing on same level. don't animate if user just lost a level or if the view just loaded.
var shouldAnimate = false
var playerLeveledUpWithXPPerkActive = false
let currentLevel = currentLevelAndProgress.0
shouldAnimate = didPlayer(magnitudeDirection: .noChange, in: .level, byAchieving: currentLevel.level)
//determine if the player leveled up while the XP perk was active, or by earning more than 1 xp
//this would occur if progress > 0 and the player increased in level
let playerIncreasedLevel = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: currentLevel.level)
if playerIncreasedLevel && !xpPerks.isEmpty {
playerLeveledUpWithXPPerkActive = true
}
/******************************************************/
/*******************///MARK: END PERK INCREASED XP
/******************************************************/
if playerLeveledUpWithXPPerkActive && progress < 1.0 {
//TODO: fix this so it works
//flash user feedback for increased xp
//the player leveled up by earning more than 1 XP, so progress bar should animate to full, then reset to the current level and progress
//0. update labels
//trick the label to think it will end up light
thisLevelColor = progressViewLightTextColor.textColor
nextLevelColor = progressViewLightTextColor.textColor
let currentLevel = currentLevelAndProgress.0
let previousLevel = (Levels.Game[currentLevel.level - 1])!
UIView.animate(withDuration: 0.8,
delay: 0.8,
animations: {
self.thisLevelLabel.alpha = 1
self.thisLevelLabel.text = String(describing: previousLevel.level)
self.thisLevelLabel.textColor = thisLevelColor
//print(" text of this level label: \(self.thisLevelLabel.text)")
//if player is on the highest level, don't show a level label
if currentLevel != Levels.HighestLevel {
self.nextLevelLabel.alpha = 1
self.nextLevelLabel.text = String(describing: (previousLevel.level + 1))
self.nextLevelLabel.textColor = nextLevelColor
} else {
//player is on highest level
self.nextLevelLabel.alpha = 0
self.nextLevelLabel.text = ""
self.nextLevelLabel.textColor = nextLevelColor
}
//level label
self.levelDescriptionLabel.alpha = 1
self.levelDescriptionLabel.text = previousLevel.name
})
//1. animate the progress bar to full
//to do this need to animate it to 1
self.levelProgressView.setProgress(1, animated: true)
//2. wait then call this refresh function again
let seconds = 2
let deadline = DispatchTime.now() + DispatchTimeInterval.seconds(seconds)
DispatchQueue.main.asyncAfter(deadline: deadline, execute: {
self.refreshLevelProgress(true)
})
} else {
UIView.animate(withDuration: 0.8,
delay: 0.8,
animations: {
let currentLevel = currentLevelAndProgress.0
self.thisLevelLabel.alpha = 1
self.thisLevelLabel.text = String(describing: currentLevel.level)
self.thisLevelLabel.textColor = thisLevelColor
//print(" text of this level label: \(self.thisLevelLabel.text)")
//if player is on the highest level, don't show a level label
if currentLevel != Levels.HighestLevel {
self.nextLevelLabel.alpha = 1
self.nextLevelLabel.text = String(describing: (currentLevel.level + 1))
self.nextLevelLabel.textColor = nextLevelColor
} else {
//player is on highest level
self.nextLevelLabel.alpha = 0
self.nextLevelLabel.text = ""
self.nextLevelLabel.textColor = nextLevelColor
}
}, completion: { (finished:Bool) in
//if progress is going to 1, then animate to 1 then continue
self.levelProgressView.setProgress(progress, animated: shouldAnimate)
//level label
self.levelDescriptionLabel.alpha = 1
self.levelDescriptionLabel.text = currentLevel.name
})
}
} else {
//no progress value returned (some sort of problem)
levelProgressView.setProgress(0.0, animated: true)
//TODO: log problem
}
//play sounds if needed
compareLevelAndProgressAndPlaySounds(given: currentLevelAndProgress)
}
checkIfMapShouldBePresentedAndPresent()
checkIfClueShouldBePresentedAndPresent()
}
///determines if the map should be presented
func checkIfMapShouldBePresentedAndPresent() {
// let userXP = calculateUserXP()
// let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let userCurrentLevel = getUserCurrentLevel().level
let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel)
if userCurrentLevel >= Levels.ReturnToDarknessLevelFirst.level && userCurrentLevel <= Levels.ReturnToDarknessLevelLast.level {
//player is returning to darkness so do not present the map
return
} else if didPlayerProgressToGetHere && userCurrentLevel >= 11 {
let topVC = topMostController()
let mapVC = self.storyboard!.instantiateViewController(withIdentifier: "MapCollectionViewController") as! MapCollectionViewController
mapVC.initialLevelToScrollTo = userCurrentLevel - 1 //initial level is the one just passed
mapVC.playerHasFinishedInitialLevelToScrollTo = true
topVC.present(mapVC, animated: true, completion: nil)
}
}
///checks if the user's new level warrants the presentation of a clue, and presents that clue
func checkIfClueShouldBePresentedAndPresent() {
let userXP = calculateUserXP()
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let userCurrentLevel = userLevelAndProgress.0.level
let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel)
//if the user progressed to get to here (as opposed to lost a level) and there is a clue for this new level
if let clue = Clues.Lineup[userCurrentLevel], didPlayerProgressToGetHere {
//there is a clue, so present this clue
let topVC = topMostController()
let clueVC = self.storyboard!.instantiateViewController(withIdentifier: "BasicClueViewController") as! BasicClueViewController
clueVC.clue = clue
topVC.present(clueVC, animated: true, completion: nil)
}
}
///calculates the progress value for the progress meter based on the user's level and XP. returns Float
func calculateProgressValue() -> Float? {
//get user's level and progress
let userXP = calculateUserXP()
let currentLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let usersProgressOnCurrentLevel = currentLevelAndProgress.1
let usersCurrentLevel = currentLevelAndProgress.0
let progress: Float = Float(usersProgressOnCurrentLevel) / (Float(usersCurrentLevel.xPRequired) - 1)
return progress
}
///sets the playerLevelBaseline and playerProgerssBaseline for comparisonlater. should be called before the player starts an objective
func setUserLevelAndProgressBaselines() {
let userXP = calculateUserXP()
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
//record the current level for comparison at score time
let userLevel = userLevelAndProgress.0
playerLevelBaseline = userLevel.level
let userProgress = userLevelAndProgress.1
playerProgressBaseline = userProgress
}
//a test to see if the user progressed, degressed, or remained same in a Baseline compared to the given level
func didPlayer(magnitudeDirection: MagnitudeComparison, in baseline: Baseline, byAchieving newValue: Int) -> Bool {
//figure out what type of comparison to make
var comparisonOperator: (Int, Int) -> Bool
switch magnitudeDirection {
case .increase:
comparisonOperator = (>)
case .decrease:
comparisonOperator = (<)
default:
comparisonOperator = (==)
}
if baseline == .level {
if comparisonOperator(newValue, playerLevelBaseline) {
return true
} else {
return false
}
} else { //must be referring to a progress not a level
if comparisonOperator(newValue, playerProgressBaseline) {
return true
} else {
return false
}
}
}
/******************************************************/
/*******************///MARK: XP and Levels
/******************************************************/
/// sets the current score, returns the newly set score
func giveXP(value: Int = 1, earnedDatetime: Date = Date(), level: Int, score: Int, successScore: Float, time: Int, toggles: Int, metaInt1: Int? = nil, metaInt2: Int? = nil, metaString1: String? = nil, metaString2: String? = nil, consolidatedRecords: Int? = nil, dontExceedHighestLevel: Bool = true) {
guard let fc = frcDict[keyXP] else {
return
}
guard (fc.fetchedObjects as? [XP]) != nil else {
return
}
guard successScore >= 0 && successScore <= 1 else {
//TODO: log error
return
}
var xpToAward = value
if let excessXP = howMuchWouldPlayerExceedHighestLevel(ifPlayerGained: value), dontExceedHighestLevel { //if the player is at the highest level of the game and this function should not exceed that
xpToAward -= excessXP
}
//create a new score object
let newXP = XP(entity: NSEntityDescription.entity(forEntityName: "XP", in: stack.context)!, insertInto: fc.managedObjectContext)
newXP.value = Int64(xpToAward)
newXP.successScore = successScore
newXP.earnedDatetime = earnedDatetime
newXP.level = Int64(level)
newXP.score = Int64(score)
newXP.time = Int64(time)
newXP.toggles = Int64(toggles)
if let int1 = metaInt1 {
newXP.metaInt1 = Int64(int1)
}
if let int2 = metaInt1 {
newXP.metaInt2 = Int64(int2)
}
newXP.metaString1 = metaString1
newXP.metaString2 = metaString2
if let records = consolidatedRecords {
newXP.consolidatedRecords = Int64(records)
}
//save this right away
stack.save()
}
///checks to see how many XP records there are. If above the given number, will combine them all into a single record for each level. This to prevent big O problems
func checkXPAndConsolidateIfNeccessary(consolidateAt numRecords: Int) {
guard let fc = frcDict[keyXP] else {
fatalError("Counldn't get frcDict")
}
guard let xps = fc.fetchedObjects as? [XP] else {
fatalError("Counldn't get XP")
}
if xps.count >= numRecords {
//go thru each level
for (levelKey, _) in Levels.Game {
var resultantValue:Int64 = 0
var resultantScore:Int64 = 0
var resultantRecordsCount: Int64 = 0
var rawSuccessScores: [Float] = [Float]()
var found = false
var numFound = 0
//and check each xp record's level
for xp in xps {
if Int(xp.level) == levelKey {
//this xp record matches the level
resultantValue += xp.value
resultantScore += xp.score
resultantRecordsCount += xp.consolidatedRecords //consolidatedRecords holds records counts
if resultantRecordsCount == 0 {
//this is a single record so weigh it as 1
rawSuccessScores.append(xp.successScore) //weight of 1
} else {
//this is a consolidated record so weigh it
rawSuccessScores.append(xp.successScore * Float(xp.consolidatedRecords)) //weighted scores
}
found = true
numFound += 1
//now delete the record you just found
let delegate = UIApplication.shared.delegate as! AppDelegate
self.stack = delegate.stack
if let context = self.frcDict[keyXP]?.managedObjectContext {
context.delete(xp)
}
}
}
//if an applicable XP record was found, then consolidate and create a new XP
if found {
//create a new score object
let newXP = XP(entity: NSEntityDescription.entity(forEntityName: "XP", in: stack.context)!, insertInto: fc.managedObjectContext)
newXP.value = Int64(resultantValue)
newXP.earnedDatetime = Date()
newXP.level = Int64(levelKey)
newXP.score = Int64(resultantScore)
//calculate the average success
var sumOfSuccessScores: Float = 0
for successScore in rawSuccessScores {
sumOfSuccessScores += successScore
}
let averageSuccessScore: Float
switch (Int(resultantRecordsCount), rawSuccessScores.count) {
case (0, 1):
//there is only a single record, this one is not consolidated, so it is the average
averageSuccessScore = sumOfSuccessScores
case (0, let y) where y > 1:
//there are multiple records but none of them is a consolidated one
averageSuccessScore = sumOfSuccessScores / Float(rawSuccessScores.count)
case (let x, _) where x > 0:
//there are multiple records but none of them is a consolidated one
averageSuccessScore = sumOfSuccessScores / Float(resultantRecordsCount)
default:
//TODO: Make this a log entry
fatalError("Unexpected case for consolidating a successScore. \(Int(resultantRecordsCount), rawSuccessScores.count))")
}
newXP.successScore = averageSuccessScore
newXP.consolidatedRecords = resultantRecordsCount + Int64(numFound) //add the number of records consolidating to the count
print("Consolidated \(numFound) XP objects at level \(levelKey). Resulting XP sum for this level is \(resultantValue).")
}
}
}
}
///returns the total amount of user XP
func calculateUserXP() -> Int {
guard let fc = frcDict[keyXP] else {
fatalError("Counldn't get frcDict")
}
guard let xps = fc.fetchedObjects as? [XP] else {
fatalError("Counldn't get XP")
}
var sum = 0
for xp in xps {
sum = sum + Int(xp.value)
}
return sum
}
///returns the user's current level determine programmatically. returns nil if user's level is off the charts high
func getUserCurrentLevel() -> Level {
let userXP = calculateUserXP()
let userLevel = Levels.getLevelAndProgress(from: userXP)
//userLevel is a tuple (player level, xp towards that level)
return userLevel.0
}
///determines if the user just reached the highest progress of the highest level
func didPlayerBeatGame() -> Bool {
let userCurrentLevel = getUserCurrentLevel().level
if isPlayerAtHighestLevelAndProgress() { //looks like the user is at the highest level with the highest progress
//check that the player just arrived at this level
let didJustReach = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel)
//if the player just reached this level, then show the "you won" sequence
if didJustReach {
return true
}
}
return false
}
///determines if the user is at the highest level and progress values allowed
func isPlayerAtHighestLevelAndProgress() -> Bool {
let highestLevel = (Levels.HighestLevel.level)
let highestProgressRequiredOnHighestLevel = Levels.Game[(highestLevel)]?.xPRequired
let userXP = calculateUserXP()
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let requiredProgressValue = highestProgressRequiredOnHighestLevel! - 1 //The user must get up to 1 fewer than the highest XP of the highest level to win the game
if userLevelAndProgress.0.level == highestLevel && userLevelAndProgress.1 == requiredProgressValue {
return true
} else {
return false
}
}
///determines if the user is at the highest level and progress values allowed
func howMuchWouldPlayerExceedHighestLevel(ifPlayerGained XP: Int) -> Int? {
let highestLevel = Levels.HighestLevel
let userXP = calculateUserXP()
let userXPAndHypotheticalXP = userXP + XP
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXPAndHypotheticalXP)
if (userLevelAndProgress.0.level) > (highestLevel.level) {
var maxXP = 0
var level = 1
while level <= (Levels.HighestLevel.level) {
maxXP += (Levels.Game[level]?.xPRequired)!
level += 1
}
//maxXP now holds the total number of XP required to win
let xpDeviation = abs(userXPAndHypotheticalXP - maxXP) + 1 //if the user level is higher than the highest level the deviation will be the entire higher levels plus one.
return xpDeviation
} else {
return nil
}
}
///shows the wining sequence
func showWinningSequence() {
let topVC = topMostController()
let youWonVC = self.storyboard!.instantiateViewController(withIdentifier: "GameWinner") as! GameWinnerViewController
let userXP = calculateUserXP()
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let userLevel = userLevelAndProgress.0.level
youWonVC.parentVC = self
youWonVC.userLevel = userLevel
topVC.present(youWonVC, animated: true, completion: nil)
}
//modifies the user's real XP data to send them back to the given level
func reducePlayerLevel(to level: Int = 22) {
//destroy all XP earned after the player reached given level
guard let fc = frcDict[keyXP] else {
fatalError("Counldn't get frcDict")
}
guard let xps = fc.fetchedObjects as? [XP] else {
fatalError("Counldn't get XP")
}
//delete any xp object earnedon the given level or higher
let delegate = UIApplication.shared.delegate as! AppDelegate
self.stack = delegate.stack
for xp in xps {
if Int(xp.level) >= level {
if let context = self.frcDict[keyXP]?.managedObjectContext {
print("Deleting XP for level \(xp.level)")
context.delete(xp)
}
}
}
stack.save()
//now check that player is back to given level
let newActualLevel = getUserCurrentLevel().level
if newActualLevel > level {
fatalError("Something went wrong when trying to put player back to level \(level). Current level being reported as \(String(describing: newActualLevel))")
}
}
}
|
apache-2.0
|
d7420706c95612e20c12b2b0b5fd0b69
| 44.596091 | 304 | 0.52729 | 5.591372 | false | false | false | false |
practicalswift/swift
|
validation-test/Sema/type_checker_perf/fast/rdar22282851.swift
|
6
|
424
|
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types
// REQUIRES: tools-release,no_asserts
struct S {
let s: String
}
func rdar22282851(_ a: [S]) -> [S] {
let result = a.filter { $0.s == "hello" }.sorted { $0.s < $1.s || ($0.s == $1.s && $0.s < $1.s) && $0.s >= $1.s }
return result
}
|
apache-2.0
|
0fc1376d5f02cb84b4918aa4955a6291
| 37.545455 | 183 | 0.646226 | 2.735484 | false | false | false | false |
460467069/smzdm
|
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Home(首页)/BaiCai(白菜专区)/View/ZZBaiCaiNewestCell.swift
|
1
|
1130
|
//
// ZZBaiCaiNewestCell.swift
// 什么值得买
//
// Created by Wang_ruzhou on 2016/11/29.
// Copyright © 2016年 Wang_ruzhou. All rights reserved.
//
import UIKit
class ZZBaiCaiNewestCell: UICollectionViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var mallLabel: UILabel!
@IBOutlet weak var commentBtn: UIButton!
var worthyArticle: ZZWorthyArticle? {
didSet {
guard let worthyArticle = worthyArticle else { return }
iconView.zdm_setImage(urlStr: worthyArticle.article_pic, placeHolder: nil)
titleLabel.text = worthyArticle.article_title
subTitleLabel.text = worthyArticle.article_price
mallLabel.text = worthyArticle.article_mall
commentBtn.setTitle(worthyArticle.article_comment, for: .normal)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
layer.cornerRadius = 3.0
layer.masksToBounds = true
}
}
|
mit
|
2db26cc4f2536c6b1f58c637018a9fa4
| 28.394737 | 86 | 0.655327 | 4.199248 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureDashboard/Sources/FeatureDashboardUI/WalletActionScreen/Custody/CustodyInformationViewController/CustodyInformationViewController.swift
|
1
|
1927
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformUIKit
final class CustodyInformationViewController: BaseScreenViewController {
// MARK: Private Properties
private let presenter: CustodyInformationScreenPresenter
// MARK: Private IBOutlets
@IBOutlet private var okButtonView: ButtonView!
@IBOutlet private var backgroundImageView: UIImageView!
@IBOutlet private var walletIllustrationImageView: UIImageView!
@IBOutlet private var primaryDescriptionLabel: UILabel!
@IBOutlet private var secondaryDescriptionLabel: UILabel!
// MARK: - Setup
init(presenter: CustodyInformationScreenPresenter) {
self.presenter = presenter
super.init(nibName: CustodyInformationViewController.objectName, bundle: .module)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
okButtonView.viewModel = presenter.okButtonViewModel
primaryDescriptionLabel.content = presenter.description
secondaryDescriptionLabel.content = presenter.subDescription
titleViewStyle = presenter.titleView
set(
barStyle: presenter.barStyle,
leadingButtonStyle: presenter.leadingButton,
trailingButtonStyle: presenter.trailingButton
)
applyAnimation()
}
private func applyAnimation() {
UIView.animate(
withDuration: 1.0,
delay: 0,
options: [.repeat, .autoreverse, .curveEaseInOut],
animations: {
self.walletIllustrationImageView.transform = .init(translationX: 0.0, y: 7.0)
},
completion: nil
)
}
override func navigationBarTrailingButtonPressed() {
presenter.navigationBarTrailingButtonTapped()
}
}
|
lgpl-3.0
|
99f62220d2a2f7a7c68071533d2ebdb6
| 30.064516 | 93 | 0.682243 | 5.440678 | false | false | false | false |
alloyapple/GooseGtk
|
Sources/TreeViewExample/main.swift
|
1
|
975
|
//
// Created by color on 12/11/17.
//
import Foundation
import GooseGtk
extension Sequence {
func sum<N: Numeric>(by valueProvider: (Element) -> N) -> N {
return reduce(0) { result, element in
return result + valueProvider(element)
}
}
}
struct level {
public let score: Int
}
let levels: [level] = []
_ = levels.sum{ $0.score }
//let app = Application(id: "abc")
//app.keyWindow.rootViewController = TreeViewExampleViewController()
//app.run()
//
//protocol Identifiable {
// associatedtype ID
// static var idKey: WritableKeyPath<Self, ID> { get }
//}
//
//struct Person: Identifiable {
// var socialSecurityNumber: String
// var name: String
// static var idKey = \Person.socialSecurityNumber
//}
//
//struct Book: Identifiable {
// var isbn: String
// var title: String
// static var idKey = \Book.isbn
//}
//
//func printId<T: Identifiable>(thing: T) {
// print("\(thing[keyPath: T.idKey])")
//}
|
apache-2.0
|
816d34b3efd7be5a0187f35685e82e46
| 19.333333 | 68 | 0.631795 | 3.494624 | false | false | false | false |
huonw/swift
|
test/SourceKit/InterfaceGen/gen_swift_source.swift
|
14
|
1108
|
// REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/Foo2.swift -- %S/Inputs/Foo2.swift %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t > %t.response
// RUN: diff -u %s.response %t.response
// RUN: %sourcekitd-test -req=interface-gen-open %S/Inputs/Foo2.swift -- %S/Inputs/Foo2.swift %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \
// RUN: == -req=cursor -pos=18:49 | %FileCheck -check-prefix=CHECK1 %s
// The cursor points to 'FooOverlayClassBase' inside the list of base classes, see 'gen_swift_source.swift.response'
// CHECK1: FooOverlayClassBase
// CHECK1: s:4Foo219FooOverlayClassBaseC
// CHECK1: FooOverlayClassBase.Type
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/UnresolvedExtension.swift -- %S/Inputs/UnresolvedExtension.swift | %FileCheck -check-prefix=CHECK2 %s
// CHECK2: extension ET
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/Foo3.swift -- %S/Inputs/Foo3.swift | %FileCheck -check-prefix=CHECK3 %s
// CHECK3: public class C {
|
apache-2.0
|
c7ee8236d3a72e2988aaaf919b6082a1
| 51.761905 | 169 | 0.731047 | 3.052342 | false | true | false | false |
huonw/swift
|
test/DebugInfo/linetable-cleanups.swift
|
4
|
1127
|
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// TODO: check why this is failing on linux
// REQUIRES: OS=macosx
func markUsed<T>(_ t: T) {}
class Person {
var name = "No Name"
var age = 0
}
func main() {
var person = Person()
var b = [0,1,13]
for element in b {
markUsed("element = \(element)")
}
markUsed("Done with the for loop")
// CHECK: call {{.*}}void @"$S4main8markUsedyyxlF"
// CHECK: br label
// CHECK: <label>:
// CHECK: call %Ts16IndexingIteratorVySaySiGG* @"$Ss16IndexingIteratorVySaySiGGWOh"(%Ts16IndexingIteratorVySaySiGG* %{{.*}}), !dbg ![[LOOPHEADER_LOC:.*]]
// CHECK: call {{.*}}void @"$S4main8markUsedyyxlF"
// The cleanups should share the line number with the ret stmt.
// CHECK: call %TSa* @"$SSaySiGWOh"(%TSa* %{{.*}}), !dbg ![[CLEANUPS:.*]]
// CHECK-NEXT: !dbg ![[CLEANUPS]]
// CHECK-NEXT: llvm.lifetime.end
// CHECK-NEXT: load
// CHECK-NEXT: swift_release
// CHECK-NEXT: bitcast
// CHECK-NEXT: llvm.lifetime.end
// CHECK-NEXT: ret void, !dbg ![[CLEANUPS]]
// CHECK: ![[CLEANUPS]] = !DILocation(line: [[@LINE+1]], column: 1,
}
main()
|
apache-2.0
|
943ed23314a3c5157d2bb18f98cb0e9c
| 30.305556 | 153 | 0.62378 | 3.229226 | false | false | false | false |
glassonion1/R9HTTPRequest
|
R9HTTPRequest/HTTPClient.swift
|
1
|
2172
|
//
// HTTPClient.swift
// R9HTTPRequest
//
// Created by taisuke fujita on 2017/10/03.
// Copyright © 2017年 Revolution9. All rights reserved.
//
import Foundation
import RxSwift
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
public enum HttpClientMethodType: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
public protocol HttpClient {
associatedtype ResponseType
func get(url: URL, headers: HTTPHeaders?) -> Observable<ResponseType>
func post(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType>
func put(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType>
func patch(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType>
func delete(url: URL, headers: HTTPHeaders?) -> Observable<ResponseType>
func action(method: HttpClientMethodType, url: URL, requestBody: Data?, headers: HTTPHeaders?) -> Observable<ResponseType>
}
public extension HttpClient {
public func get(url: URL, headers: HTTPHeaders?) -> Observable<ResponseType> {
return action(method: .get, url: url, requestBody: nil, headers: headers)
}
public func post(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType> {
return action(method: .post, url: url, requestBody: requestBody?.data(using: .utf8), headers: headers)
}
public func put(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType> {
return action(method: .put, url: url, requestBody: requestBody?.data(using: .utf8), headers: headers)
}
public func patch(url: URL, requestBody: String?, headers: HTTPHeaders?) -> Observable<ResponseType> {
return action(method: .patch, url: url, requestBody: requestBody?.data(using: .utf8), headers: headers)
}
public func delete(url: URL, headers: HTTPHeaders?) -> Observable<ResponseType> {
return action(method: .delete, url: url, requestBody: nil, headers: headers)
}
}
|
mit
|
5981f4f6f23f8074f7e08951d012d118
| 37.732143 | 126 | 0.69018 | 4.21165 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/SensorData/ImportDocumentOperation.swift
|
1
|
3218
|
/*
* 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 Foundation
/// An operation that encapsulates the full process of importing a .sj file.
class ImportDocumentOperation: GroupOperation {
/// Designated initialzer.
///
/// - Parameters:
/// - sourceURL: The source URL of the imported document as given by the system.
/// - zipURL: The URL where the source file will be copied.
/// - extractionURL: The URL where the file will be extracted.
/// - experimentURL: The URL of the new experiment that will be created.
/// - sensorDataManager: A sensor data manager.
/// - metadataManager: A metadata manager.
init(sourceURL: URL,
zipURL: URL,
extractionURL: URL,
experimentURL: URL,
sensorDataManager: SensorDataManager,
metadataManager: MetadataManager) {
// Copy the file, Unzip it, import the experiment, then clean up.
let copySourceOperation = CopyFileOperation(fromURL: sourceURL, toURL: zipURL)
let unzipOperation = UnzipOperation(sourceURL: zipURL, destinationURL: extractionURL)
let importExperimentOperation = ImportExperimentOperation(importDirectoryURL: extractionURL,
metadataManager: metadataManager)
let importSensorDataOperation =
ImportSensorDataFromProtoOperation(sensorDataManager: sensorDataManager)
let copyImportedFilesOperation =
CopyImportedFilesOperation(destinationExperimentURL: experimentURL)
let removeExtractedOperation = RemoveFileOperation(url: extractionURL)
let removeZipOperation = RemoveFileOperation(url: zipURL)
// Set up dependencies.
unzipOperation.addDependency(copySourceOperation)
importExperimentOperation.addDependency(unzipOperation)
importSensorDataOperation.addDependency(importExperimentOperation)
copyImportedFilesOperation.addDependency(importExperimentOperation)
// The cleanup operations depend on both copy and import sensor data finishing.
removeExtractedOperation.addDependency(copyImportedFilesOperation)
removeExtractedOperation.addDependency(importSensorDataOperation)
removeZipOperation.addDependency(copyImportedFilesOperation)
removeZipOperation.addDependency(importSensorDataOperation)
super.init(operations: [copySourceOperation,
unzipOperation,
importExperimentOperation,
importSensorDataOperation,
copyImportedFilesOperation,
removeExtractedOperation,
removeZipOperation])
}
}
|
apache-2.0
|
4f07938f2fe5f99fdc93b8506ebd84fb
| 44.971429 | 96 | 0.716283 | 5.140575 | false | false | false | false |
tellowkrinkle/Sword
|
Sources/Sword/Rest/Request.swift
|
1
|
5790
|
//
// Request.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
import Foundation
import Dispatch
/// HTTP Handler
extension Sword {
// MARK: Functions
/**
Actual HTTP Request
- parameter url: URL to request
- parameter params: Optional URL Query Parameters to send
- parameter body: Optional Data to send to server
- parameter file: Optional for when files
- parameter authorization: Whether or not the Authorization header is required by Discord
- parameter method: Type of HTTP Method
- parameter rateLimited: Whether or not the HTTP request needs to be rate limited
- parameter reason: Optional for when user wants to specify audit-log reason
*/
func request(_ endpoint: Endpoint, params: [String: Any]? = nil, body: [String: Any]? = nil, file: String? = nil, authorization: Bool = true, rateLimited: Bool = true, reason: String? = nil, then completion: @escaping (Any?, RequestError?) -> ()) {
let sema = DispatchSemaphore(value: 0) //Provide a way to urlsession from command line
let endpointInfo = endpoint.httpInfo
var route = self.getRoute(for: endpointInfo.url)
if route.hasSuffix("/messages/:id") && endpointInfo.method == .delete {
route += ".delete"
}
var urlString = "https://discordapp.com/api/v7\(endpointInfo.url)"
if let params = params {
urlString += "?"
urlString += params.map({ key, value in "\(key)=\(value)" }).joined(separator: "&")
}
guard let url = URL(string: urlString) else {
self.error("[Sword] Used an invalid URL: \"\(urlString)\". Please report this.")
return
}
var request = URLRequest(url: url)
request.httpMethod = endpointInfo.method.rawValue
if authorization {
if self.options.isBot {
request.addValue("Bot \(token)", forHTTPHeaderField: "Authorization")
}else {
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
if let reason = reason {
request.addValue(reason.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!, forHTTPHeaderField: "X-Audit-Log-Reason")
}
request.addValue("DiscordBot (https://github.com/Azoy/Sword, 0.7.0)", forHTTPHeaderField: "User-Agent")
if let body = body {
if let array = body["array"] as? [Any] {
request.httpBody = array.createBody()
}else {
request.httpBody = body.createBody()
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
#if os(macOS)
if let file = file {
let boundary = createBoundary()
let payloadJson: String?
if let array = body?["array"] as? [Any] {
payloadJson = array.encode()
}else {
payloadJson = body?.encode()
}
request.httpBody = try? self.createMultipartBody(with: payloadJson, fileUrl: file, boundary: boundary)
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
}
#endif
let task = self.session.dataTask(with: request) { [unowned self, unowned sema] data, response, error in
let response = response as! HTTPURLResponse
let headers = response.allHeaderFields
if error != nil {
#if !os(Linux)
completion(nil, RequestError(error! as NSError))
#else
completion(nil, RequestError(error as! NSError))
#endif
sema.signal()
return
}
if rateLimited {
self.handleRateLimitHeaders(headers["x-ratelimit-limit"], headers["x-ratelimit-reset"], (headers["Date"] as! String).httpDate.timeIntervalSince1970, route)
}
if response.statusCode == 204 {
completion(nil, nil)
sema.signal()
return
}
let returnedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
if response.statusCode != 200 && response.statusCode != 201 {
if response.statusCode == 429 {
print("[Sword] You're being rate limited. (This shouldn't happen, check your system clock)")
let retryAfter = Int(headers["retry-after"] as! String)!
let global = headers["x-ratelimit-global"] as? Bool
guard global == nil else {
self.isGloballyLocked = true
self.globalQueue.asyncAfter(deadline: DispatchTime.now() + .seconds(retryAfter)) { [unowned self] in
self.globalUnlock()
}
sema.signal()
return
}
self.globalQueue.asyncAfter(deadline: DispatchTime.now() + .seconds(retryAfter)) { [unowned self] in
self.request(endpoint, body: body, file: file, authorization: authorization, rateLimited: rateLimited, then: completion)
}
}
if response.statusCode >= 500 {
self.globalQueue.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) { [unowned self] in
self.request(endpoint, body: body, file: file, authorization: authorization, rateLimited: rateLimited, then: completion)
}
sema.signal()
return
}
completion(nil, RequestError(response.statusCode, returnedData!))
sema.signal()
return
}
completion(returnedData, nil)
sema.signal()
}
let apiCall = { [unowned self] in
guard rateLimited, self.rateLimits[route] != nil else {
task.resume()
sema.wait()
return
}
let item = DispatchWorkItem {
task.resume()
sema.wait()
}
self.rateLimits[route]!.queue(item)
}
if !self.isGloballyLocked {
apiCall()
}else {
self.globalRequestQueue.append(apiCall)
}
}
}
|
mit
|
026f4ebc35244203608ae17ea216383f
| 29.468421 | 250 | 0.627051 | 4.412348 | false | false | false | false |
rporzuc/FindFriends
|
FindFriends/FindFriends/PeopleNearby/MapView/UserDatailsViewController.swift
|
1
|
1644
|
//
// UserDatailsViewController.swift
// FindFriends
//
// Created by MacOSXRAFAL on 17/11/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import UIKit
class UserDatailsViewController: UIViewController {
var userId : Int?
@IBOutlet var centerView: UIView!
@IBOutlet var imagePerson: UIImageView!
@IBOutlet var labelName: UILabel!
@IBOutlet var labelSex: UILabel!
@IBOutlet var labelAge: UILabel!
@IBOutlet var labelDescription: UILabel!
@IBOutlet var buttonSendMessage: UIButton!
var parentMapViewDelegate : MapViewController?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
self.centerView.layer.cornerRadius = 15
self.centerView.layer.borderColor = UIColor.white.cgColor
self.centerView.layer.borderWidth = 5
self.labelDescription.numberOfLines = 0
self.labelDescription.lineBreakMode = .byWordWrapping
self.labelDescription.sizeToFit()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let tagTouch = touches.first?.view?.tag
if tagTouch == 99
{
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func buttonSendMessageClicked(_ sender: UIButton) {
self.dismiss(animated: true) {
if self.parentMapViewDelegate != nil{
self.parentMapViewDelegate?.returnAndShowMessagesView(id_converser: self.userId!)
}
}
}
}
|
gpl-3.0
|
1c2fac165ea1ae5a7e2608025fabba89
| 27.327586 | 97 | 0.642118 | 4.846608 | false | false | false | false |
Antondomashnev/Sourcery
|
Pods/SourceKittenFramework/Source/SourceKittenFramework/Clang+SourceKitten.swift
|
1
|
10054
|
//
// Clang+SourceKitten.swift
// SourceKitten
//
// Created by Thomas Goyne on 9/17/15.
// Copyright © 2015 SourceKitten. All rights reserved.
//
#if !os(Linux)
#if SWIFT_PACKAGE
import Clang_C
#endif
import Foundation
import SWXMLHash
private var _interfaceUUIDMap = [String: String]()
private var _interfaceUUIDMapLock = NSLock()
/// Thread safe read from sourceKitUID map
private func uuidString(`for` sourceKitUID: String) -> String? {
_interfaceUUIDMapLock.lock()
defer { _interfaceUUIDMapLock.unlock() }
return _interfaceUUIDMap[sourceKitUID]
}
/// Thread safe write from sourceKitUID map
private func setUUIDString(uidString: String, `for` file: String) {
_interfaceUUIDMapLock.lock()
defer { _interfaceUUIDMapLock.unlock() }
_interfaceUUIDMap[file] = uidString
}
struct ClangIndex {
private let index = clang_createIndex(0, 1)
func open(file: String, args: [UnsafePointer<Int8>?]) -> CXTranslationUnit {
return clang_createTranslationUnitFromSourceFile(index, file, Int32(args.count), args, 0, nil)!
}
}
public struct ClangAvailability {
public let alwaysDeprecated: Bool
public let alwaysUnavailable: Bool
public let deprecationMessage: String?
public let unavailableMessage: String?
}
extension CXString: CustomStringConvertible {
func str() -> String? {
if let cString = clang_getCString(self) {
return String(validatingUTF8: cString)
}
return nil
}
public var description: String {
return str() ?? "<null>"
}
}
extension CXTranslationUnit {
func cursor() -> CXCursor {
return clang_getTranslationUnitCursor(self)
}
}
extension CXCursor {
func location() -> SourceLocation {
return SourceLocation(clangLocation: clang_getCursorLocation(self))
}
func extent() -> (start: SourceLocation, end: SourceLocation) {
let extent = clang_getCursorExtent(self)
let start = SourceLocation(clangLocation: clang_getRangeStart(extent))
let end = SourceLocation(clangLocation: clang_getRangeEnd(extent))
return (start, end)
}
func shouldDocument() -> Bool {
return clang_isDeclaration(kind) != 0 &&
kind != CXCursor_ParmDecl &&
kind != CXCursor_TemplateTypeParameter &&
clang_Location_isInSystemHeader(clang_getCursorLocation(self)) == 0
}
func declaration() -> String? {
let comment = parsedComment()
if comment.kind() == CXComment_Null {
return str()
}
let commentXML = clang_FullComment_getAsXML(comment).str() ?? ""
guard let rootXML = SWXMLHash.parse(commentXML).children.first else {
fatalError("couldn't parse XML")
}
guard let text = rootXML["Declaration"].element?.text,
!text.isEmpty else {
return nil
}
return text
.replacingOccurrences(of: "\n@end", with: "")
.replacingOccurrences(of: "@property(", with: "@property (")
}
func objCKind() -> ObjCDeclarationKind {
return ObjCDeclarationKind(kind)
}
func str() -> String? {
let cursorExtent = extent()
let contents = try! String(contentsOfFile: cursorExtent.start.file, encoding: .utf8)
return contents.substringWithSourceRange(start: cursorExtent.start, end: cursorExtent.end)
}
func name() -> String {
let type = objCKind()
if type == .category, let usrNSString = usr() as NSString? {
let ext = (usrNSString.range(of: "c:objc(ext)").location == 0)
let regex = try! NSRegularExpression(pattern: "(\\w+)@(\\w+)", options: [])
let range = NSRange(location: 0, length: usrNSString.length)
let matches = regex.matches(in: usrNSString as String, options: [], range: range)
if !matches.isEmpty {
let categoryOn = usrNSString.substring(with: matches[0].range(at: 1))
let categoryName = ext ? "" : usrNSString.substring(with: matches[0].range(at: 2))
return "\(categoryOn)(\(categoryName))"
} else {
fatalError("Couldn't get category name")
}
}
let spelling = clang_getCursorSpelling(self).str()!
if type == .methodInstance {
return "-" + spelling
} else if type == .methodClass {
return "+" + spelling
}
return spelling
}
func usr() -> String? {
return clang_getCursorUSR(self).str()
}
func platformAvailability() -> ClangAvailability {
var alwaysDeprecated: Int32 = 0
var alwaysUnavailable: Int32 = 0
var deprecationString = CXString()
var unavailableString = CXString()
_ = clang_getCursorPlatformAvailability(self,
&alwaysDeprecated,
&deprecationString,
&alwaysUnavailable,
&unavailableString,
nil,
0)
return ClangAvailability(alwaysDeprecated: alwaysDeprecated != 0,
alwaysUnavailable: alwaysUnavailable != 0,
deprecationMessage: deprecationString.description,
unavailableMessage: unavailableString.description)
}
func visit(_ block: @escaping (CXCursor, CXCursor) -> CXChildVisitResult) {
_ = clang_visitChildrenWithBlock(self, block)
}
func parsedComment() -> CXComment {
return clang_Cursor_getParsedComment(self)
}
func flatMap<T>(_ block: @escaping (CXCursor) -> T?) -> [T] {
var ret = [T]()
visit { cursor, _ in
if let val = block(cursor) {
ret.append(val)
}
return CXChildVisit_Continue
}
return ret
}
func commentBody() -> String? {
let rawComment = clang_Cursor_getRawCommentText(self).str()
let replacements = [
"@param ": "- parameter: ",
"@return ": "- returns: ",
"@warning ": "- warning: ",
"@see ": "- see: ",
"@note ": "- note: "
]
var commentBody = rawComment?.commentBody()
for (original, replacement) in replacements {
commentBody = commentBody?.replacingOccurrences(of: original, with: replacement)
}
return commentBody
}
func swiftDeclaration(compilerArguments: [String]) -> String? {
let file = location().file
let swiftUUID: String
if let uuid = uuidString(for: file) {
swiftUUID = uuid
} else {
swiftUUID = NSUUID().uuidString
setUUIDString(uidString: swiftUUID, for: file)
// Generate Swift interface, associating it with the UUID
_ = Request.interface(file: file, uuid: swiftUUID, arguments: compilerArguments).send()
}
guard let usr = usr(),
let usrOffset = Request.findUSR(file: swiftUUID, usr: usr).send()[SwiftDocKey.offset.rawValue] as? Int64 else {
return nil
}
let cursorInfo = Request.cursorInfo(file: swiftUUID, offset: usrOffset, arguments: compilerArguments).send()
if let docsXML = cursorInfo[SwiftDocKey.fullXMLDocs.rawValue] as? String,
let swiftDeclaration = SWXMLHash.parse(docsXML).children.first?["Declaration"].element?.text {
return swiftDeclaration
}
if let annotatedDeclarationXML = cursorInfo[SwiftDocKey.annotatedDeclaration.rawValue] as? String,
let swiftDeclaration = SWXMLHash.parse(annotatedDeclarationXML).element?.recursiveText {
return swiftDeclaration
}
return nil
}
}
extension CXComment {
func paramName() -> String? {
guard clang_Comment_getKind(self) == CXComment_ParamCommand else { return nil }
return clang_ParamCommandComment_getParamName(self).str()
}
func paragraph() -> CXComment {
return clang_BlockCommandComment_getParagraph(self)
}
func paragraphToString(kindString: String? = nil) -> [Text] {
if kind() == CXComment_VerbatimLine {
return [.verbatim(clang_VerbatimLineComment_getText(self).str()!)]
} else if kind() == CXComment_BlockCommand {
return (0..<count()).reduce([]) { returnValue, childIndex in
return returnValue + self[childIndex].paragraphToString()
}
}
guard kind() == CXComment_Paragraph else {
print("not a paragraph: \(kind())")
return []
}
let paragraphString = (0..<count()).reduce("") { paragraphString, childIndex in
let child = self[childIndex]
if let text = clang_TextComment_getText(child).str() {
return paragraphString + (paragraphString != "" ? "\n" : "") + text
} else if child.kind() == CXComment_InlineCommand {
// @autoreleasepool etc. get parsed as commands when not in code blocks
let inlineCommand = child.commandName().map { "@" + $0 }
return paragraphString + (inlineCommand ?? "")
}
fatalError("not text: \(child.kind())")
}
return [.para(paragraphString.removingCommonLeadingWhitespaceFromLines(), kindString)]
}
func kind() -> CXCommentKind {
return clang_Comment_getKind(self)
}
func commandName() -> String? {
return clang_BlockCommandComment_getCommandName(self).str() ??
clang_InlineCommandComment_getCommandName(self).str()
}
func count() -> UInt32 {
return clang_Comment_getNumChildren(self)
}
subscript(idx: UInt32) -> CXComment {
return clang_Comment_getChild(self, idx)
}
}
#endif
|
mit
|
cd89d117b38f642b69a309e9f509b5ad
| 34.15035 | 125 | 0.590968 | 4.628453 | false | false | false | false |
HenvyLuk/BabyGuard
|
testSwift/testSwift/ViewController.swift
|
1
|
5671
|
//
// ViewController.swift
// testSwift
//
// Created by csh on 16/7/4.
// Copyright © 2016年 csh. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate, UIAlertViewDelegate{
@IBOutlet weak var testBtn: UIButton!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var testView: UIView!
var stuDic = Dictionary<String, String>()
var namesOfIntegers = Dictionary<Int, String>()
var a = 0
var timerInterval = CGFloat(0)
@IBAction func testAction(sender: AnyObject) {
let positionAnimation = POPSpringAnimation(propertyNamed: "positionX")
//positionAnimation.velocity = 10000
positionAnimation.springBounciness = 20
self.testBtn.layer.pop_addAnimation(positionAnimation, forKey: "positionAnimation")
}
override func viewDidLoad() {
super.viewDidLoad()
print(self.view.backgroundColor.debugDescription)
self.addScrollView()
self.addTimer()
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.test), userInfo: nil, repeats: true)
print(self.view.frame.height)
}
func test() {
//print("aaa")
a += 1
//print(a,self.scrollView.contentOffset.y)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// let date = NSDate()
// let dateFormatter = NSDateFormatter()
// dateFormatter.locale = NSLocale.currentLocale()
// dateFormatter.dateFormat = "MM.dd"
// let convertedDate = dateFormatter.stringFromDate(date)
// let str = convertedDate.stringByReplacingOccurrencesOfString("0", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
var str = "0808"
let index = str.startIndex.advancedBy(2)
str.insert(".", atIndex: index)
print(str)
//let alertView = UIAlertView()
// alertView.delegate = self
// alertView.title = "Title"
// alertView.message = "Message"
// alertView.addButtonWithTitle("OK")
// alertView.show()
//var alertView = UIAlertView(title: "提示", message: "qqqqqq", delegate: self, cancelButtonTitle: "确定")
///alertView.show()
//self.performSelector(#selector(ViewController.dissmiss), withObject: alertView, afterDelay: 1.0)
}
// func dissmiss(withAlertView alertView: UIAlertView) {
//
// print("dddddddd")
// alertView.dismissWithClickedButtonIndex(0, animated: true)
//
//
// }
func tetstClick() {
let st = UIStoryboard(name: "Main", bundle: nil)
let vc = st.instantiateViewControllerWithIdentifier("1")
self.presentViewController(vc, animated: true) {
print("p1")
}
}
func addScrollView() {
self.scrollView.delegate = self
for i in 1..<3 {
let imageViewX = CGFloat(0)
let imageViewY = CGFloat(i - 1) * (self.scrollView.frame.height)
let imageViewW = self.view.bounds.size.width
let imageViewH = self.scrollView.frame.height
let myImageView = UIImageView.init(frame: CGRectMake(imageViewX, imageViewY, imageViewW, imageViewH))
let name = String(i)
myImageView.image = UIImage(named: name)
self.scrollView.addSubview(myImageView)
}
self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, self.scrollView.frame.height * 2)
}
func addTimer() {
let bottomOffset = CGPointMake(0, self.view.bounds.size.height * 0.5)
let scrollDurationInSeconds = CGFloat(2.0)
let totalScrollAmount = CGFloat(bottomOffset.y)
let timerInterval = scrollDurationInSeconds / totalScrollAmount
self.timerInterval = timerInterval
NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(ViewController.cycleImage), userInfo: nil, repeats: true)
//#selector(LoginViewController.cycleImage)
}
func cycleImage(withTimer timer: NSTimer) {
var newScrollViewContentOffset = self.scrollView.contentOffset
newScrollViewContentOffset.y += 1
self.scrollView.contentOffset = newScrollViewContentOffset
if (newScrollViewContentOffset.y == self.view.frame.size.height * 0.5) {
timer.invalidate()
print("qqqqqqq")
NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(ViewController.cycleImage2), userInfo: nil, repeats: true)
}
}
func cycleImage2(withTimer timer: NSTimer) {
var newScrollViewContentOffset = self.scrollView.contentOffset
newScrollViewContentOffset.y -= 1
self.scrollView.contentOffset = newScrollViewContentOffset
if (newScrollViewContentOffset.y == 0) {
timer.invalidate()
print("wwwwwww")
NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(ViewController.cycleImage), userInfo: nil, repeats: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
d3976df566f5c662620b0eb56ad3f6bc
| 31.906977 | 166 | 0.620141 | 4.960561 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/NewVersion/Search/ZSSourceManager.swift
|
1
|
6147
|
//
// ZSSourceManagerr.swift
// zhuishushenqi
//
// Created by caony on 2019/11/11.
// Copyright © 2019 QS. All rights reserved.
//
// 书籍来源管理类
import UIKit
class ZSSourceManager {
var sources:[ZSAikanParserModel] = []
static let selectedSourceKey = "selectedSourceKey"
static let share = ZSSourceManager()
private init() {
unpack()
}
private func unpack() {
let modifyfilePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!.appending("/source/HtmlParserModelData_edit.dat")
let originialfilePath_edit = Bundle(for: ZSSourceManager.self).path(forResource: "HtmlParserModelData_edit.dat", ofType: nil) ?? ""
let originialfilePath = Bundle(for: ZSSourceManager.self).path(forResource: "HtmlParserModelData.dat", ofType: nil) ?? ""
if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: modifyfilePath) as? [ZSAikanParserModel] {
self.sources = objs
} else if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: modifyfilePath) as? [AikanParserModel] {
self.sources = self.transform(models: objs)
} else if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: originialfilePath_edit) as? [ZSAikanParserModel] {
self.sources = objs
save()
} else if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: originialfilePath_edit) as? [AikanParserModel] {
self.sources = self.transform(models: objs)
save()
}
else if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: originialfilePath) as? [ZSAikanParserModel] {
self.sources = objs
save()
} else if let objs = NSKeyedUnarchiver.unarchiveObject(withFile: originialfilePath) as? [AikanParserModel] {
self.sources = self.transform(models: objs)
save()
}
}
private func transform(models:[AikanParserModel]) ->[ZSAikanParserModel] {
var aikans:[ZSAikanParserModel] = []
for model in models {
let aikan = ZSAikanParserModel()
// aikan.errDate = model.errDate
aikan.searchUrl = model.searchUrl
aikan.name = model.name
aikan.type = Int64(model.type)
aikan.enabled = model.enabled
aikan.checked = model.checked
aikan.searchEncoding = model.searchEncoding
aikan.host = model.host
aikan.contentReplace = model.contentReplace
aikan.contentRemove = model.contentRemove
aikan.content = model.content
aikan.chapterUrl = model.chapterUrl
aikan.chapterName = model.chapterName
aikan.chapters = model.chapters
aikan.chaptersModel = model.chaptersModel as? [ZSBookChapter] ?? []
aikan.detailBookIcon = model.detailBookIcon
aikan.detailChaptersUrl = model.detailChaptersUrl
aikan.bookLastChapterName = model.bookLastChapterName
aikan.bookUpdateTime = model.bookUpdateTime
aikan.bookUrl = model.bookUrl
aikan.bookIcon = model.bookIcon
aikan.bookDesc = model.bookDesc
aikan.bookCategory = model.bookCategory
aikan.bookAuthor = model.bookAuthor
aikan.bookName = model.bookName
aikan.books = model.books
aikan.chaptersReverse = model.chaptersReverse
aikan.detailBookDesc = model.detailBookDesc
aikans.append(aikan)
}
return aikans
}
private func save() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!.appending("/source/")
let filePath = path.appending("HtmlParserModelData_edit.dat")
let isDirectory:UnsafeMutablePointer<ObjCBool>? = UnsafeMutablePointer.allocate(capacity: 1)
if !FileManager.default.fileExists(atPath: path, isDirectory: isDirectory) {
try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
NSKeyedArchiver.archiveRootObject(self.sources, toFile: filePath)
}
func add(source:ZSAikanParserModel) {
if sources.contains(source) {
modify(source: source)
} else {
sources.append(source)
DispatchQueue.global().async {
self.save()
}
}
}
func modify(source:ZSAikanParserModel) {
var index = 0
let ts = sources
for ss in ts {
if ss.host == source.host {
sources[index] = source
break
}
index += 1
}
DispatchQueue.global().async {
self.save()
}
}
func delete(source:ZSAikanParserModel) {
var index = 0
let ts = sources
for ss in ts {
if ss.host == source.host {
sources.remove(at: index)
break
}
index += 1
}
DispatchQueue.global().async {
self.save()
}
}
func select(source:ZSAikanParserModel) {
source.checked = true
replace(source: source)
DispatchQueue.global().async {
self.save()
}
}
func unselect(source:ZSAikanParserModel) {
source.checked = false
replace(source: source)
DispatchQueue.global().async {
self.save()
}
}
func source(_ host:String) ->ZSAikanParserModel? {
var resultSource:ZSAikanParserModel?
for source in sources {
if host == source.host {
resultSource = source
break
}
}
return resultSource
}
private func replace(source:ZSAikanParserModel) {
var index = 0
let ts = sources
for ss in ts {
if ss.host == source.host {
sources[index] = source
break
}
index += 1
}
}
}
|
mit
|
321ad3ea578f4708e95ae594ddab800b
| 34.651163 | 164 | 0.594749 | 4.552339 | false | false | false | false |
outfoxx/CryptoSecurity
|
Sources/ASN1.swift
|
1
|
24669
|
//
// ASN1.swift
// CryptoSecurity
//
// Copyright © 2019 Outfox, inc.
//
//
// Distributed under the MIT License, See LICENSE for details.
//
import Foundation
public protocol ASN1Encoder {
func encode(boolean value: Bool)
func encode(integer value: Data)
func encode(bitString value: Data, bitLength: Int)
func encode(octetString value: Data)
func encode(null value: Void)
func encode(objectIdentifier value: [UInt64])
func encode(utf8String value: String)
func encode(printableString value: String)
func encode(ia5String value: String)
func encode(sequence value: [ASN1Item])
func encode(set value: [ASN1Item])
func encode(utcTime value: Date)
func encode(tag: UInt8, data: Data)
}
public protocol ASN1Item {
func encode(encoder: ASN1Encoder)
}
public struct ASN1Boolean: ASN1Item, Equatable {
public let value: Bool
public func encode(encoder: ASN1Encoder) {
encoder.encode(boolean: value)
}
public static func == (lhs: ASN1Boolean, rhs: ASN1Boolean) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1Integer: ASN1Item, Equatable {
public let value: Data
public func encode(encoder: ASN1Encoder) {
encoder.encode(integer: value)
}
var intValue: Int64 {
return value.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Int64 in
switch value.count {
case 0:
return 0
case 1:
let byte0 = ((Int64(ptr[0]) & 0xFF) << 00)
return byte0
case 2:
let byte1 = ((Int64(ptr[0]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[1]) & 0xFF) << 00)
return byte1 | byte0
case 3:
let byte2 = ((Int64(ptr[0]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[1]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[2]) & 0xFF) << 00)
return byte2 | byte1 | byte0
case 4:
let byte3 = ((Int64(ptr[0]) & 0xFF) << 24)
let byte2 = ((Int64(ptr[1]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[2]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[3]) & 0xFF) << 00)
return byte3 | byte2 | byte1 | byte0
case 5:
let byte4 = ((Int64(ptr[0]) & 0xFF) << 32)
let byte3 = ((Int64(ptr[1]) & 0xFF) << 24)
let byte2 = ((Int64(ptr[2]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[3]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[4]) & 0xFF) << 00)
return byte4 | byte3 | byte2 | byte1 | byte0
case 6:
let byte5 = ((Int64(ptr[0]) & 0xFF) << 40)
let byte4 = ((Int64(ptr[1]) & 0xFF) << 32)
let byte3 = ((Int64(ptr[2]) & 0xFF) << 24)
let byte2 = ((Int64(ptr[3]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[4]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[5]) & 0xFF) << 00)
return byte5 | byte4 | byte3 | byte2 | byte1 | byte0
case 7:
let byte6 = ((Int64(ptr[0]) & 0xFF) << 48)
let byte5 = ((Int64(ptr[1]) & 0xFF) << 40)
let byte4 = ((Int64(ptr[2]) & 0xFF) << 32)
let byte3 = ((Int64(ptr[3]) & 0xFF) << 24)
let byte2 = ((Int64(ptr[4]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[5]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[6]) & 0xFF) << 00)
return byte6 | byte5 | byte4 | byte3 | byte2 | byte1 | byte0
case 8:
let byte7 = ((Int64(ptr[0]) & 0xFF) << 56)
let byte6 = ((Int64(ptr[1]) & 0xFF) << 48)
let byte5 = ((Int64(ptr[2]) & 0xFF) << 40)
let byte4 = ((Int64(ptr[3]) & 0xFF) << 32)
let byte3 = ((Int64(ptr[4]) & 0xFF) << 24)
let byte2 = ((Int64(ptr[5]) & 0xFF) << 16)
let byte1 = ((Int64(ptr[6]) & 0xFF) << 08)
let byte0 = ((Int64(ptr[7]) & 0xFF) << 00)
return byte7 | byte6 | byte5 | byte4 | byte3 | byte2 | byte1 | byte0
default:
fatalError("Invalid intger length")
}
}
}
public static func == (lhs: ASN1Integer, rhs: ASN1Integer) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1BitString: ASN1Item, Equatable {
public let value: Data
public let length: Int
public func encode(encoder: ASN1Encoder) {
encoder.encode(bitString: value, bitLength: length)
}
public static func == (lhs: ASN1BitString, rhs: ASN1BitString) -> Bool {
return lhs.value == rhs.value && lhs.length == rhs.length
}
private func big<Container: UnsignedInteger>() -> Container {
let size = MemoryLayout<Container>.size
let prefix = [UInt8](repeating: 0, count: size)
let bytes = Array((prefix + value.reversed().map {
reverse(byte: $0)
}).suffix(size))
return bytes.withUnsafeBytes { ptr -> Container in
ptr.baseAddress!.assumingMemoryBound(to: Container.self).pointee
}
}
public func host() -> UInt8 {
return big() as UInt8
}
public func host() -> UInt16 {
var value = big() as UInt16
if NSHostByteOrder() != NS_BigEndian {
value = value.byteSwapped
}
return value
}
public func host() -> UInt32 {
var value = big() as UInt32
if NSHostByteOrder() != NS_BigEndian {
value = value.byteSwapped
}
return value
}
public func host() -> UInt64 {
var value = big() as UInt64
if NSHostByteOrder() != NS_BigEndian {
value = value.byteSwapped
}
return value
}
}
public struct ASN1OctetString: ASN1Item, Equatable {
public let value: Data
public func encode(encoder: ASN1Encoder) {
encoder.encode(octetString: value)
}
public static func == (lhs: ASN1OctetString, rhs: ASN1OctetString) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1Null: ASN1Item, Equatable {
public func encode(encoder: ASN1Encoder) {
encoder.encode(null: Void())
}
public static func == (lhs: ASN1Null, rhs: ASN1Null) -> Bool {
return true
}
}
public struct ASN1ObjectIdentifier: ASN1Item, Equatable {
public let value: [UInt64]
public func encode(encoder: ASN1Encoder) {
encoder.encode(objectIdentifier: value)
}
public static func == (lhs: ASN1ObjectIdentifier, rhs: ASN1ObjectIdentifier) -> Bool {
return lhs.value == rhs.value
}
}
public protocol ASN1String: ASN1Item {
var value: String { get }
}
public struct ASN1UTF8String: ASN1Item, ASN1String, Equatable {
public let value: String
public func encode(encoder: ASN1Encoder) {
encoder.encode(utf8String: value)
}
public static func == (lhs: ASN1UTF8String, rhs: ASN1UTF8String) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1PrintableString: ASN1Item, ASN1String, Equatable {
public let value: String
public func encode(encoder: ASN1Encoder) {
encoder.encode(printableString: value)
}
public static func == (lhs: ASN1PrintableString, rhs: ASN1PrintableString) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1IA5String: ASN1Item, ASN1String, Equatable {
public let value: String
public func encode(encoder: ASN1Encoder) {
encoder.encode(ia5String: value)
}
public static func == (lhs: ASN1IA5String, rhs: ASN1IA5String) -> Bool {
return lhs.value == rhs.value
}
}
public struct ASN1Sequence: ASN1Item, Equatable {
public let value: [ASN1Item]
public func encode(encoder: ASN1Encoder) {
encoder.encode(sequence: value)
}
public static func == (lhs: ASN1Sequence, rhs: ASN1Sequence) -> Bool {
for (lhs, rhs) in zip(lhs.value, rhs.value) {
if lhs != rhs { return false }
}
return true
}
}
public struct ASN1Set: ASN1Item, Equatable {
public let value: [ASN1Item]
public func encode(encoder: ASN1Encoder) {
encoder.encode(set: value)
}
public static func == (lhs: ASN1Set, rhs: ASN1Set) -> Bool {
for (lhs, rhs) in zip(lhs.value, rhs.value) {
if lhs != rhs { return false }
}
return true
}
}
public struct ASN1UTCTime: ASN1Item, Equatable {
public let timestamp: Date
public func encode(encoder: ASN1Encoder) {
encoder.encode(utcTime: timestamp)
}
public static func == (lhs: ASN1UTCTime, rhs: ASN1UTCTime) -> Bool {
return lhs.timestamp == rhs.timestamp
}
}
public struct ASN1Object: ASN1Item, Equatable {
public let tag: UInt8
public let data: Data
public func encode(encoder: ASN1Encoder) {
encoder.encode(tag: tag, data: data)
}
public static func == (lhs: ASN1Object, rhs: ASN1Object) -> Bool {
return lhs.tag == rhs.tag && lhs.data == rhs.data
}
}
func == (lhs: ASN1Item, rhs: ASN1Item) -> Bool {
if let lhs = lhs as? ASN1Boolean, let rhs = rhs as? ASN1Boolean {
return lhs == rhs
}
if let lhs = lhs as? ASN1Integer, let rhs = rhs as? ASN1Integer {
return lhs == rhs
}
if let lhs = lhs as? ASN1BitString, let rhs = rhs as? ASN1BitString {
return lhs == rhs
}
if let lhs = lhs as? ASN1OctetString, let rhs = rhs as? ASN1OctetString {
return lhs == rhs
}
if let lhs = lhs as? ASN1Null, let rhs = rhs as? ASN1Null {
return lhs == rhs
}
if let lhs = lhs as? ASN1ObjectIdentifier, let rhs = rhs as? ASN1ObjectIdentifier {
return lhs == rhs
}
if let lhs = lhs as? ASN1UTF8String, let rhs = rhs as? ASN1UTF8String {
return lhs == rhs
}
if let lhs = lhs as? ASN1PrintableString, let rhs = rhs as? ASN1PrintableString {
return lhs == rhs
}
if let lhs = lhs as? ASN1Sequence, let rhs = rhs as? ASN1Sequence {
return lhs == rhs
}
if let lhs = lhs as? ASN1Set, let rhs = rhs as? ASN1Set {
return lhs == rhs
}
if let lhs = lhs as? ASN1UTCTime, let rhs = rhs as? ASN1UTCTime {
return lhs == rhs
}
if let lhs = lhs as? ASN1Object, let rhs = rhs as? ASN1Object {
return lhs == rhs
}
return false
}
func != (lhs: ASN1Item, rhs: ASN1Item) -> Bool {
return !(lhs == rhs)
}
public struct ASN1 {
/**
Native value wrapping methods
**/
public static func item(wrapping value: Any?) -> ASN1Item {
guard let value = value else {
return null()
}
switch value {
case let it as ASN1Item:
return it
case let it as [ASN1Item]:
return sequence(of: it)
case let it as String:
return utf8String(of: it)
case let it as Bool:
return boolean(of: it)
case let it as Data:
return octetString(of: it)
case let it as Date:
return utcTime(of: it)
case let it as [UInt64]:
return oid(of: it)
case let it as Int:
return integer(of: toData(it))
case let it as UInt:
return integer(of: toData(it))
case let it as Int8:
return integer(of: toData(it))
case let it as UInt8:
return integer(of: toData(it))
case let it as Int16:
return integer(of: toData(it))
case let it as UInt16:
return integer(of: toData(it))
case let it as Int32:
return integer(of: toData(it))
case let it as UInt32:
return integer(of: toData(it))
case let it as Int64:
return integer(of: toData(it))
case let it as UInt64:
return integer(of: toData(it))
case let it as BitSet:
return bitString(of: it)
default:
fatalError("Unsupported type")
}
}
public static func sequence(wrapping values: [Any?]) -> ASN1Sequence {
return sequence(of: values.map { item(wrapping: $0) })
}
public static func set(wrapping values: [Any?]) -> ASN1Set {
return set(of: values.map { item(wrapping: $0) })
}
/**
Item factory methods
**/
public static func object(tag: UInt8, data: Data) -> ASN1Object {
return ASN1Object(tag: tag, data: data)
}
public static func null() -> ASN1Null {
return ASN1Null()
}
public static func boolean(of value: Bool) -> ASN1Boolean {
return ASN1Boolean(value: value)
}
public static func integer(of value: UInt64) -> ASN1Integer {
return integer(of: toData(value.bigEndian))
}
public static func integer(of value: Data) -> ASN1Integer {
return value.withUnsafeBytes { (raw: UnsafeRawBufferPointer) -> ASN1Integer in
let ptr = raw.baseAddress!.assumingMemoryBound(to: UInt8.self)
var nonZero = ptr
while nonZero.pointee == 0, ptr.distance(to: nonZero) < value.count - 1 {
nonZero = nonZero.successor()
}
let off = ptr.distance(to: nonZero)
return ASN1Integer(value: value.subdata(in: off ..< value.count))
}
}
public static func bitString(of value: BitSet) -> ASN1BitString {
var lastUsedIdx = 0
var bytes = [UInt8]()
for byteIdx in 0 ..< value.bytes.count {
var byte = UInt8(0)
var offsetBitTarget = UInt8(0x80)
for offsetBitIdx in 0 ..< 8 {
let bitIdx = byteIdx * 8 + offsetBitIdx
if value[bitIdx] {
byte = byte | offsetBitTarget
lastUsedIdx = bitIdx
}
offsetBitTarget >>= 1
}
bytes.append(byte)
}
bytes = Array(bytes.prefix(through: lastUsedIdx / 8))
return ASN1BitString(value: Data(bytes: &bytes, count: bytes.count), length: lastUsedIdx + 1)
}
public static func bitString(of value: Data) -> ASN1BitString {
return bitString(of: value, bitLength: value.count * 8)
}
public static func bitString(of value: Data, bitLength: Int) -> ASN1BitString {
return ASN1BitString(value: value, length: bitLength)
}
public static func octetString(of value: Data) -> ASN1OctetString {
return ASN1OctetString(value: value)
}
public static func octetString<T>(of value: T) -> ASN1OctetString {
return ASN1OctetString(value: toData(value))
}
public static func utf8String(of value: String) -> ASN1UTF8String {
return ASN1UTF8String(value: value)
}
public static func printableString(of value: String) -> ASN1PrintableString {
return ASN1PrintableString(value: value)
}
public static func sequence(of values: ASN1Item...) -> ASN1Sequence {
return ASN1Sequence(value: values)
}
public static func sequence(of values: [ASN1Item]) -> ASN1Sequence {
return ASN1Sequence(value: values)
}
public static func set(of values: ASN1Item...) -> ASN1Set {
return ASN1Set(value: values)
}
public static func set(of values: [ASN1Item]) -> ASN1Set {
return ASN1Set(value: values)
}
public static func utcTime(of value: Date) -> ASN1UTCTime {
return ASN1UTCTime(timestamp: value)
}
public static func oid(of values: [UInt64]) -> ASN1ObjectIdentifier {
return ASN1ObjectIdentifier(value: values)
}
public static func oid(of values: UInt64...) -> ASN1ObjectIdentifier {
return oid(of: values)
}
public struct Tag {
public static let BOOLEAN: UInt8 = 0x01
public static let INTEGER: UInt8 = 0x02
public static let BITSTRING: UInt8 = 0x03
public static let OCTETSTRING: UInt8 = 0x04
public static let NULL: UInt8 = 0x05
public static let OBJECT_IDENTIFIER: UInt8 = 0x06
public static let REAL: UInt8 = 0x09
public static let UTF8STRING: UInt8 = 0x0C
public static let PRINTABLESTRING: UInt8 = 0x13
public static let IA5STRING: UInt8 = 0x16
public static let UTCTIME: UInt8 = 0x17
public static let SEQUENCE: UInt8 = 0x30
public static let SET: UInt8 = 0x31
public static func privatePrimitive(tag: UInt8) -> UInt8 {
return tag | 0x80
}
public static func privateStructured(tag: UInt8) -> UInt8 {
return tag | 0xA0
}
private init() {}
}
/**
DER Encoding
**/
public struct DER {
public static func encode(wrapping values: Any?...) -> Data {
return encode(wrapping: values)
}
public static func encode(wrapping values: [Any?]) -> Data {
return encode(items: values.map { ASN1.item(wrapping: $0) })
}
public static func encode(items: ASN1Item...) -> Data {
return encode(items: items)
}
public static func encode(items: [ASN1Item]) -> Data {
let encoder = DER.Encoder()
for item in items {
item.encode(encoder: encoder)
}
return encoder.data
}
public static func decode(data: Data) -> ASN1Item {
return data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in
var ptr = raw.baseAddress!.assumingMemoryBound(to: UInt8.self)
return parse(item: &ptr)
}
}
public class Encoder: ASN1Encoder {
var data = Data(capacity: 512)
public func append(byte: UInt8) {
var byte = byte
withUnsafePointer(to: &byte) {
data.append(UnsafePointer($0), count: 1)
}
}
public func append(length value: Int) {
switch value {
case 0x0000 ..< 0x0080:
append(byte: UInt8(value & 0x007F))
case 0x0080 ..< 0x0100:
append(byte: 0x81)
append(byte: UInt8(value & 0x00FF))
case 0x0100 ..< 0x8000:
append(byte: 0x82)
append(byte: UInt8((value & 0xFF00) >> 8))
append(byte: UInt8(value & 0xFF))
default:
fatalError("Invalid DER length")
}
}
public func append(data: Data) {
self.data.append(data)
}
public func append(tag: UInt8, length: Int) {
append(byte: tag)
append(length: length)
}
public func encode(boolean value: Bool) {
append(tag: Tag.BOOLEAN, length: 1)
append(byte: value ? 0xFF : 0x00)
}
public func encode(integer value: UInt64) {
encode(integer: toData(value.bigEndian))
}
public func encode(integer value: Data) {
append(tag: ASN1.Tag.INTEGER, length: value.count)
append(data: value)
}
public func encode(bitString value: Data, bitLength: Int) {
let usedBits = UInt8(bitLength % 8)
let unusedBits = usedBits == 0 ? 0 : 8 - usedBits
append(tag: ASN1.Tag.BITSTRING, length: value.count + 1)
append(byte: unusedBits)
append(data: value)
}
public func encode(octetString value: Data) {
append(tag: ASN1.Tag.OCTETSTRING, length: value.count)
append(data: value)
}
public func encode(ia5String value: Data) {
append(tag: ASN1.Tag.OCTETSTRING, length: value.count)
append(data: value)
}
public func encode(null value: Void) {
append(tag: ASN1.Tag.NULL, length: 0)
}
public func encode(objectIdentifier value: [UInt64]) {
func field(val: UInt64) -> Data {
var val = val
var result = Data(count: 9)
var pos = 8
result[pos] = UInt8(val & 0x7F)
while val >= (UInt64(1) << 7) {
val >>= 7
pos -= 1
result[pos] = UInt8((val & 0x7F) | 0x80)
}
return Data(result.dropFirst(pos))
}
var iter = value.makeIterator()
let first = iter.next()!
let second = iter.next()!
var bytes = field(val: first * 40 + second)
while let val = iter.next() {
bytes.append(field(val: val))
}
append(tag: ASN1.Tag.OBJECT_IDENTIFIER, length: bytes.count)
append(data: bytes)
}
public func encode(utf8String value: String) {
let itemData = value.data(using: String.Encoding.utf8)!
append(tag: ASN1.Tag.UTF8STRING, length: itemData.count)
append(data: itemData)
}
public func encode(printableString value: String) {
let itemData = value.data(using: String.Encoding.ascii)!
append(tag: ASN1.Tag.PRINTABLESTRING, length: itemData.count)
append(data: itemData)
}
public func encode(ia5String value: String) {
let itemData = value.data(using: String.Encoding.ascii)!
append(tag: ASN1.Tag.IA5STRING, length: itemData.count)
append(data: itemData)
}
public func encode(sequence value: [ASN1Item]) {
let itemData = ASN1.DER.encode(items: value)
append(tag: ASN1.Tag.SEQUENCE, length: itemData.count)
append(data: itemData)
}
public func encode(set value: [ASN1Item]) {
let itemData = ASN1.DER.encode(items: value)
append(tag: ASN1.Tag.SET, length: itemData.count)
append(data: itemData)
}
let utcDateFormatter: DateFormatter = {
let fmt = DateFormatter()
fmt.timeZone = TimeZone(abbreviation: "UTC")
fmt.dateFormat = "yyMMddHHmmss'Z'"
return fmt
}()
public func encode(utcTime value: Date) {
let itemData = utcDateFormatter.string(from: value).data(using: String.Encoding.ascii)!
append(tag: ASN1.Tag.UTCTIME, length: itemData.count)
append(data: itemData)
}
public func encode(tag: UInt8, data: Data) {
append(tag: tag, length: data.count)
append(data: data)
}
}
public static func parse(items ptr: inout UnsafePointer<UInt8>, length: Int) -> [ASN1Item] {
let start = ptr
var items = [ASN1Item]()
repeat {
items.append(parse(item: &ptr))
}
while start.distance(to: ptr) < length
return items
}
public static func parse(item ptr: inout UnsafePointer<UInt8>) -> ASN1Item {
let tag = ptr[0]
ptr = ptr.successor()
let length = parse(length: &ptr)
switch tag {
case Tag.BOOLEAN:
let bool = ASN1Boolean(value: ptr.pointee != 0)
ptr = ptr.advanced(by: length)
return bool
case Tag.INTEGER:
let int = ASN1Integer(value: Data(bytes: ptr, count: length))
ptr = ptr.advanced(by: length)
return int
case Tag.BITSTRING:
let data = Data(bytes: ptr.successor(), count: length - 1)
let bits = ASN1BitString(value: data, length: data.count * 8)
ptr = ptr.advanced(by: length)
return bits
case Tag.OCTETSTRING:
let octs = ASN1OctetString(value: Data(bytes: ptr, count: length))
ptr = ptr.advanced(by: length)
return octs
case Tag.NULL:
return ASN1Null()
case Tag.OBJECT_IDENTIFIER:
return ASN1ObjectIdentifier(value: parse(oid: &ptr, length: length))
case Tag.UTF8STRING:
let str = ASN1UTF8String(value: String(data: Data(bytes: ptr, count: length), encoding: String.Encoding.utf8)!)
ptr = ptr.advanced(by: length)
return str
case Tag.PRINTABLESTRING:
let str = ASN1PrintableString(value: String(data: Data(bytes: ptr, count: length), encoding: String.Encoding.ascii)!)
ptr = ptr.advanced(by: length)
return str
case Tag.IA5STRING:
let str = ASN1IA5String(value: String(data: Data(bytes: ptr, count: length), encoding: String.Encoding.ascii)!)
ptr = ptr.advanced(by: length)
return str
case Tag.SEQUENCE:
return ASN1Sequence(value: parse(items: &ptr, length: length))
case Tag.SET:
return ASN1Set(value: parse(items: &ptr, length: length))
default:
let obj = ASN1Object(tag: tag, data: Data(bytes: ptr, count: length))
ptr = ptr.advanced(by: length)
return obj
}
}
private static func parse(oid ptr: inout UnsafePointer<UInt8>, length: Int) -> [UInt64] {
let start = ptr
var ids = [UInt64]()
repeat {
var val = parse(base128: &ptr)
if ids.isEmpty {
if val < 40 {
ids.append(0)
}
else if val < 80 {
ids.append(1)
val = val - 40
}
else {
ids.append(2)
val = val - 80
}
}
ids.append(val)
}
while start.distance(to: ptr) < length
return ids
}
private static func parse(base128 ptr: inout UnsafePointer<UInt8>) -> UInt64 {
var val = UInt64(0)
repeat {
val = val << 7
val = val + UInt64(ptr.pointee & 0x7F)
ptr = ptr.successor()
}
while ptr.predecessor().pointee & 0x80 != 0
return val
}
private static func parse(length ptr: inout UnsafePointer<UInt8>) -> Int {
var length: Int = 0
let numBytes: Int
if ptr.pointee > 0x80 {
numBytes = Int(ptr.pointee) - 0x80
}
else {
length = Int(ptr.pointee)
numBytes = 0
}
ptr = ptr.successor()
for _ in 0 ..< numBytes {
length = (length * 0x100) + Int(ptr.pointee)
ptr = ptr.successor()
}
return length
}
private init() {}
}
private init() {}
}
func reverse(byte: UInt8) -> UInt8 {
var b = byte
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4
b = (b & 0xCC) >> 2 | (b & 0x33) << 2
b = (b & 0xAA) >> 1 | (b & 0x55) << 1
return b
}
func toData<T>(_ value: T) -> Data {
var value = value
return withUnsafePointer(to: &value) {
Data(bytes: $0, count: MemoryLayout<T>.size)
}
}
|
mit
|
1d8ed06206d00e760c73282dd16dfb2f
| 24.27459 | 125 | 0.606251 | 3.518471 | false | false | false | false |
wangxin20111/WXWeiBo
|
WXWeibo/WXWeibo/Classes/Home/Controller/WXHomeController.swift
|
1
|
6891
|
//
// WXHomeController.swift
// WXWeibo
//
// Created by 王鑫 on 16/6/14.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import SVProgressHUD
import SDWebImage
class WXHomeController: WXBaseTableViewController {
/**
* App Key:2890134094
App Secret:82320f3bc05f9d08010c47ad1a566a81
*/
let WB_App_Key = "2890134094"
//盛放模型数组的
let models = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
//设置首页未登录状态的样式
visitorView?.setupAppearance("", text: "", isHome: true)
//设置barItem
setupBarItems()
//添加titleView
setupTitleView()
//添加通知
setupNotification()
//获取网络数据
if WXUser.fetchUserInfo()?.accessToken != nil {
loadNewData()
//设置cell的高度和属性
setupCellAttri()
}
}
//MARK: - 设置通知
private func setupNotification(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "closeNorifation", name: animationTitleViewCloseNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "openNorifation", name: animationTitleViewOpenNotification, object: nil)
}
//MARK: - 实现通知的方法
func closeNorifation(){
let titleView = navigationItem.titleView as! WXTitleView
titleView.selected = !titleView.selected
}
func openNorifation(){
let titleView = navigationItem.titleView as! WXTitleView
titleView.selected = !titleView.selected
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK: - 添加titleView
private func setupTitleView(){
let titleView = WXTitleView()
titleView.setTitle("afd", forState: UIControlState.Normal)
titleView.addTarget(self, action: "titleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
navigationItem.titleView = titleView
}
//titleView点击事件
func titleButtonClick(btn:WXTitleView){
// btn.selected = !btn.selected
//添加菜单
let sb = UIStoryboard(name:"WXPopViewController", bundle:nil)
//加载一个vc
let vc = sb.instantiateInitialViewController()
//自定义一个牟达
presentedViewController?.modalPresentationStyle = UIModalPresentationStyle.Custom
vc?.transitioningDelegate = anim
vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
//model出来
presentViewController(vc!, animated: true, completion: nil)
}
//MARK: - 添加左右leftBarItem
private func setupBarItems(){
//创建左边
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarItem("navigationbar_friendattention", target: self, action:"leftItemClickInHomePage")
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarItem("navigationbar_pop", target: self, action: "rightItemClickInHomePage")
}
//MARK: - 左右点击事件
func leftItemClickInHomePage(){
SVProgressHUD.showErrorWithStatus("leftBarItem")
}
func rightItemClickInHomePage(){
let sb = UIStoryboard(name: "WXQRCodeController",bundle: nil)
let qrCodeVC = sb.instantiateInitialViewController()
presentViewController(qrCodeVC!, animated: true, completion: nil)
}
//一定要有一个变量盛放,否则会出现问题
private func setupCellAttri(){
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
}
private lazy var anim:WXAnimationObj = {
let ani = WXAnimationObj()
ani.aniFrame = CGRectMake(120, 80, 150, 200)
return ani
}()
//获取网络数据
private func loadNewData(){
let path = "2/statuses/home_timeline.json"
let params = ["access_token": WXUser.fetchUserInfo()!.accessToken!]
WXAPITool.shareNetWorkTools().GET(path, parameters: params, success: { (_, JSON) in
//0.创建一个线程
let group = dispatch_group_create()
//通过这句话,可以找到我的cache路径
// print("OKJson".cacheDir())
//1.获取具体的json字典
let statusDics = JSON!["statuses"] as! [[String:AnyObject]]
//2.便利字典
for index in 0...(statusDics.count-1) {
let dic = statusDics[index] as [String:AnyObject]
//3.字典转模型
let status = WXStatusModel.init(dict: dic)
//4.添加到一个数组
self.models.addObject(status)
//4.1判断当前的微博是否有配图
//4.2 此处status已经将picURLs转化好了,使用一个for循环,去下载照片
for picURL in status.picULRs
{
//进入线程
dispatch_group_enter(group)
SDWebImageManager.sharedManager().downloadWithURL(picURL, options: SDWebImageOptions(rawValue:0), progress: nil, completed: { (image, _, _, _) in
// print("SDWebImageManager下载的照片是-image")
//下载完毕,离开线程
dispatch_group_leave(group)
})
}
}
//因为微博并没有给我照片尺寸,只有一个具体的照片,那么我们要先去获取具体的照片,然后根据image.size去获取照片的尺寸,但是我就蛋疼了,过去MJ是怎么做的?好在这一次可以去使用SDImage的下载照片的功能,还有就是使用移步线程去缓存照片
//所有的线程都下载完毕,去更新UI
dispatch_group_notify(group, dispatch_get_main_queue(), {
// print("最后的刷新UI")
//5.更新tableview
self.tableView.reloadData()
})
}) { (_, error) in
print(error)
}
}
}
//MARK: - 实现数据源方法
extension WXHomeController{
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.models.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = WXStatusCell.cellWithTableView(tableView) as? WXStatusCell
let status = models.objectAtIndex(indexPath.row) as? WXStatusModel
cell?.statusM = status
return cell!
}
}
|
mit
|
5dd995987d89f2021e9c06124055aec2
| 34.215909 | 165 | 0.616489 | 4.580931 | false | false | false | false |
kreshikhin/scituner
|
SciTuner/Models/Tuning.swift
|
1
|
2988
|
//
// Tuning.swift
// SciTuner
//
// Created by Denis Kreshikhin on 8/10/17.
// Copyright © 2017 Denis Kreshikhin. All rights reserved.
//
import Foundation
struct Tuning: Equatable {
typealias `Self` = Tuning
let id: String
let strings: [Note]
let description: String
func localized() -> String {
return id.localized() + " (" + description + ")"
}
init(_ id: String, _ strings: String) {
self.id = id
let splitStrings: [String] = strings.characters.split {$0 == " "}.map { String($0) }
self.description = splitStrings.map({(note: String) -> String in
note.replacingOccurrences(of: "#", with: "♯")
}).joined(separator: " ")
self.strings = splitStrings.map() { (name: String) -> Note in
return Note(name)
}
}
init?(instrument: Instrument, id: String) {
let tunings = instrument.tunings()
guard let tuning = tunings.filter({ $0.id == id}).first else {
return nil
}
self = tuning
}
init(standard instrument: Instrument) {
self = instrument.tunings().first!
}
func index(instrument: Instrument) -> Int? {
return instrument.tunings().index(of: self)
}
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
static let guitarTunings = [
Tuning("standard", "e2 a2 d3 g3 b3 e4"),
Tuning("new_standard", "c2 g2 d3 a3 e4 g4"),
Tuning("russian", "d2 g2 b2 d3 g3 b3 d4"),
Tuning("drop_d", "d2 a2 d3 g3 b3 e4"),
Tuning("drop_c", "c2 g2 c3 f3 a3 d4"),
Tuning("drop_g", "g2 d2 g3 c4 e4 a4"),
Tuning("open_d", "d2 a2 d3 f#3 a3 d4"),
Tuning("open_c", "c2 g2 c3 g3 c4 e4"),
Tuning("open_g", "g2 g3 d3 g3 b3 d4"),
Tuning("lute", "e2 a2 d3 f#3 b3 e4"),
Tuning("irish", "d2 a2 d3 g3 a3 d4")
]
static let celloTunings = [
Tuning("standard", "c2 g2 d3 a3"),
Tuning("alternative", "c2 g2 d3 g3")
]
static let violinTunings = [
Tuning("standard", "g3 d4 a4 e5"),
Tuning("tenor", "g2 d3 a3 e4"),
Tuning("tenor_alter", "f2 c3 g3 d4")
]
static let banjoTunings = [
Tuning("standard", "g4 d3 g3 b3 d4")
]
static let balalaikaTunings = [
Tuning("standard_prima", "e4 e4 a4"),
Tuning("bass", "e2 a2 d3"),
Tuning("tenor", "a2 a2 e3"),
Tuning("alto", "e3 e3 a3"),
Tuning("secunda", "a3 a3 d4"),
Tuning("piccolo", "b4 e5 a5")
]
static let ukuleleTunings = [
Tuning("standard", "g4 c4 e4 a4"),
Tuning("d_tuning", "a4 d4 f#4 b4")
]
static let freemodeTunings = [
Tuning("octaves", "c2 c3 c4 c5 c6"),
Tuning("c_major", "c3 d3 e3 f3 g3 a3 b3"),
Tuning("c_minor", "c3 d3 e3 f3 g3 a3 b3")
]
}
|
mit
|
c694c80723eb61149f30ed97691e1dd5
| 27.160377 | 92 | 0.520938 | 3.061538 | false | false | false | false |
ikesyo/Quick
|
Sources/Quick/Hooks/Closures.swift
|
125
|
1028
|
// MARK: Example Hooks
/**
A closure executed before an example is run.
*/
public typealias BeforeExampleClosure = () -> ()
/**
A closure executed before an example is run. The closure is given example metadata,
which contains information about the example that is about to be run.
*/
public typealias BeforeExampleWithMetadataClosure = (_ exampleMetadata: ExampleMetadata) -> ()
/**
A closure executed after an example is run.
*/
public typealias AfterExampleClosure = BeforeExampleClosure
/**
A closure executed after an example is run. The closure is given example metadata,
which contains information about the example that has just finished running.
*/
public typealias AfterExampleWithMetadataClosure = BeforeExampleWithMetadataClosure
// MARK: Suite Hooks
/**
A closure executed before any examples are run.
*/
public typealias BeforeSuiteClosure = () -> ()
/**
A closure executed after all examples have finished running.
*/
public typealias AfterSuiteClosure = BeforeSuiteClosure
|
apache-2.0
|
d3d6f7362c5bfde60195a28b6dad1341
| 28.371429 | 94 | 0.753891 | 5.14 | false | false | false | false |
kaideyi/KDYSample
|
LeetCode/LeetCode/21_MergeSortedLists.swift
|
1
|
1439
|
//
// 21_MergeSortedLists.swift
// LeetCode
//
// Created by Mac on 2018/4/17.
// Copyright © 2018年 Mac. All rights reserved.
//
import Foundation
class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class List {
var head: ListNode?
var tail: ListNode?
// 尾插法
func appendToTail(_ val: Int) {
if tail == nil {
tail = ListNode(val)
head = tail
} else {
tail!.next = ListNode(val)
tail = tail!.next
}
}
// 头插法
func appendToHead(_ val: Int) {
if head == nil {
head = ListNode(val)
tail = head
} else {
let temp = ListNode(val)
temp.next = head
head = temp
}
}
}
class MergeSortedLists {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let dummy = ListNode(0)
var node = dummy
var l1 = l1
var l2 = l2
while l1 != nil && l2 != nil {
if l1!.val < l2!.val {
node.next = l1
l1 = l1!.next
} else {
node.next = l2
l2 = l2!.next
}
node = node.next!
}
node.next = l1 ?? l2
return dummy.next
}
}
|
mit
|
4ed617476cf1a13bd7b3004c02511dde
| 19.056338 | 71 | 0.444522 | 3.859079 | false | false | false | false |
jimmy54/iRime
|
iRime/Keyboard/tasty-imitation-keyboard/Demo/spi/Logger.swift
|
1
|
5442
|
import Foundation
private let _LoggerSharedInstance = Logger()
class Logger {
class var sharedInstance: Logger {
return _LoggerSharedInstance
}
let path = { () -> String in
let folder = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return URL(string: folder)!.appendingPathComponent("log").absoluteString
}()
var outputStream: OutputStream!
init() {
initOutputStream()
}
func initOutputStream() {
outputStream = OutputStream(toFileAtPath: path, append: true)
if outputStream != nil {
outputStream.open()
} else {
assertionFailure("Unable to open file")
}
}
deinit {
outputStream.close()
}
func writeLogLine(selectedCellIndex: Int, selectedCellText: String) {
writeLogLine(filledString: "@\(selectedCellIndex) \(selectedCellText)")
}
func writeLogLine(tappedKey: Key) {
let tappedKeyText = tappedKey.uppercaseKeyCap ?? (tappedKey.lowercaseKeyCap ?? "???")
writeLogLine(filledString: "\(tappedKeyText) <>")
}
func writeLogLine(filledString: String) {
let currentTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let currentTimeStr = dateFormatter.string(from: currentTime)
writeLogFileWith("\(filledString)\t\(currentTimeStr)\n")
}
func writeLogFileWith(_ string: String) {
if !UserDefaults.standard.bool(forKey: "kLogging") {
return
}
//let qos = Int(DispatchQoS.QoSClass.background.rawValue)
let queue = DispatchQueue.global() //DispatchQueue.global(priority: qos)
queue.async { () -> Void in
self.outputStream.write(string)
return
}
}
func getLogFileContent() -> String {
return (try? String(contentsOfFile: path, encoding: String.Encoding.utf8)) ?? "can not open log file"
}
func clearLogFile() {
do {
try FileManager.default.removeItem(atPath: path)
} catch _ {
}
initOutputStream()
}
func getMemoryUsageReport() -> String {
// from http://stackoverflow.com/questions/27556807/swift-pointer-problems-with-mach-task-basic-info/27559770#27559770
// constant
let MACH_TASK_BASIC_INFO_COUNT = (MemoryLayout<mach_task_basic_info_data_t>.size / MemoryLayout<natural_t>.size)
// prepare parameters
let name = mach_task_self_
let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
var size = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)
// allocate pointer to mach_task_basic_info
let infoPointer = UnsafeMutablePointer<mach_task_basic_info>.allocate(capacity: 1)
// call task_info - note extra UnsafeMutablePointer(...) call
let kerr = task_info(name, flavor, UnsafeMutablePointer<integer_t>.allocate(capacity: 1), &size)
// get mach_task_basic_info struct out of pointer
let info = infoPointer.move()
// deallocate pointer
infoPointer.deallocate(capacity: 1)
// check return value for success / failure
if kerr == KERN_SUCCESS {
let numberFormatter = NumberFormatter()
numberFormatter.groupingSize = 3
numberFormatter.groupingSeparator = ","
numberFormatter.usesGroupingSeparator = true
let usageStr = numberFormatter.string(from: NSNumber(value: info.resident_size as UInt64)) ?? "not available"
return ("Memory in use (in bytes): \(usageStr)")
} else {
let errorString = String.init(cString: mach_error_string(kerr), encoding: String.Encoding.ascii)
return (errorString ?? "Error: couldn't parse error string")
}
}
}
extension OutputStream {
/// Write String to outputStream
///
/// - parameter string: The string to write.
/// - parameter encoding: The NSStringEncoding to use when writing the string. This will default to UTF8.
/// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string.
///
/// - returns: Return total number of bytes written upon success. Return -1 upon failure.
func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8, allowLossyConversion: Bool = true) -> Int {
if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
var bytes = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)
var bytesRemaining = data.count
var totalBytesWritten = 0
while bytesRemaining > 0 {
let bytesWritten = self.write(bytes, maxLength: bytesRemaining)
if bytesWritten < 0 {
return -1
}
bytesRemaining -= bytesWritten
bytes += bytesWritten
totalBytesWritten += bytesWritten
}
return totalBytesWritten
}
return -1
}
}
|
gpl-3.0
|
bc400debc516a2d363acefce5ec15161
| 35.52349 | 126 | 0.604006 | 5.024931 | false | false | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/NCMainMenuViewController.swift
|
2
|
25357
|
//
// NCMainMenuViewController.swift
// Neocom
//
// Created by Artem Shimanski on 04.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCMainMenuRow: DefaultTreeRow {
let scopes: Set<ESI.Scope>
let account: NCAccount?
let isEnabled: Bool
init(prototype: Prototype = Prototype.NCDefaultTableViewCell.default, nodeIdentifier: String, image: UIImage? = nil, title: String? = nil, route: Route? = nil, scopes: [ESI.Scope] = [], account: NCAccount? = nil) {
let scopes = Set(scopes)
self.scopes = scopes
self.account = account
let isEnabled: Bool = {
guard !scopes.isEmpty else {return true}
guard let currentScopes = account?.scopes?.compactMap({($0 as? NCScope)?.name}).compactMap ({ESI.Scope($0)}) else {return false}
return scopes.isSubset(of: currentScopes)
}()
self.isEnabled = isEnabled
super.init(prototype: prototype, nodeIdentifier: nodeIdentifier, image: image, title: title, accessoryType: .disclosureIndicator, route: isEnabled ? route : nil)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = title
cell.iconView?.image = image
cell.accessoryType = .disclosureIndicator
if !isEnabled {
cell.titleLabel?.textColor = .lightText
cell.subtitleLabel?.text = NSLocalizedString("Please sign in again to unlock all features", comment: "")
}
else {
cell.titleLabel?.textColor = .white
cell.subtitleLabel?.text = nil
}
}
}
class NCAccountDataMenuRow<T>: NCMainMenuRow {
private var observer: NCManagedObjectObserver?
var isLoading = false
var result: CachedValue<T>? {
didSet {
if let cacheRecord = result?.cacheRecord(in: NCCache.sharedCache!.viewContext) {
self.observer = NCManagedObjectObserver(managedObject: cacheRecord) { [weak self] (_,_) in
guard let strongSelf = self else {return}
strongSelf.treeController?.reloadCells(for: [strongSelf], with: .none)
}
}
}
}
var error: Error?
}
class NCCharacterSheetMenuRow: NCAccountDataMenuRow<ESI.Skills.CharacterSkills> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
cell.subtitleLabel?.text = NCUnitFormatter.localizedString(from: value.totalSP, unit: .skillPoints, style: .full)
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).skills().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCJumpClonesMenuRow: NCAccountDataMenuRow<ESI.Clones.JumpClones> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
let t = 3600 * 24 + (value.lastCloneJumpDate ?? .distantPast).timeIntervalSinceNow
cell.subtitleLabel?.text = String(format: NSLocalizedString("Clone jump availability: %@", comment: ""), t > 0 ? NCTimeIntervalFormatter.localizedString(from: t, precision: .minutes) : NSLocalizedString("Now", comment: ""))
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).clones().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCSkillsMenuRow: NCAccountDataMenuRow<[ESI.Skills.SkillQueueItem]> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
let date = Date()
let skillQueue = value.filter {
guard let finishDate = $0.finishDate else {return false}
return finishDate >= date
}
if let skill = skillQueue.last,
let endTime = skill.finishDate {
cell.subtitleLabel?.text = String(format: NSLocalizedString("%d skills in queue (%@)", comment: ""), skillQueue.count, NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes))
}
else {
cell.subtitleLabel?.text = NSLocalizedString("No skills in training", comment: "")
}
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).skillQueue().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCWealthMenuRow: NCAccountDataMenuRow<Double> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
cell.subtitleLabel?.text = NCUnitFormatter.localizedString(from: value, unit: .isk, style: .full)
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).walletBalance().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCServerStatusRow: NCAccountDataMenuRow<ESI.Status.ServerStatus> {
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "HH:mm:ss"
return dateFormatter
}()
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
cell.accessoryType = .none
if let value = result?.value {
if value.players > 0 {
cell.titleLabel?.text = String(format: NSLocalizedString("Tranquility: online %@ players", comment: ""), NCUnitFormatter.localizedString(from: value.players, unit: .none, style: .full))
}
else {
cell.titleLabel?.text = NSLocalizedString("Tranquility: offline", comment: "")
}
cell.subtitleLabel?.text = NSLocalizedString("EVE Time: ", comment: "") + dateFormatter.string(from: Date())
}
else if let error = error {
cell.titleLabel?.text = NSLocalizedString("Tranquility", comment: "")
cell.subtitleLabel?.text = error.localizedDescription
}
else {
cell.titleLabel?.text = NSLocalizedString("Tranquility", comment: "")
cell.subtitleLabel?.text = NSLocalizedString("Updating...", comment: "")
guard !isLoading else {return}
isLoading = true
NCDataManager().serverStatus().then(on: .main) { result in
self.result = result
self.error = nil
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerTick(_:)), userInfo: nil, repeats: true)
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
deinit {
timer?.invalidate()
}
private var timer: Timer? {
didSet {
oldValue?.invalidate()
}
}
// override func willDisplay(cell: UITableViewCell) {
// timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerTick(_:)), userInfo: cell, repeats: true)
// }
@objc func timerTick(_ timer: Timer) {
guard let cell = treeController?.cell(for: self) as? NCDefaultTableViewCell else {return}
// guard let cell = timer.userInfo as? NCDefaultTableViewCell else {return}
cell.subtitleLabel?.text = NSLocalizedString("EVE Time: ", comment: "") + dateFormatter.string(from: Date())
}
// override func didEndDisplaying(cell: UITableViewCell) {
// if (timer?.userInfo as? UITableViewCell) == cell {
// timer = nil
// }
// }
}
class NCMainMenuViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
accountChangeAction = .update
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.default,
Prototype.NCDefaultTableViewCell.noImage])
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let h = tableView.tableHeaderView?.bounds.height {
self.tableView.scrollIndicatorInsets.top = h
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if transitionCoordinator?.viewController(forKey: .to)?.parent == navigationController {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
/*override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
DispatchQueue.main.async {
if let headerViewController = self.headerViewController {
self.headerMinHeight = headerViewController.view.systemLayoutSizeFitting(CGSize(width:self.view.bounds.size.width, height:0), withHorizontalFittingPriority:UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultHigh).height
self.headerMaxHeight = headerViewController.view.systemLayoutSizeFitting(CGSize(width:self.view.bounds.size.width, height:0), withHorizontalFittingPriority:UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel).height
var rect = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.bounds.size.width, height: self.headerMaxHeight))
self.tableView?.tableHeaderView?.frame = rect
rect = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: max(self.headerMaxHeight - self.tableView.contentOffset.y, self.headerMinHeight))
headerViewController.view.frame = self.view.convert(rect, to:self.tableView)
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(rect.size.height, 0, 0, 0)
}
}
}*/
override func content() -> Future<TreeNode?> {
let account = NCAccount.current
var sections: [TreeNode] = [
DefaultTreeSection(nodeIdentifier: "Character", title: NSLocalizedString("Character", comment: "").uppercased(),
children: [
NCCharacterSheetMenuRow(nodeIdentifier: "CharacterSheet",
image: #imageLiteral(resourceName: "charactersheet"),
title: NSLocalizedString("Character Sheet", comment: ""),
route: Router.MainMenu.CharacterSheet(),
scopes: [.esiWalletReadCharacterWalletV1,
.esiSkillsReadSkillsV1,
.esiLocationReadLocationV1,
.esiLocationReadShipTypeV1,
.esiClonesReadImplantsV1],
account: account),
NCJumpClonesMenuRow(nodeIdentifier: "JumpClones",
image: #imageLiteral(resourceName: "jumpclones"),
title: NSLocalizedString("Jump Clones", comment: ""),
route: Router.MainMenu.JumpClones(),
scopes: [.esiClonesReadClonesV1,
.esiClonesReadImplantsV1],
account: account),
NCSkillsMenuRow(nodeIdentifier: "Skills",
image: #imageLiteral(resourceName: "skills"),
title: NSLocalizedString("Skills", comment: ""),
route: Router.MainMenu.Skills(),
scopes: [.esiSkillsReadSkillqueueV1,
.esiSkillsReadSkillsV1,
.esiClonesReadImplantsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Mail",
image: #imageLiteral(resourceName: "evemail"),
title: NSLocalizedString("EVE Mail", comment: ""),
route: Router.MainMenu.Mail(),
scopes: [.esiMailReadMailV1,
.esiMailSendMailV1,
.esiMailOrganizeMailV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Calendar",
image: #imageLiteral(resourceName: "calendar"),
title: NSLocalizedString("Calendar", comment: ""),
route: Router.MainMenu.Calendar(),
scopes: [.esiCalendarReadCalendarEventsV1,
.esiCalendarRespondCalendarEventsV1],
account: account),
NCWealthMenuRow(nodeIdentifier: "Wealth",
image: #imageLiteral(resourceName: "folder"),
title: NSLocalizedString("Wealth", comment: ""),
route: Router.MainMenu.Wealth(),
scopes: [.esiWalletReadCharacterWalletV1,
.esiAssetsReadAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "LP",
image: #imageLiteral(resourceName: "lpstore"),
title: NSLocalizedString("Loyalty Points", comment: ""),
route: Router.MainMenu.LoyaltyPoints(),
scopes: [.esiCharactersReadLoyaltyV1],
account: account)
]),
DefaultTreeSection(nodeIdentifier: "Database", title: NSLocalizedString("Database", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Database", image: #imageLiteral(resourceName: "items"), title: NSLocalizedString("Database", comment: ""), route: Router.MainMenu.Database()),
NCMainMenuRow(nodeIdentifier: "Certificates", image: #imageLiteral(resourceName: "certificates"), title: NSLocalizedString("Certificates", comment: ""), route: Router.MainMenu.Certificates()),
NCMainMenuRow(nodeIdentifier: "Market", image: #imageLiteral(resourceName: "market"), title: NSLocalizedString("Market", comment: ""), route: Router.MainMenu.Market()),
NCMainMenuRow(nodeIdentifier: "NPC", image: #imageLiteral(resourceName: "criminal"), title: NSLocalizedString("NPC", comment: ""), route: Router.MainMenu.NPC()),
NCMainMenuRow(nodeIdentifier: "Wormholes", image: #imageLiteral(resourceName: "terminate"), title: NSLocalizedString("Wormholes", comment: ""), route: Router.MainMenu.Wormholes()),
NCMainMenuRow(nodeIdentifier: "Incursions", image: #imageLiteral(resourceName: "incursions"), title: NSLocalizedString("Incursions", comment: ""), route: Router.MainMenu.Incursions())
]),
DefaultTreeSection(nodeIdentifier: "Fitting", title: NSLocalizedString("Fitting/Kills", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Fitting", image: #imageLiteral(resourceName: "fitting"), title: NSLocalizedString("Fitting", comment: ""), route: Router.MainMenu.Fitting()),
NCMainMenuRow(nodeIdentifier: "KillReports",
image: #imageLiteral(resourceName: "killreport"),
title: NSLocalizedString("Kill Reports", comment: ""),
route: Router.MainMenu.KillReports(),
scopes: [.esiKillmailsReadKillmailsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "zKillboardReports", image: #imageLiteral(resourceName: "killrights"), title: NSLocalizedString("zKillboard Reports", comment: ""), route: Router.MainMenu.ZKillboardReports())
]),
DefaultTreeSection(nodeIdentifier: "Business", title: NSLocalizedString("Business", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Assets",
image: #imageLiteral(resourceName: "assets"),
title: NSLocalizedString("Assets", comment: ""),
route: Router.MainMenu.Assets(owner: .character),
scopes: [.esiAssetsReadAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "MarketOrders",
image: #imageLiteral(resourceName: "marketdeliveries"),
title: NSLocalizedString("Market Orders", comment: ""),
route: Router.MainMenu.MarketOrders(owner: .character),
scopes: [.esiMarketsReadCharacterOrdersV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Contracts",
image: #imageLiteral(resourceName: "contracts"),
title: NSLocalizedString("Contracts", comment: ""),
route: Router.MainMenu.Contracts(),
scopes: [.esiContractsReadCharacterContractsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletTransactions",
image: #imageLiteral(resourceName: "journal"),
title: NSLocalizedString("Wallet Transactions", comment: ""),
route: Router.MainMenu.WalletTransactions(owner: .character),
scopes: [.esiWalletReadCharacterWalletV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletJournal",
image: #imageLiteral(resourceName: "wallet"),
title: NSLocalizedString("Wallet Journal", comment: ""),
route: Router.MainMenu.WalletJournal(owner: .character),
scopes: [.esiWalletReadCharacterWalletV1],
account: account),
NCMainMenuRow(nodeIdentifier: "IndustryJobs",
image: #imageLiteral(resourceName: "industry"),
title: NSLocalizedString("Industry Jobs", comment: ""),
route: Router.MainMenu.IndustryJobs(owner: .character),
scopes: [.esiIndustryReadCharacterJobsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Planetaries",
image: #imageLiteral(resourceName: "planets"),
title: NSLocalizedString("Planetaries", comment: ""),
route: Router.MainMenu.Planetaries(),
scopes: [.esiPlanetsManagePlanetsV1],
account: account),
]),
DefaultTreeSection(nodeIdentifier: "Corporation", title: NSLocalizedString("Corporation", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Assets",
image: #imageLiteral(resourceName: "assets"),
title: NSLocalizedString("Assets", comment: ""),
route: Router.MainMenu.Assets(owner: .corporation),
scopes: [.esiAssetsReadCorporationAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "MarketOrders",
image: #imageLiteral(resourceName: "marketdeliveries"),
title: NSLocalizedString("Market Orders", comment: ""),
route: Router.MainMenu.MarketOrders(owner: .corporation),
scopes: [.esiMarketsReadCorporationOrdersV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletTransactions",
image: #imageLiteral(resourceName: "journal"),
title: NSLocalizedString("Wallet Transactions", comment: ""),
route: Router.MainMenu.WalletTransactions(owner: .corporation),
scopes: [.esiWalletReadCorporationWalletsV1, .esiCorporationsReadDivisionsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletJournal",
image: #imageLiteral(resourceName: "wallet"),
title: NSLocalizedString("Wallet Journal", comment: ""),
route: Router.MainMenu.WalletJournal(owner: .corporation),
scopes: [.esiWalletReadCorporationWalletsV1, .esiCorporationsReadDivisionsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "IndustryJobs",
image: #imageLiteral(resourceName: "industry"),
title: NSLocalizedString("Industry Jobs", comment: ""),
route: Router.MainMenu.IndustryJobs(owner: .corporation),
scopes: [.esiIndustryReadCorporationJobsV1],
account: account)
]),
DefaultTreeSection(nodeIdentifier: "Info", title: NSLocalizedString("Info", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "News", image: #imageLiteral(resourceName: "newspost"), title: NSLocalizedString("News", comment: ""), route: Router.MainMenu.News()),
NCMainMenuRow(nodeIdentifier: "Settings", image: #imageLiteral(resourceName: "settings"), title: NSLocalizedString("Settings", comment: ""), route: Router.MainMenu.Settings()),
NCMainMenuRow(nodeIdentifier: "Subscription", image: #imageLiteral(resourceName: "votes"), title: NSLocalizedString("Remove Ads", comment: ""), route: Router.MainMenu.Subscription()),
NCMainMenuRow(nodeIdentifier: "BugReport", image: #imageLiteral(resourceName: "notepad"), title: NSLocalizedString("Report a Bug", comment: ""), route: Router.MainMenu.BugReport()),
NCMainMenuRow(nodeIdentifier: "About", image: #imageLiteral(resourceName: "info"), title: NSLocalizedString("About", comment: ""), route: Router.MainMenu.About())
])
]
// let currentScopes = Set((account?.scopes?.allObjects as? [NCScope])?.compactMap {return $0.name != nil ? ESI.Scope($0.name!) : nil} ?? [])
if (account?.scopes as? Set<NCScope>)?.compactMap({$0.name}).contains(ESI.Scope.esiAssetsReadCorporationAssetsV1.rawValue) == true {
sections[4].isExpanded = true
}
else {
sections[4].isExpanded = false
}
sections.forEach {$0.children = ($0.children as! [NCMainMenuRow]).filter({$0.scopes.isEmpty || account != nil})}
sections = sections.filter {!$0.children.isEmpty}
sections.insert(NCServerStatusRow(prototype: Prototype.NCDefaultTableViewCell.noImage,nodeIdentifier: "ServerStatus"), at: 0)
return .init(RootNode(sections, collapseIdentifier: "NCMainMenuViewController"))
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NCAccountsViewController" {
segue.destination.transitioningDelegate = parent as? UIViewControllerTransitioningDelegate
}
}
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
if (node as? NCMainMenuRow)?.isEnabled == false {
ESI.performAuthorization(from: self)
}
}
/*
//MARK: UIScrollViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = self.mainMenu[indexPath.section][indexPath.row]
let isEnabled: Bool = {
guard let scopes = row["scopes"] as? [String] else {return true}
guard let currentScopes = currentScopes else {return false}
return Set(scopes).isSubset(of: currentScopes)
}()
if isEnabled {
if let segue = row["segueIdentifier"] as? String {
performSegue(withIdentifier: segue, sender: tableView.cellForRow(at: indexPath))
}
}
else {
let url = OAuth2.authURL(clientID: ESClientID, callbackURL: ESCallbackURL, scope: ESI.Scope.default, state: "esi")
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}*/
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let t: CGFloat
if #available(iOS 11, *) {
t = scrollView.safeAreaInsets.top + 70
}
else {
t = 70
}
if (scrollView.contentOffset.y < -t && self.transitionCoordinator == nil && scrollView.isTracking) {
// performSegue(withIdentifier: "NCAccountsViewController", sender: self)
}
}
}
|
lgpl-2.1
|
a9612cdabbab72507daeaaea23cfa4d3
| 43.020833 | 253 | 0.654046 | 4.358948 | false | false | false | false |
OscarSwanros/swift
|
stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
|
22
|
16757
|
//===--- SwiftReflectionTest.swift ----------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file provides infrastructure for introspecting type information in a
// remote swift executable by swift-reflection-test, using pipes and a
// request-response protocol to communicate with the test tool.
//
//===----------------------------------------------------------------------===//
// FIXME: Make this work with Linux
import MachO
import Darwin
let RequestInstanceKind = "k"
let RequestInstanceAddress = "i"
let RequestReflectionInfos = "r"
let RequestReadBytes = "b"
let RequestSymbolAddress = "s"
let RequestStringLength = "l"
let RequestDone = "d"
let RequestPointerSize = "p"
internal func debugLog(_ message: String) {
#if DEBUG_LOG
fputs("Child: \(message)\n", stderr)
fflush(stderr)
#endif
}
public enum InstanceKind : UInt8 {
case None
case Object
case Existential
case ErrorExistential
case Closure
}
/// Represents a section in a loaded image in this process.
internal struct Section {
/// The absolute start address of the section's data in this address space.
let startAddress: UnsafeRawPointer
/// The size of the section in bytes.
let size: UInt
}
/// Holds the addresses and sizes of sections related to reflection
internal struct ReflectionInfo : Sequence {
/// The name of the loaded image
internal let imageName: String
/// Reflection metadata sections
internal let fieldmd: Section?
internal let assocty: Section?
internal let builtin: Section?
internal let capture: Section?
internal let typeref: Section?
internal let reflstr: Section?
internal func makeIterator() -> AnyIterator<Section?> {
return AnyIterator([
fieldmd,
assocty,
builtin,
capture,
typeref,
reflstr
].makeIterator())
}
}
#if arch(x86_64) || arch(arm64)
typealias MachHeader = mach_header_64
#else
typealias MachHeader = mach_header
#endif
/// Get the location and size of a section in a binary.
///
/// - Parameter name: The name of the section
/// - Parameter imageHeader: A pointer to the Mach header describing the
/// image.
/// - Returns: A `Section` containing the address and size, or `nil` if there
/// is no section by the given name.
internal func getSectionInfo(_ name: String,
_ imageHeader: UnsafePointer<MachHeader>) -> Section? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var size: UInt = 0
let address = getsectiondata(imageHeader, "__TEXT", name, &size)
guard let nonNullAddress = address else { return nil }
guard size != 0 else { return nil }
return Section(startAddress: nonNullAddress, size: size)
}
/// Get the Swift Reflection section locations for a loaded image.
///
/// An image of interest must have the following sections in the __DATA
/// segment:
/// - __swift3_fieldmd
/// - __swift3_assocty
/// - __swift3_builtin
/// - __swift3_capture
/// - __swift3_typeref
/// - __swift3_reflstr (optional, may have been stripped out)
///
/// - Parameter i: The index of the loaded image as reported by Dyld.
/// - Returns: A `ReflectionInfo` containing the locations of all of the
/// needed sections, or `nil` if the image doesn't contain all of them.
internal func getReflectionInfoForImage(atIndex i: UInt32) -> ReflectionInfo? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let header = unsafeBitCast(_dyld_get_image_header(i),
to: UnsafePointer<MachHeader>.self)
let imageName = _dyld_get_image_name(i)!
let fieldmd = getSectionInfo("__swift3_fieldmd", header)
let assocty = getSectionInfo("__swift3_assocty", header)
let builtin = getSectionInfo("__swift3_builtin", header)
let capture = getSectionInfo("__swift3_capture", header)
let typeref = getSectionInfo("__swift3_typeref", header)
let reflstr = getSectionInfo("__swift3_reflstr", header)
return ReflectionInfo(imageName: String(validatingUTF8: imageName)!,
fieldmd: fieldmd,
assocty: assocty,
builtin: builtin,
capture: capture,
typeref: typeref,
reflstr: reflstr)
}
internal func sendBytes<T>(from address: UnsafePointer<T>, count: Int) {
var source = address
var bytesLeft = count
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
while bytesLeft > 0 {
let bytesWritten = fwrite(source, 1, bytesLeft, stdout)
fflush(stdout)
guard bytesWritten > 0 else {
fatalError("Couldn't write to parent pipe")
}
bytesLeft -= bytesWritten
source = source.advanced(by: bytesWritten)
}
}
/// Send the address of an object to the parent.
internal func sendAddress(of instance: AnyObject) {
debugLog("BEGIN \(#function)")
defer { debugLog("END \(#function)") }
var address = Unmanaged.passUnretained(instance).toOpaque()
sendBytes(from: &address, count: MemoryLayout<UInt>.size)
}
/// Send the `value`'s bits to the parent.
internal func sendValue<T>(_ value: T) {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value = value
sendBytes(from: &value, count: MemoryLayout<T>.size)
}
/// Read a word-sized unsigned integer from the parent.
internal func readUInt() -> UInt {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value: UInt = 0
fread(&value, MemoryLayout<UInt>.size, 1, stdin)
return value
}
/// Send all known `ReflectionInfo`s for all images loaded in the current
/// process.
internal func sendReflectionInfos() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let infos = (0..<_dyld_image_count()).flatMap(getReflectionInfoForImage)
var numInfos = infos.count
debugLog("\(numInfos) reflection info bundles.")
precondition(numInfos >= 1)
sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size)
for info in infos {
debugLog("Sending info for \(info.imageName)")
for section in info {
sendValue(section?.startAddress)
sendValue(section?.size ?? 0)
}
}
}
internal func printErrnoAndExit() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let errorCString = strerror(errno)!
let message = String(validatingUTF8: errorCString)! + "\n"
let bytes = Array(message.utf8)
fwrite(bytes, 1, bytes.count, stderr)
fflush(stderr)
exit(EXIT_FAILURE)
}
/// Retrieve the address and count from the parent and send the bytes back.
internal func sendBytes() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let count = Int(readUInt())
debugLog("Parent requested \(count) bytes from \(address)")
var totalBytesWritten = 0
var pointer = UnsafeMutableRawPointer(bitPattern: address)
while totalBytesWritten < count {
let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout))
fflush(stdout)
if bytesWritten == 0 {
printErrnoAndExit()
}
totalBytesWritten += bytesWritten
pointer = pointer?.advanced(by: bytesWritten)
}
}
/// Send the address of a symbol loaded in this process.
internal func sendSymbolAddress() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let name = readLine()!
name.withCString {
let handle = UnsafeMutableRawPointer(bitPattern: Int(-2))!
let symbol = dlsym(handle, $0)
let symbolAddress = unsafeBitCast(symbol, to: UInt.self)
sendValue(symbolAddress)
}
}
/// Send the length of a string to the parent.
internal func sendStringLength() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let cString = UnsafePointer<CChar>(bitPattern: address)!
let count = String(validatingUTF8: cString)!.utf8.count
sendValue(count)
}
/// Send the size of this architecture's pointer type.
internal func sendPointerSize() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size)
sendValue(pointerSize)
}
/// Hold an `instance` and wait for the parent to query for information.
///
/// This is the main "run loop" of the test harness.
///
/// The parent will necessarily need to:
/// - Get the addresses of all of the reflection sections for any swift dylibs
/// that are loaded, where applicable.
/// - Get the address of the `instance`
/// - Get the pointer size of this process, which affects assumptions about the
/// the layout of runtime structures with pointer-sized fields.
/// - Read raw bytes out of this process's address space.
///
/// The parent sends a Done message to indicate that it's done
/// looking at this instance. It will continue to ask for instances,
/// so call doneReflecting() when you don't have any more instances.
internal func reflect(instanceAddress: UInt, kind: InstanceKind) {
while let command = readLine(strippingNewline: true) {
switch command {
case String(validatingUTF8: RequestInstanceKind)!:
sendValue(kind.rawValue)
case String(validatingUTF8: RequestInstanceAddress)!:
sendValue(instanceAddress)
case String(validatingUTF8: RequestReflectionInfos)!:
sendReflectionInfos()
case String(validatingUTF8: RequestReadBytes)!:
sendBytes()
case String(validatingUTF8: RequestSymbolAddress)!:
sendSymbolAddress()
case String(validatingUTF8: RequestStringLength)!:
sendStringLength()
case String(validatingUTF8: RequestPointerSize)!:
sendPointerSize()
case String(validatingUTF8: RequestDone)!:
return
default:
fatalError("Unknown request received: '\(Array(command.utf8))'!")
}
}
}
/// Reflect a class instance.
///
/// This reflects the stored properties of the immediate class.
/// The superclass is not (yet?) visited.
public func reflect(object: AnyObject) {
defer { _fixLifetime(object) }
let address = Unmanaged.passUnretained(object).toOpaque()
let addressValue = UInt(bitPattern: address)
reflect(instanceAddress: addressValue, kind: .Object)
}
/// Reflect any type at all by boxing it into an existential container (an `Any`)
///
/// Given a class, this will reflect the reference value, and not the contents
/// of the instance. Use `reflect(object:)` for that.
///
/// This function serves to exercise the projectExistential function of the
/// SwiftRemoteMirror API.
///
/// It tests the three conditions of existential layout:
///
/// ## Class existentials
///
/// For example, a `MyClass as Any`:
/// ```
/// [Pointer to class instance]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type fits in the 3-word buffer
///
/// For example, a `(1, 2) as Any`:
/// ```
/// [Tuple element 1: Int]
/// [Tuple element 2: Int]
/// [-Empty_]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type has to be allocated into a
/// heap buffer.
///
/// For example, a `LargeStruct<T> as Any`:
/// ```
/// [Pointer to unmanaged heap container] --> [Large struct]
/// [-Empty-]
/// [-Empty-]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// The test doesn't care about the witness tables - we only care
/// about what's in the buffer, so we always put these values into
/// an Any existential.
public func reflect<T>(any: T) {
let any: Any = any
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size)
anyPointer.initialize(to: any)
let anyPointerValue = UInt(bitPattern: anyPointer)
reflect(instanceAddress: anyPointerValue, kind: .Existential)
anyPointer.deallocate(capacity: MemoryLayout<Any>.size)
}
// Reflect an `Error`, a.k.a. an "error existential".
//
// These are always boxed on the heap, with the following layout:
//
// - Word 0: Metadata Pointer
// - Word 1: 2x 32-bit reference counts
//
// If Objective-C interop is available, an Error is also an
// `NSError`, and so has:
//
// - Word 2: code (NSInteger)
// - Word 3: domain (NSString *)
// - Word 4: userInfo (NSDictionary *)
//
// Then, always follow:
//
// - Word 2 or 5: Instance type metadata pointer
// - Word 3 or 6: Instance witness table for conforming
// to `Swift.Error`.
//
// Following that is the instance that conforms to `Error`,
// rounding up to its alignment.
public func reflect<T: Error>(error: T) {
let error: Error = error
let errorPointerValue = unsafeBitCast(error, to: UInt.self)
reflect(instanceAddress: errorPointerValue, kind: .ErrorExistential)
}
/// Wraps a thick function with arity 0.
struct ThickFunction0 {
var function: () -> Void
}
/// Wraps a thick function with arity 1.
struct ThickFunction1 {
var function: (Int) -> Void
}
/// Wraps a thick function with arity 2.
struct ThickFunction2 {
var function: (Int, String) -> Void
}
/// Wraps a thick function with arity 3.
struct ThickFunction3 {
var function: (Int, String, AnyObject?) -> Void
}
struct ThickFunctionParts {
var function: UnsafeRawPointer
var context: Optional<UnsafeRawPointer>
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping () -> Void) {
let fn = UnsafeMutablePointer<ThickFunction0>.allocate(
capacity: MemoryLayout<ThickFunction0>.size)
fn.initialize(to: ThickFunction0(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction0>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int) -> Void) {
let fn =
UnsafeMutablePointer<ThickFunction1>.allocate(
capacity: MemoryLayout<ThickFunction1>.size)
fn.initialize(to: ThickFunction1(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction1>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction2>.allocate(
capacity: MemoryLayout<ThickFunction2>.size)
fn.initialize(to: ThickFunction2(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction2>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String, AnyObject?) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction3>.allocate(
capacity: MemoryLayout<ThickFunction3>.size)
fn.initialize(to: ThickFunction3(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction3>.size)
}
/// Call this function to indicate to the parent that there are
/// no more instances to look at.
public func doneReflecting() {
reflect(instanceAddress: UInt(InstanceKind.None.rawValue), kind: .None)
}
/* Example usage
public protocol P {
associatedtype Index
var startIndex: Index { get }
}
public struct Thing : P {
public let startIndex = 1010
}
public enum E<T: P> {
case B(T)
case C(T.Index)
}
public class A<T: P> : P {
public let x: T?
public let y: T.Index
public let b = true
public let t = (1, 1.0)
private let type: NSObject.Type
public let startIndex = 1010
public init(x: T) {
self.x = x
self.y = x.startIndex
self.type = NSObject.self
}
}
let instance = A(x: A(x: Thing()))
reflect(A(x: Thing()))
*/
|
apache-2.0
|
09b2e79488c9fed986fb24a556bf9700
| 30.796964 | 87 | 0.689205 | 4.105096 | false | false | false | false |
euajudo/ios
|
euajudo/Controller/CampaignsCollectionViewController.swift
|
1
|
4849
|
//
// CampaignsCollectionViewController.swift
// euajudo
//
// Created by Rafael Kellermann Streit on 4/11/15.
// Copyright (c) 2015 euajudo. All rights reserved.
//
import UIKit
let kCellCampaignIdentifier = "CellCampaign"
class CampaignsCollectionViewController: UICollectionViewController {
var campaigns = [Campaign]()
@IBOutlet weak var buttonProfile: UIBarButtonItem!
@IBOutlet weak var buttonSettings: UIBarButtonItem!
lazy var refreshControl: UIRefreshControl = {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: "refreshControlUpdateStatus:", forControlEvents: .ValueChanged)
return refresh
}()
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Register cell in collectionView
collectionView?.registerNib(UINib(nibName: "CampaignCell", bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: kCellCampaignIdentifier)
// Refresh data
collectionView?.addSubview(refreshControl)
reloadCampaigns()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Campaign" {
if let campaign = sender as? Campaign, controller = segue.destinationViewController as? CampaignDetailViewController {
controller.campaign = campaign
}
}
}
// MARK: Data
func reloadCampaigns() {
campaigns = [Campaign]()
refreshControl.beginRefreshing()
unowned let weakSelf = self
API.sharedInstance.allCampaings { (campaignList, error) -> Void in
weakSelf.campaigns += campaignList as! [Campaign]
weakSelf.collectionView!.reloadData()
weakSelf.refreshControl.endRefreshing()
}
}
// MARK: RefreshControl
func refreshControlUpdateStatus(refreshControl: UIRefreshControl) {
if refreshControl.refreshing {
reloadCampaigns()
}
}
// MARK: - Navigation
func showAuth() {
let auth = self.storyboard!.instantiateViewControllerWithIdentifier("Auth") as! UINavigationController
self.presentViewController(auth, animated: true, completion: nil)
}
func showDonatedCampaigns() {
self.performSegueWithIdentifier("donatedCampaigns", sender: self)
}
// MARK: - IBAction
@IBAction func buttonProfilePressed(sender: AnyObject) {
if !API.sharedInstance.isLogged() {
showAuth()
} else {
showDonatedCampaigns()
}
}
@IBAction func buttonSettingsPressed(sender: AnyObject) {
let nav = storyboard?.instantiateViewControllerWithIdentifier("Settings") as! UINavigationController
self.presentViewController(nav, animated: true, completion: nil)
}
}
// MARK: UICollectionViewDataSource
extension CampaignsCollectionViewController: UICollectionViewDataSource {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return campaigns.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellCampaignIdentifier, forIndexPath: indexPath) as! CampaignCell
let campaign = campaigns[indexPath.row]
cell.campaign = campaign
cell.updateInformations()
return cell
}
}
// MARK: UICollectionViewDelegate
extension CampaignsCollectionViewController: UICollectionViewDelegate {
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let campaign = campaigns[indexPath.row]
self.performSegueWithIdentifier("Campaign", sender: campaign)
}
}
// MARK: UICollectionViewDataSource
extension CampaignsCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(view.frame.size.width - 30, 410.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 20.0
}
}
|
mit
|
a709e31a75274a690268616c7b9cda03
| 30.901316 | 173 | 0.690452 | 5.779499 | false | false | false | false |
googlearchive/friendlyping
|
ios/FriendlyPingSwift/AppState.swift
|
1
|
1259
|
//
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/** Keeps track of the application state */
class AppState: NSObject {
static let sharedInstance = AppState()
/** True if app is connected to GCM */
var connectedToGcm = false
/** True if app is subscribed to new clients topic */
var subscribed = false
/** GCM registration token of the app */
var registrationToken: String?
/** senderID of the Friendly Ping server */
var senderID: String?
/** GCM address of the Friendly Ping server */
var serverAddress: String?
/** True if the client is registered to the Friendly Ping server */
var registeredToFP = false
/** True if the user has signed in */
var signedIn = false
}
|
apache-2.0
|
499c494467446690bcae5f7993f82568
| 33.027027 | 76 | 0.710087 | 4.224832 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Tests/ClientTests/Extensions/UIImageViewExtensionsTests.swift
|
2
|
3522
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import XCTest
import Storage
import GCDWebServers
import Shared
@testable import Client
class UIImageViewExtensionsTests: XCTestCase {
func testsetIcon() {
let url = URL(string: "http://mozilla.com")
let imageView = UIImageView()
let goodIcon = FaviconFetcher.letter(forUrl: url!)
imageView.setImageAndBackground(forIcon: nil, website: url) {}
XCTAssertEqual(imageView.image!, goodIcon, "The correct default favicon should be applied")
imageView.setImageAndBackground(forIcon: nil, website: URL(string: "http://mozilla.com/blahblah")) {}
XCTAssertEqual(imageView.image!, goodIcon, "The same icon should be applied to all urls with the same domain")
imageView.setImageAndBackground(forIcon: nil, website: URL(string: "b")) {}
XCTAssertEqual(imageView.image, FaviconFetcher.defaultFavicon, "The default favicon should be applied when no information is given about the icon")
}
func testAsyncDownloadCacheWithAuthenticationOfSetIcon() throws {
throw XCTSkip("Failing without App delegate setup, needs investigation")
// let originalImage = UIImage(named: "bookmark")!
//
// WebServer.sharedInstance.registerHandlerForMethod("GET", module: "favicon", resource: "icon") { (request) -> GCDWebServerResponse in
// return GCDWebServerDataResponse(data: originalImage.pngData()!, contentType: "image/png")
// }
//
// let expect = expectation(description: "UIImageView async load")
// let imageLoader = ImageLoadingHandler()
// imageLoader.credential = WebServer.sharedInstance.credentials
//
// let favImageView = UIImageView()
//
// let url = URL(string: "http://localhost:\(AppInfo.webserverPort)/favicon/icon")!
// imageLoader.downloadAndCacheImageWithAuthentication(with: url) { image, err in
// if err == nil, let downloadedImage = image {
// favImageView.image = image
// XCTAssert(downloadedImage.size.width * downloadedImage.scale == favImageView.image!.size.width * favImageView.image!.scale, "The correct favicon should be applied to the UIImageView")
// expect.fulfill()
// }
// }
//
// waitForExpectations(timeout: 5, handler: nil)
}
func testDefaultIcons() {
let favImageView = UIImageView()
let gFavURL = URL(string: "https://www.facebook.com/fav") // This will be fetched from tippy top sites
let gURL = URL(string: "http://www.facebook.com")!
let defaultItem = FaviconFetcher.bundledIcons[gURL.baseDomain!]!
let correctImage = UIImage(contentsOfFile: defaultItem.filePath)!
favImageView.setImageAndBackground(forIcon: Favicon(url: gFavURL!.absoluteString), website: gURL) {}
let expect = expectation(description: "UIImageView async load")
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
XCTAssertEqual(favImageView.backgroundColor, defaultItem.bgcolor)
XCTAssert(correctImage.size.width * correctImage.scale == favImageView.image!.size.width * favImageView.image!.scale, "The correct default favicon should be applied to the UIImageView")
expect.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
}
|
mpl-2.0
|
fe594b400d88540a02fcc5e2427dfdb7
| 45.96 | 201 | 0.687677 | 4.526992 | false | true | false | false |
EPICmynamesBG/SKButton
|
SKButton-Demo3/SKButton-Demo3/GameViewController.swift
|
1
|
1981
|
//
// GameViewController.swift
// SKButton-Demo3
//
// Created by Brandon Groff on 12/10/15.
// Copyright (c) 2015 Brandon Groff. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* A modified version of creating a GameScene.
* Note that GameScene is being initialized with size: Device.screenSize.
* This must be done in order to use the SKButtonPosition class as intended.
*/
let skView: SKView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
// skView.ignoresSiblingOrder = true
let scene = GameScene(size: Device.screenSize)
scene.scaleMode = .AspectFill
skView.presentScene(scene)
/*
Note: The below is the auto-generated GameScene creation.
*/
// if let scene = GameScene(fileNamed: "GameScene") {
// // Configure the view.
// let skView = self.view as! SKView
// skView.showsFPS = true
// skView.showsNodeCount = true
//
// /* Sprite Kit applies additional optimizations to improve rendering performance */
// skView.ignoresSiblingOrder = true
//
// /* Set the scale mode to scale to fit the window */
// scene.scaleMode = .AspectFill
//
// skView.presentScene(scene)
// }
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
2476021d473e85ddb2042baac4659886
| 27.710145 | 96 | 0.62847 | 4.867322 | false | false | false | false |
frootloops/swift
|
stdlib/private/SwiftPrivate/PRNG.swift
|
4
|
1697
|
//===--- PRNG.swift -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
public func rand32() -> UInt32 {
return _stdlib_cxx11_mt19937()
}
public func rand32(exclusiveUpperBound limit: UInt32) -> UInt32 {
return _stdlib_cxx11_mt19937_uniform(limit)
}
public func rand64() -> UInt64 {
return
(UInt64(_stdlib_cxx11_mt19937()) << 32) |
UInt64(_stdlib_cxx11_mt19937())
}
public func randInt() -> Int {
#if arch(i386) || arch(arm)
return Int(Int32(bitPattern: rand32()))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return Int(Int64(bitPattern: rand64()))
#else
fatalError("unimplemented")
#endif
}
public func randArray64(_ count: Int) -> [UInt64] {
var result = [UInt64](repeating: 0, count: count)
for i in result.indices {
result[i] = rand64()
}
return result
}
public func randArray(_ count: Int) -> [Int] {
var result = [Int](repeating: 0, count: count)
for i in result.indices {
result[i] = randInt()
}
return result
}
public func pickRandom<
C : RandomAccessCollection
>(_ c: C) -> C.Iterator.Element {
let i = Int(rand32(exclusiveUpperBound: numericCast(c.count)))
return c[c.index(c.startIndex, offsetBy: numericCast(i))]
}
|
apache-2.0
|
45bb51328d04decbb371f960d1aa3cd2
| 27.283333 | 90 | 0.629346 | 3.550209 | false | false | false | false |
ioscreator/ioscreator
|
IOSSpriteKitPhysicsTutorial/IOSSpriteKitPhysicsTutorial/GameScene.swift
|
1
|
871
|
//
// GameScene.swift
// IOSSpriteKitPhysicsTutorial
//
// Created by Arthur Knopper on 17/01/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = UIColor.white
scene!.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
run(SKAction.repeat(SKAction.sequence([SKAction.run(createBall), SKAction.wait(forDuration: 0.05)]), count: 200))
}
func createBall() {
let ball = SKSpriteNode(imageNamed: "ball")
ball.position = CGPoint(x: CGFloat(Int(arc4random()) & Int(size.width)),
y: size.height - ball.size.height)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
addChild(ball)
}
}
|
mit
|
4e9ee261ab3681f33064e2379f51cdc8
| 28 | 121 | 0.635632 | 4.264706 | false | false | false | false |
elpassion/el-space-ios
|
ELSpace/Coordinators/AppCoordinator/AppCoordinator.swift
|
1
|
1518
|
import UIKit
class AppCoordinator: Coordinator {
init(navigationController: UINavigationController,
loginViewController: LoginViewControlling,
selectionCoordinatorFactory: SelectionCoordinatorCreation,
viewControllerPresenter: ViewControllerPresenting) {
self.navigationController = navigationController
self.selectionCoordinatorFactory = selectionCoordinatorFactory
self.viewControllerPresenter = viewControllerPresenter
self.loginViewController = loginViewController
self.loginViewController.googleTooken = { [weak self] token in
self?.presentSelectionController(googleTokenId: token)
}
}
// MARK: - Coordinator
var initialViewController: UIViewController {
return navigationController
}
// MARK: - Private
private let navigationController: UINavigationController
private var loginViewController: LoginViewControlling
private let selectionCoordinatorFactory: SelectionCoordinatorCreation
private let viewControllerPresenter: ViewControllerPresenting
// MARK: - Presenting
private var presentedCoordinator: Coordinator?
private func presentSelectionController(googleTokenId: String) {
let coordinator = selectionCoordinatorFactory.selectionCoordinator(googleIdToken: googleTokenId)
self.presentedCoordinator = coordinator
viewControllerPresenter.push(viewController: coordinator.initialViewController, on: navigationController)
}
}
|
gpl-3.0
|
bdb463c1b7bd96591d93c7a412d191e2
| 36.02439 | 113 | 0.76614 | 6.628821 | false | false | false | false |
hayleyqinn/windWeather
|
风生/Pods/Alamofire/Source/SessionManager.swift
|
118
|
33492
|
//
// SessionManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
open static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
open let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
open let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return request(encodedURLRequest)
} catch {
return request(failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
do {
let originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(failedWith error: Error) -> DataRequest {
let request = DataRequest(session: session, requestTask: .data(nil, nil), error: error)
if startRequestsImmediately { request.resume() }
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest
{
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let request = DownloadRequest(session: session, requestTask: .download(downloadable, task))
request.downloadDelegate.destination = destination
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return download(failedWith: error)
}
}
private func download(failedWith error: Error) -> DownloadRequest {
let download = DownloadRequest(session: session, requestTask: .download(nil, nil), error: error)
if startRequestsImmediately { download.resume() }
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(fileURL, with: urlRequestWithContentType),
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(failedWith: error)
}
}
private func upload(failedWith error: Error) -> UploadRequest {
let upload = UploadRequest(session: session, requestTask: .upload(nil, nil), error: error)
if startRequestsImmediately { upload.resume() }
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
request.delegate.task = task // resets all task delegate data
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error
return false
}
}
}
|
mit
|
4654c10501b652dd3ad673e02f518603
| 42.159794 | 129 | 0.631076 | 5.389765 | false | false | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/27271-swift-typechecker-validatedecl.swift
|
11
|
2496
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class A : P {func a
class
b : A
func a{
{{struct d B {
struct c<T where f
struct b
class B<T where k:d B : A{
f
class a: e{enum S<T
class B<T=a{enum S<I : b : b
struct B<d { }
let a
}
let a{
class d{
b {
class b{enum e
protocol c<T where k:d=[Void{
class d=a{
class C<A{}
class A
let a
}
}
}
}protocol a {class a{
}
}}}
}
protocol a {
let f<T where H:d where H:a{{typealias d:T=Dictionary<T where T{
if true {
protocol P{
f=[]
struct B<S<S<T where H:NSObject
<T where j: a:a{
struct Q<T where H:b<T : P {}
var b : a{
l
let:NSObject
class A{
var f: a{}
var b : T where f<d { }protocol c {func a{
}
{
struct c{
class C<I : e{
var _=B{func a:{
class A
struct c
class A{
"" \(a{enum S<c<T where H:Sequence
class B<T=k
a {
class d=k
}
var
class
protocol c<T where I : a{
class d=[Void{
class d{func p )"[ 0
class A
}
}}
let
func f {}
class d{enum C<T where j: b {
struct c<T where j: e{
enum S<T where d=[Void{
}class d{
class b:{let f=[]
protocol c
var f:T>
f:a{
class d:c
func p )"" "[ 0
f: A{
func x(a<T{
let:{
<d { }{
enum S<T : A{struct B<k
}
let:a:a{
T where d{
struct S
}
{
class d{
}
class A {
{
if true{
}{
Void{
class A : A {
}
}
}}
class b{
class d:Sequence
}func b{}protocol P{
class d=c
}
let
{
struct d:Collection
}
protocol c : Poid{
let f
let:T{
class b<T where g:Collection
func a<T : a{
let f
class B{
}
class b{
var a
struct d=c{struct B{
class C{
f:Collection
class A{struct B<T where H:Sequence
var a:a{
class a{
func x(a<T : b:a= []
let a{
class B
}
protocol c<T where I : a{
enum S
protocol c<T where H:{
}
let f:Collection
enum S< > S >
class d}{struct B
protocol c {
f
class A
protocol c
}}}
struct Q<h where I : A{
}
f=a{struct B{
enum S<
class C<
func a{enum e
{
protocol P{struct c<T>Bool [ 0
func x(a{typealias d=c
class B<T>
class A{
func x(a<T where j: e A {struct d{}struct Q<c<T where d}
T where f:T=[Void{}
{
}
enum e{
protocol c{}
class b{
var f
let c<T where T>i<a
class a{
let a
protocol c {
class a<h where j: A : A{
struct S<T{
struct d{
struct B{
}
func x(a{
let a
class a<T where h:{
protocol A {
}
f=[Void{
{
let a{
<T where h:T
let
struct S< {let f:Collection
{
let
|
apache-2.0
|
e27fa14bef3ba70c11bfd025cda3fa97
| 12.206349 | 78 | 0.645032 | 2.352498 | false | false | false | false |
Desgard/Guardia-Swift-Server
|
src/Sources/App/Models/Code.swift
|
1
|
3659
|
//
// Code.swift
// Guardia
//
// Created by 段昊宇 on 2017/2/5.
//
//
import Foundation
import Vapor
import Fluent
let DEFAULT_RUN_PATH: String = "/Users/Shared/Guardia-pg/code.swift"
let DEFALUT_LOG_PATH: String = "/Users/Shared/Guardia-pg/code.log"
let DEFALUT_ERROR_LOG_PATH: String = "/Users/Shared/Guardia-pg/error.log"
final class CodeFile: Model {
var id: Node?
var codeText: String
var timestamp: String
let path: String = {
var path: String = DEFAULT_RUN_PATH
return path
}()
let logPath: String = {
var path: String = DEFALUT_LOG_PATH
return path
}()
let errorLogPath: String = {
var path: String = DEFALUT_ERROR_LOG_PATH
return path
}()
init(code: String, timestamp: String) {
self.id = UUID().uuidString.makeNode()
self.codeText = code
self.timestamp = timestamp
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
codeText = try node.extract("codeText")
timestamp = try node.extract("timestamp")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"codeText": codeText,
"timestamp": timestamp,
])
}
// Operation Function
private func cli(cmd: String) -> String {
let process: Process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", cmd]
let pipe: Pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
let fileHandle: FileHandle = pipe.fileHandleForReading
process.launch()
let data: Data = fileHandle.readDataToEndOfFile()
let log: String = String(data: data, encoding: String.Encoding.utf8)!
return log
}
private func isFileExist(atPath filePath: String) -> Bool {
return FileManager.default.fileExists(atPath: filePath)
}
public func creatFile() {
let url: NSURL = NSURL(fileURLWithPath: self.path)
let data = NSMutableData()
data.append(codeText.data(using: String.Encoding.utf8, allowLossyConversion: true)!)
data.write(toFile: url.path!, atomically: true)
}
public func readLogFile() -> String {
let file: URL = URL(fileURLWithPath: self.logPath)
let readHandler = try! FileHandle(forReadingFrom: file)
let data: Data = readHandler.readDataToEndOfFile()
let log: String = String(data: data, encoding: String.Encoding.utf8)!
return log
}
public func readErrorFile() -> String {
let file: URL = URL(fileURLWithPath: self.errorLogPath)
let readHandler = try! FileHandle(forReadingFrom: file)
let data: Data = readHandler.readDataToEndOfFile()
let log: String = String(data: data, encoding: String.Encoding.utf8)!
return log
}
public func runFile() -> String {
let serverLog: String = cli(cmd: "bash run-swift.sh;")
let retLog: String = readLogFile()
let retError: String = readErrorFile()
if retError == "" {
return retLog
} else {
return retError
}
}
}
extension CodeFile {
public convenience init?(from code: String, timestamp: String) throws {
self.init(code: code, timestamp: timestamp)
}
}
extension CodeFile: Preparation {
static func prepare(_ database: Database) throws {
//
}
static func revert(_ database: Database) throws {
//
}
}
|
mit
|
e633e730e39a8e373234fe5a61085b32
| 27.317829 | 92 | 0.597865 | 4.237819 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
WordPress/Classes/ViewRelated/Views/ConfettiView.swift
|
2
|
2614
|
import UIKit
/// Displays a small shower of confetti, raining down from the top of the view
/// Designed to work with FancyAlertViewController, so may currently have
/// visual issues working with larger views.
///
class ConfettiView: UIView {
let colors: [UIColor]
/// - parameter: colors An array of colors to use for the confetti particles
///
init(colors: [UIColor]) {
self.colors = colors
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Starts the confetti effect
/// - parameter duration: Optional time interval after which the confetti
/// effect will automatically finish
///
func start(duration: TimeInterval? = nil) {
let cells = colors.map({ makeEmitterCell(with: $0) })
makeEmitter(with: cells)
if let duration = duration, duration > 0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
self.stop()
}
}
}
/// Stop the confetti effect
///
func stop() {
emitterLayer?.birthRate = 0
}
// MARK: - Emitter creation
private var emitterLayer: CAEmitterLayer? = nil
private func makeEmitter(with cells: [CAEmitterCell]) {
let emitterLayer = CAEmitterLayer()
emitterLayer.beginTime = CACurrentMediaTime()
emitterLayer.emitterShape = kCAEmitterLayerRectangle
emitterLayer.emitterCells = cells
layer.addSublayer(emitterLayer)
self.emitterLayer = emitterLayer
updateEmitterSize()
}
private func updateEmitterSize() {
let emitterHeight = bounds.height / 4
emitterLayer?.emitterSize = CGSize(width: bounds.width, height: emitterHeight)
emitterLayer?.emitterPosition = CGPoint(x: bounds.midX, y: 0)
}
/// Creates the cells used for each color in the confetti.
/// Values
///
private func makeEmitterCell(with color: UIColor) -> CAEmitterCell {
let cell = CAEmitterCell()
cell.color = color.cgColor
cell.contents = UIImage(named: "confetti")?.cgImage
cell.birthRate = 3.0
cell.lifetime = 15.0
cell.lifetimeRange = 5.0
cell.emissionLongitude = CGFloat.pi / 2
cell.emissionRange = CGFloat.pi / 4
cell.scale = 0.7
cell.scaleRange = 0.5
cell.scaleSpeed = -0.05
cell.velocity = 60.0
cell.velocityRange = 50.0
cell.spinRange = CGFloat.pi / 4
return cell
}
}
|
gpl-2.0
|
53a6bbfed4f94b9c011321232fa23864
| 26.229167 | 86 | 0.620888 | 4.70991 | false | false | false | false |
edjiang/forward-swift-workshop
|
SwiftNotesIOS/Pods/Stormpath/Stormpath/Networking/APIRequestManager.swift
|
1
|
2199
|
//
// APIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 2/5/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
class APIRequestManager: NSObject {
let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
var request = NSMutableURLRequest()
init(withURL url: NSURL) {
request.URL = url
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let version = NSBundle(forClass: APIRequestManager.self).infoDictionary?["CFBundleShortVersionString"] as? String {
request.setValue("stormpath-sdk-ios/" + version + " iOS/" + UIDevice.currentDevice().systemVersion, forHTTPHeaderField: "X-Stormpath-Agent")
}
}
func requestDidFinish(data: NSData, response: NSHTTPURLResponse) {
preconditionFailure("Method not implemented")
}
func performCallback(error error: NSError?) {
preconditionFailure("Method not implemented")
}
func prepareForRequest() {
}
func begin() {
prepareForRequest()
let task = urlSession.dataTaskWithRequest(request, completionHandler : requestCompletionHandler)
task.resume()
}
func setAccessToken(accessToken: String) {
request.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
}
private func requestCompletionHandler(data: NSData?, response: NSURLResponse?, error: NSError?) {
guard let response = response as? NSHTTPURLResponse, data = data where error == nil else {
if let error = error {
Logger.logError(error)
}
self.performCallback(error: error)
return
}
Logger.logResponse(response, data: data)
//If the status code isn't 2XX
if response.statusCode / 100 != 2 {
self.performCallback(error: StormpathError.errorForResponse(response, data: data))
} else {
requestDidFinish(data, response: response)
}
}
}
|
apache-2.0
|
39a6d108f52418bae70646b60039c2df
| 33.34375 | 152 | 0.647862 | 5.147541 | false | false | false | false |
dkeichinger/XLForm
|
Examples/Swift/SwiftExample/RealExamples/NativeEventFormViewController.swift
|
2
|
11554
|
//
// NativeEventNavigationViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class NativeEventFormViewController : XLFormViewController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializeForm()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Add Event")
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Title
row = XLFormRowDescriptor(tag: "title", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Title"
row.required = true
section.addFormRow(row)
// Location
row = XLFormRowDescriptor(tag: "location", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Location"
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// All-day
row = XLFormRowDescriptor(tag: "all-day", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "All-day")
section.addFormRow(row)
// Starts
row = XLFormRowDescriptor(tag: "starts", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Starts")
row.value = NSDate(timeIntervalSinceNow: 60*60*24)
section.addFormRow(row)
// Ends
row = XLFormRowDescriptor(tag: "ends", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Ends")
row.value = NSDate(timeIntervalSinceNow: 60*60*25)
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Repeat
row = XLFormRowDescriptor(tag: "repeat", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Repeat")
row.value = XLFormOptionsObject(value: 0, displayText: "Never")
row.selectorTitle = "Repeat"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText: "Never"),
XLFormOptionsObject(value: 1, displayText: "Every Day"),
XLFormOptionsObject(value: 2, displayText: "Every Week"),
XLFormOptionsObject(value: 3, displayText: "Every 2 Weeks"),
XLFormOptionsObject(value: 4, displayText: "Every Month"),
XLFormOptionsObject(value: 5, displayText: "Every Year")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Alert
row = XLFormRowDescriptor(tag: "alert", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Alert")
row.value = XLFormOptionsObject(value: 0, displayText: "None")
row.selectorTitle = "Event Alert"
row.selectorOptions = [
XLFormOptionsObject(value: 0, displayText: "None"),
XLFormOptionsObject(value: 1, displayText: "At time of event"),
XLFormOptionsObject(value: 2, displayText: "5 minutes before"),
XLFormOptionsObject(value: 3, displayText: "15 minutes before"),
XLFormOptionsObject(value: 4, displayText: "30 minutes before"),
XLFormOptionsObject(value: 5, displayText: "1 hour before"),
XLFormOptionsObject(value: 6, displayText: "2 hours before"),
XLFormOptionsObject(value: 7, displayText: "1 day before"),
XLFormOptionsObject(value: 8, displayText: "2 days before")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Show As
row = XLFormRowDescriptor(tag: "showAs", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Show As")
row.value = XLFormOptionsObject(value: 0, displayText: "Busy")
row.selectorTitle = "Show As"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText:"Busy"),
XLFormOptionsObject(value: 1, displayText:"Free")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// URL
row = XLFormRowDescriptor(tag: "url", rowType:XLFormRowDescriptorTypeURL)
row.cellConfigAtConfigure["textField.placeholder"] = "URL"
section.addFormRow(row)
// Notes
row = XLFormRowDescriptor(tag: "notes", rowType:XLFormRowDescriptorTypeTextView)
row.cellConfigAtConfigure["textView.placeholder"] = "Notes"
section.addFormRow(row)
self.form = form
}
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelPressed:")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "savePressed:")
}
// MARK: XLFormDescriptorDelegate
override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) {
super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
if formRow.tag == "alert" {
if !formRow.value.valueData().isEqual(0) && oldValue.valueData().isEqual(0) {
let newRow = formRow.copy() as! XLFormRowDescriptor
newRow.tag = "secondAlert"
newRow.title = "Second Alert"
self.form.addFormRow(newRow, afterRow:formRow)
}
else if !oldValue.valueData().isEqual(0) && newValue.valueData().isEqual(0) {
self.form.removeFormRowWithTag("secondAlert")
}
}
else if formRow.tag == "all-day" {
let startDateDescriptor = self.form.formRowWithTag("starts")
let endDateDescriptor = self.form.formRowWithTag("ends")
let dateStartCell: XLFormDateCell = self.form.formRowWithTag("starts").cellForFormController(self) as! XLFormDateCell
let dateEndCell: XLFormDateCell = self.form.formRowWithTag("ends").cellForFormController(self) as! XLFormDateCell
if formRow.value.valueData() as? Bool == true {
startDateDescriptor.valueTransformer = DateValueTrasformer.self
endDateDescriptor.valueTransformer = DateValueTrasformer.self
dateStartCell.formDatePickerMode = XLFormDateDatePickerMode.Date
dateEndCell.formDatePickerMode = XLFormDateDatePickerMode.Date
}
else{
startDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
endDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
dateStartCell.formDatePickerMode = XLFormDateDatePickerMode.DateTime
dateEndCell.formDatePickerMode = XLFormDateDatePickerMode.DateTime
}
self.updateFormRow(startDateDescriptor)
self.updateFormRow(endDateDescriptor)
}
else if formRow.tag == "starts" {
let startDateDescriptor = self.form.formRowWithTag("starts")
let endDateDescriptor = self.form.formRowWithTag("ends")
let dateStartCell: XLFormDateCell = self.form.formRowWithTag("starts").cellForFormController(self) as! XLFormDateCell
let dateEndCell: XLFormDateCell = self.form.formRowWithTag("ends").cellForFormController(self) as! XLFormDateCell
if startDateDescriptor.value.compare(endDateDescriptor.value as! NSDate) == NSComparisonResult.OrderedDescending {
// startDateDescriptor is later than endDateDescriptor
endDateDescriptor.value = NSDate(timeInterval: 60*60*24, sinceDate: startDateDescriptor.value as! NSDate)
endDateDescriptor.cellConfig.removeObjectForKey("detailTextLabel.attributedText")
self.updateFormRow(endDateDescriptor)
}
}
else if formRow.tag == "ends" {
let startDateDescriptor = self.form.formRowWithTag("starts")
let endDateDescriptor = self.form.formRowWithTag("ends")
let dateEndCell = endDateDescriptor.cellForFormController(self) as! XLFormDateCell
if startDateDescriptor.value.compare(endDateDescriptor.value as! NSDate) == NSComparisonResult.OrderedDescending {
// startDateDescriptor is later than endDateDescriptor
dateEndCell.update()
let newDetailText : String = dateEndCell.detailTextLabel!.text!
let strikeThroughAttribute = [NSStrikethroughStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue]
let strikeThroughText = NSAttributedString(string: newDetailText, attributes: strikeThroughAttribute)
endDateDescriptor.cellConfig["detailTextLabel.attributedText"] = strikeThroughText
self.updateFormRow(endDateDescriptor)
}
else{
let endDateDescriptor = self.form.formRowWithTag("ends")
endDateDescriptor.cellConfig.removeObjectForKey("detailTextLabel.attributedText")
self.updateFormRow(endDateDescriptor)
}
}
}
func cancelPressed(button: UIBarButtonItem)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func savePressed(button: UIBarButtonItem)
{
let validationErrors : Array<NSError> = self.formValidationErrors() as! Array<NSError>
if (validationErrors.count > 0){
self.showFormValidationError(validationErrors.first)
return
}
self.tableView.endEditing(true)
}
}
class NativeEventNavigationViewController : UINavigationController {
override func viewDidLoad(){
super.viewDidLoad()
self.view.tintColor = UIColor.redColor()
}
}
|
mit
|
476cb0741d33b9b947c4986749f6a1bc
| 46.159184 | 154 | 0.666955 | 5.358998 | false | false | false | false |
milchakov/omim
|
iphone/Maps/UI/Downloader/DownloadMapsViewController.swift
|
4
|
19155
|
@objc(MWMDownloadMapsViewController)
class DownloadMapsViewController: MWMViewController {
// MARK: - Types
private enum NodeAction {
case showOnMap
case download
case update
case cancelDownload
case retryDownload
case delete
}
private enum AllMapsButtonState {
case none
case download(String)
case cancel(String)
}
// MARK: - Outlets
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var statusBarBackground: UIView!
@IBOutlet var noMapsContainer: UIView!
@IBOutlet var searchBarTopOffset: NSLayoutConstraint!
@IBOutlet var downloadAllViewContainer: UIView!
// MARK: - Properties
var dataSource: IDownloaderDataSource!
@objc var mode: MWMMapDownloaderMode = .downloaded
private var skipCountryEvent = false
private var hasAddMapSection: Bool { dataSource.isRoot && mode == .downloaded }
private let allMapsViewBottomOffsetConstant: CGFloat = 64
lazy var noSerchResultViewController: SearchNoResultsViewController = {
let vc = storyboard!.instantiateViewController(ofType: SearchNoResultsViewController.self)
view.insertSubview(vc.view, belowSubview: statusBarBackground)
vc.view.alignToSuperview()
vc.view.isHidden = true
addChild(vc)
vc.didMove(toParent: self)
return vc
}()
lazy var downloadAllView: DownloadAllView = {
let view = Bundle.main.load(viewClass: DownloadAllView.self)?.first as! DownloadAllView
view.delegate = self
downloadAllViewContainer.addSubview(view)
view.alignToSuperview()
return view
}()
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
if dataSource == nil {
switch mode {
case .downloaded:
dataSource = DownloadedMapsDataSource()
case .available:
dataSource = AvailableMapsDataSource(location: LocationManager.lastLocation()?.coordinate)
@unknown default:
fatalError()
}
}
tableView.registerNib(cell: MWMMapDownloaderTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderPlaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderLargeCountryTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderSubplaceTableViewCell.self)
tableView.registerNib(cell: MWMMapDownloaderButtonTableViewCell.self)
title = dataSource.title
if mode == .downloaded {
let addMapsButton = button(with: UIImage(named: "ic_nav_bar_add"), action: #selector(onAddMaps))
navigationItem.rightBarButtonItem = addMapsButton
}
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
if !dataSource.isRoot {
searchBarTopOffset.constant = -searchBar.frame.height
} else {
searchBar.placeholder = L("downloader_search_field_hint")
}
configButtons()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
dataSource.reload {
reloadData()
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
}
Storage.shared().add(self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Storage.shared().remove(self)
}
fileprivate func showChildren(_ nodeAttrs: MapNodeAttributes) {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
vc.mode = dataSource.isSearching ? .available : mode
vc.dataSource = dataSource.dataSourceFor(nodeAttrs.countryId)
navigationController?.pushViewController(vc, animated: true)
}
fileprivate func showActions(_ nodeAttrs: MapNodeAttributes, in cell: UITableViewCell) {
let menuTitle = nodeAttrs.nodeName
let multiparent = nodeAttrs.parentInfo.count > 1
let message = dataSource.isRoot || multiparent ? nil : nodeAttrs.parentInfo.first?.countryName
let actionSheet = UIAlertController(title: menuTitle, message: message, preferredStyle: .actionSheet)
actionSheet.popoverPresentationController?.sourceView = cell
actionSheet.popoverPresentationController?.sourceRect = cell.bounds
let actions: [NodeAction]
switch nodeAttrs.nodeStatus {
case .undefined:
actions = []
case .downloading, .applying, .inQueue:
actions = [.cancelDownload]
case .error:
actions = nodeAttrs.downloadedMwmCount > 0 ? [.retryDownload, .delete] : [.retryDownload]
case .onDiskOutOfDate:
actions = [.showOnMap, .update, .delete]
case .onDisk:
actions = [.showOnMap, .delete]
case .notDownloaded:
actions = [.download]
case .partly:
actions = [.download, .delete]
@unknown default:
fatalError()
}
addActions(actions, for: nodeAttrs, to: actionSheet)
actionSheet.addAction(UIAlertAction(title: L("cancel"), style: .cancel))
present(actionSheet, animated: true)
}
private func addActions(_ actions: [NodeAction], for nodeAttrs: MapNodeAttributes, to actionSheet: UIAlertController) {
actions.forEach { [unowned self] in
let action: UIAlertAction
switch $0 {
case .showOnMap:
action = UIAlertAction(title: L("zoom_to_country"), style: .default, handler: { _ in
Storage.shared().showNode(nodeAttrs.countryId)
self.navigationController?.popToRootViewController(animated: true)
})
case .download:
let prefix = nodeAttrs.totalMwmCount == 1 ? L("downloader_download_map") : L("downloader_download_all_button")
action = UIAlertAction(title: "\(prefix) (\(formattedSize(nodeAttrs.totalSize)))",
style: .default,
handler: { _ in
Storage.shared().downloadNode(nodeAttrs.countryId)
})
case .update:
let size = formattedSize(nodeAttrs.totalUpdateSizeBytes)
let title = "\(L("downloader_status_outdated")) \(size)"
action = UIAlertAction(title: title, style: .default, handler: { _ in
Storage.shared().updateNode(nodeAttrs.countryId)
})
case .cancelDownload:
action = UIAlertAction(title: L("cancel_download"), style: .destructive, handler: { _ in
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
})
case .retryDownload:
action = UIAlertAction(title: L("downloader_retry"), style: .destructive, handler: { _ in
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
})
case .delete:
action = UIAlertAction(title: L("downloader_delete_map"), style: .destructive, handler: { _ in
Storage.shared().deleteNode(nodeAttrs.countryId)
})
}
actionSheet.addAction(action)
}
}
fileprivate func reloadData() {
tableView.reloadData()
configButtons()
}
fileprivate func configButtons() {
downloadAllView.state = .none
downloadAllView.isSizeHidden = false
let parentAttributes = dataSource.parentAttributes()
let error = parentAttributes.nodeStatus == .error || parentAttributes.nodeStatus == .undefined
let downloading = parentAttributes.nodeStatus == .downloading || parentAttributes.nodeStatus == .inQueue || parentAttributes.nodeStatus == .applying
switch mode {
case .available:
if dataSource.isRoot {
break
}
if error {
downloadAllView.state = .error
} else if downloading {
downloadAllView.state = .dowloading
} else if parentAttributes.downloadedMwmCount < parentAttributes.totalMwmCount {
downloadAllView.state = .ready
downloadAllView.style = .download
downloadAllView.downloadSize = parentAttributes.totalSize - parentAttributes.downloadedSize
}
case .downloaded:
let isUpdate = parentAttributes.totalUpdateSizeBytes > 0
let size = isUpdate ? parentAttributes.totalUpdateSizeBytes : parentAttributes.downloadingSize
if error {
downloadAllView.state = dataSource.isRoot ? .none : .error
downloadAllView.downloadSize = parentAttributes.downloadingSize
} else if downloading && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
if dataSource.isRoot {
downloadAllView.style = .download
downloadAllView.isSizeHidden = true
}
} else if isUpdate {
downloadAllView.state = .ready
downloadAllView.style = .update
downloadAllView.downloadSize = size
}
@unknown default:
fatalError()
}
}
@objc func onAddMaps() {
let vc = storyboard!.instantiateViewController(ofType: DownloadMapsViewController.self)
if !dataSource.isRoot {
vc.dataSource = AvailableMapsDataSource(dataSource.parentAttributes().countryId)
}
vc.mode = .available
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - UITableViewDataSource
extension DownloadMapsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
dataSource.numberOfSections() + (hasAddMapSection ? 1 : 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hasAddMapSection && section == dataSource.numberOfSections() {
return 1
}
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if hasAddMapSection && indexPath.section == dataSource.numberOfSections() {
let cellType = MWMMapDownloaderButtonTableViewCell.self
let buttonCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
return buttonCell
}
let nodeAttrs = dataSource.item(at: indexPath)
let cell: MWMMapDownloaderTableViewCell
if nodeAttrs.hasChildren {
let cellType = MWMMapDownloaderLargeCountryTableViewCell.self
let largeCountryCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = largeCountryCell
} else if let matchedName = dataSource.matchedName(at: indexPath), matchedName != nodeAttrs.nodeName {
let cellType = MWMMapDownloaderSubplaceTableViewCell.self
let subplaceCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
subplaceCell.setSubplaceText(matchedName)
cell = subplaceCell
} else if !nodeAttrs.hasParent {
let cellType = MWMMapDownloaderTableViewCell.self
let downloaderCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = downloaderCell
} else {
let cellType = MWMMapDownloaderPlaceTableViewCell.self
let placeCell = tableView.dequeueReusableCell(cell: cellType, indexPath: indexPath)
cell = placeCell
}
cell.mode = dataSource.isSearching ? .available : mode
cell.config(nodeAttrs, searchQuery: searchBar.text)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
dataSource.title(for: section)
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
dataSource.indexTitles()
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
index
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == dataSource.numberOfSections() {
return false
}
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .onDisk, .onDiskOutOfDate, .partly:
return true
default:
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let nodeAttrs = dataSource.item(at: indexPath)
Storage.shared().deleteNode(nodeAttrs.countryId)
}
}
}
// MARK: - UITableViewDelegate
extension DownloadMapsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = MWMMapDownloaderCellHeader()
if section != dataSource.numberOfSections() {
headerView.text = dataSource.title(for: section)
}
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
28
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
section == dataSource.numberOfSections() - 1 ? 68 : 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == dataSource.numberOfSections() {
onAddMaps()
return
}
let nodeAttrs = dataSource.item(at: indexPath)
if nodeAttrs.hasChildren {
showChildren(dataSource.item(at: indexPath))
return
}
showActions(nodeAttrs, in: tableView.cellForRow(at: indexPath)!)
}
}
// MARK: - UIScrollViewDelegate
extension DownloadMapsViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
// MARK: - MWMMapDownloaderTableViewCellDelegate
extension DownloadMapsViewController: MWMMapDownloaderTableViewCellDelegate {
func mapDownloaderCellDidPressProgress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
switch nodeAttrs.nodeStatus {
case .undefined, .error:
Storage.shared().retryDownloadNode(nodeAttrs.countryId)
case .downloading, .applying, .inQueue:
Storage.shared().cancelDownloadNode(nodeAttrs.countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
case .onDiskOutOfDate:
Storage.shared().updateNode(nodeAttrs.countryId)
case .onDisk:
// do nothing
break
case .notDownloaded, .partly:
if nodeAttrs.hasChildren {
showChildren(nodeAttrs)
} else {
Storage.shared().downloadNode(nodeAttrs.countryId)
}
@unknown default:
fatalError()
}
}
func mapDownloaderCellDidLongPress(_ cell: MWMMapDownloaderTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let nodeAttrs = dataSource.item(at: indexPath)
showActions(nodeAttrs, in: cell)
}
}
// MARK: - StorageObserver
extension DownloadMapsViewController: StorageObserver {
func processCountryEvent(_ countryId: String) {
if skipCountryEvent && countryId == dataSource.parentAttributes().countryId {
return
}
dataSource.reload {
reloadData()
noMapsContainer.isHidden = !dataSource.isEmpty || Storage.shared().downloadInProgress()
}
if countryId == dataSource.parentAttributes().countryId {
configButtons()
}
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
guard let indexPath = tableView.indexPath(for: downloaderCell) else { return }
downloaderCell.config(dataSource.item(at: indexPath), searchQuery: searchBar.text)
}
}
func processCountry(_ countryId: String, downloadedBytes: UInt64, totalBytes: UInt64) {
for cell in tableView.visibleCells {
guard let downloaderCell = cell as? MWMMapDownloaderTableViewCell else { continue }
if downloaderCell.nodeAttrs.countryId != countryId { continue }
downloaderCell.setDownloadProgress(CGFloat(downloadedBytes) / CGFloat(totalBytes))
}
let parentAttributes = dataSource.parentAttributes()
if countryId == parentAttributes.countryId {
downloadAllView.downloadProgress = CGFloat(downloadedBytes) / CGFloat(totalBytes)
downloadAllView.downloadSize = totalBytes
} else if dataSource.isRoot && dataSource is DownloadedMapsDataSource {
downloadAllView.state = .dowloading
downloadAllView.isSizeHidden = true
}
}
}
// MARK: - UISearchBarDelegate
extension DownloadMapsViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
navigationController?.setNavigationBarHidden(true, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(false, animated: true)
navigationController?.setNavigationBarHidden(false, animated: true)
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.resignFirstResponder()
dataSource.cancelSearch()
reloadData()
noSerchResultViewController.view.isHidden = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let locale = searchBar.textInputMode?.primaryLanguage
dataSource.search(searchText, locale: locale ?? "") { [weak self] finished in
guard let self = self else { return }
self.reloadData()
self.noSerchResultViewController.view.isHidden = !self.dataSource.isEmpty
}
}
}
// MARK: - UIBarPositioningDelegate
extension DownloadMapsViewController: UIBarPositioningDelegate {
func position(for bar: UIBarPositioning) -> UIBarPosition {
.topAttached
}
}
// MARK: - DownloadAllViewDelegate
extension DownloadMapsViewController: DownloadAllViewDelegate {
func onStateChanged(state: DownloadAllView.State) {
if state == .none {
downloadAllViewContainer.isHidden = true
tableView.contentInset = UIEdgeInsets.zero
} else {
downloadAllViewContainer.isHidden = false
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: allMapsViewBottomOffsetConstant, right: 0)
}
}
func onDownloadButtonPressed() {
skipCountryEvent = true
if mode == .downloaded {
Storage.shared().updateNode(dataSource.parentAttributes().countryId)
} else {
Storage.shared().downloadNode(dataSource.parentAttributes().countryId)
}
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onRetryButtonPressed() {
skipCountryEvent = true
Storage.shared().retryDownloadNode(dataSource.parentAttributes().countryId)
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
}
func onCancelButtonPressed() {
skipCountryEvent = true
Storage.shared().cancelDownloadNode(dataSource.parentAttributes().countryId)
Statistics.logEvent(kStatDownloaderDownloadCancel, withParameters: [kStatFrom: kStatMap])
skipCountryEvent = false
processCountryEvent(dataSource.parentAttributes().countryId)
reloadData()
}
}
|
apache-2.0
|
8810441cb935b2c62655cca10faf9f50
| 35.765835 | 152 | 0.716314 | 5.101198 | false | false | false | false |
lieonCX/Live
|
Live/Others/Lib/RITLImagePicker/Photofiles/Photo/RITLPhotosViewController.swift
|
1
|
14954
|
//
// RITLPhotosViewController.swift
// RITLImagePicker-Swift
//
// Created by YueWen on 2017/1/17.
// Copyright © 2017年 YueWen. All rights reserved.
//
import UIKit
import Photos
let ritl_photos_cellIdentifier = "RITLPhotosCell"
let ritl_photos_resuableViewIdentifier = "RITLPhotoBottomReusableView"
/// 选择图片的一级界面控制器
class RITLPhotosViewController: UIViewController
{
// MARK: public
/// 当前控制器的viewModel
var viewModel = RITLPhotosViewModel()
/// 显示的集合视图
fileprivate lazy var collectionView : UICollectionView = {
var collectionView :UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - 44 - 64),collectionViewLayout:UICollectionViewFlowLayout())
collectionView.delegate = self
collectionView.dataSource = self
if #available(iOS 10, *)
{
collectionView.prefetchDataSource = self
}
collectionView.backgroundColor = .white
//register
collectionView.register(RITLPhotosCell.self, forCellWithReuseIdentifier: ritl_photos_cellIdentifier)
collectionView.register(RITLPhotoBottomReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: ritl_photos_resuableViewIdentifier)
return collectionView
}()
/// 底部的tabBar
fileprivate lazy var bottomBar : UITabBar = {
return UITabBar(frame:CGRect(x: 0, y: self.view.bounds.height - 44 - 64, width: self.view.bounds.width, height:44))
}()
/// 预览按钮
fileprivate lazy var bowerButton : UIButton = {
var button = UIButton(frame: CGRect(x: 5, y: 5, width: 60, height: 30))
button.center = CGPoint(x: button.center.x, y: self.bottomBar.bounds.height / 2)
button.setTitle("预览", for: .normal)
button.setTitle("预览", for: .disabled)
button.setTitleColor(.black, for: .normal)
button.setTitleColor(UIColor.black.withAlphaComponent(0.25), for: .disabled)
button.titleLabel?.font = .systemFont(ofSize: 15)
button.titleLabel?.textAlignment = .center
button.showsTouchWhenHighlighted = true
//默认不可点击
button.isEnabled = false
//响应
button.action(at: .touchUpInside, handle: { [weak self](sender) in
let strongSelf = self
strongSelf?.viewModel.pushBrowerControllerByBrowerButtonTap()
})
return button
}()
/// 发送按钮
fileprivate lazy var sendButton : UIButton = {
var button : UIButton = UIButton(frame: CGRect(x: self.bottomBar.bounds.width - 50 - 5, y: 0, width: 50, height: 40))
button.center = CGPoint(x: button.center.x, y: self.bottomBar.bounds.height / 2)
button.setTitle("完成", for: .normal)
button.setTitle("完成", for: .disabled)
// button.setTitleColor(.colorValue(with: 0x2dd58a), for: .normal)
// button.setTitleColor(UIColor.colorValue(with: 0x2DD58A)?.withAlphaComponent(0.25), for: .disabled)
button.setTitleColor(0x2dd58a.ritl_color, for: .normal)
button.setTitleColor(0x2DD58A.ritl_color.withAlphaComponent(0.25), for: .disabled)
button.titleLabel?.font = .systemFont(ofSize: 15)
button.titleLabel?.textAlignment = .center
button.showsTouchWhenHighlighted = true
//默认不可用
button.isEnabled = false
//发送
button.action(at: .touchUpInside, handle: {[weak self] (sender) in
let strongSelf = self
strongSelf!.viewModel.photoDidSelectedComplete()
})
return button
}()
/// 显示数目的标签
fileprivate lazy var numberOfLabel : UILabel = {
var label : UILabel = UILabel(frame: CGRect(x: self.sendButton.frame.origin.x - 20, y: 0, width: 20, height: 20))
label.center = CGPoint(x: label.center.x, y: self.sendButton.center.y)
// label.backgroundColor = .colorValue(with: 0x2dd58a)
label.backgroundColor = 0x2dd58a.ritl_color
label.textAlignment = .center
label.font = .boldSystemFont(ofSize: 14)
label.text = ""
label.isHidden = true
label.textColor = .white
label.layer.cornerRadius = label.bounds.width / 2.0
label.clipsToBounds = true
return label
}()
// MARK: private
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
// navigationItem.title = viewModel.title
navigationItem.title = "相册"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(RITLPhotosViewController.dimiss))
//添加视图
self.view.backgroundColor = .white
self.view.addSubview(collectionView)
self.view.addSubview(bottomBar)
bottomBar.addSubview(bowerButton)
bottomBar.addSubview(sendButton)
bottomBar.addSubview(numberOfLabel)
//获得资源数
let items = viewModel.numberOfItem(in: 0)
if items >= 1 {
collectionView.scrollToItem(at: IndexPath(item: items - 1, section: 0), at: UICollectionViewScrollPosition.bottom, animated: false)
collectionView.contentOffset = CGPoint(x: 0, y: collectionView.contentOffset.y + 64)
}
bindViewModel()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
print("\(self.self)deinit")
}
/// 更新选中的图片数
///
/// - Parameter numberOfAssets: 选中的图片数
func update(_ numberOfAssets:UInt)
{
let hidden = numberOfAssets == 0
numberOfLabel.isHidden = hidden
if !hidden {
numberOfLabel.text = "\(numberOfAssets)"
numberOfLabel.transform = CGAffineTransform(scaleX: 0.1,y: 0.1)
UIView.animate(withDuration: 0.3, animations: {
self.numberOfLabel.transform = .identity
})
}
}
/// 绑定viewModel的响应
fileprivate func bindViewModel()
{
viewModel.photoSendStatusChangedHandle = {[weak self] (enable,count)in
let strongSelf = self
strongSelf!.bowerButton.isEnabled = enable
strongSelf!.sendButton.isEnabled = enable
strongSelf!.update(count)
}
viewModel.dismissClosure = {[weak self] in
let strongSelf = self
strongSelf?.dimiss()
}
viewModel.warningClosure = {[weak self] (_ ,count) in
let strongSelf = self
strongSelf?.present(alertControllerShow: count)
}
viewModel.photoDidTapShouldBrowerHandle = { [weak self] (result,allAssets,allPhotosAssets,asset,index) in
let strongSelf = self
//初始化控制器
let viewController = RITLPhotoBrowseController()
//获取viewModel
let viewModel = viewController.viewModel
//设置
viewModel.allAssets = allAssets as! [PHAsset]
viewModel.allPhotoAssets = allPhotosAssets as! [PHAsset]
viewModel.current = Int(index)
//刷新当前的视图
viewModel.ritl_browseWilldisappearHandle = {
strongSelf?.collectionView.reloadData()
//检测发送按钮的可用性
strongSelf?.viewModel.ritl_checkSendStatusChanged()
}
//进入下一个浏览控制器
strongSelf?.navigationController?.pushViewController(viewController, animated: true)
}
}
@objc fileprivate func dimiss()
{
self .dismiss(animated: true) { }
}
}
extension RITLPhotosViewController : UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return viewModel.collectonViewModel(sizeForItemAt: indexPath, inCollection: collectionView)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return viewModel.collectonViewModel(referenceSizeForFooterIn: section, inCollection: collectionView)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return viewModel.collectonViewModel(minimumLineSpacingForSectionIn: section)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return viewModel.collectonViewModel(minimumInteritemSpacingForSectionIn: section)
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return viewModel.collectonViewModel(shouldSelectItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
viewModel.collectonViewModel(didSelectedItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
(cell as! RITLPhotosCell).selected(viewModel.viewModel(imageDidSelectedAt: indexPath))
}
}
extension RITLPhotosViewController : UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.viewModel.numberOfItem(in: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : RITLPhotosCell = collectionView.dequeueReusableCell(withReuseIdentifier: ritl_photos_cellIdentifier, for: indexPath) as! RITLPhotosCell
//开始获取图片对象
viewModel.viewModel(imageAt: indexPath, inCollection: collectionView) { [weak cell](image, asset, isImage, timeDuation) in
cell?.ritl_imageView.image = image
cell?.ritl_chooseControl.isHidden = !isImage
// 如果不是图片对象,显示时长等
if !isImage {
cell?.ritl_messageView.isHidden = isImage
// cell?.ritl_messageLabel.text = ritl_timeFormat(timeDuation)
cell?.ritl_messageLabel.text = timeDuation.ritl_time
}
}
//响应
cell.chooseImageDidSelectHandle = { [weak self](sender) in
if (self?.viewModel.viewModel(didSelectedImageAt: indexPath))! {
sender.selected((self?.viewModel.viewModel(imageDidSelectedAt: indexPath))!)
}
}
//响应3D Touch
if #available(iOS 9.0, *) {
// 确认为3D Touch可用
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: cell)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let resuableView : RITLPhotoBottomReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: ritl_photos_resuableViewIdentifier, for: indexPath) as! RITLPhotoBottomReusableView
// 设置显示的数目
resuableView.ritl_numberOfAsset = viewModel.assetCount
return resuableView
}
}
@available(iOS 10, *)
extension RITLPhotosViewController : UICollectionViewDataSourcePrefetching
{
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
viewModel.collectonViewModel(prefetchItemsAt: indexPaths)
}
func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
viewModel.collectonViewModel(cancelPrefetchingForItemsAt: indexPaths)
}
}
@available(iOS 9.0,*)
extension RITLPhotosViewController : UIViewControllerPreviewingDelegate
{
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
let indexPath = collectionView.indexPath(for: previewingContext.sourceView as! RITLPhotosCell)
viewModel.collectonViewModel(didSelectedItemAt: indexPath!)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
//获得索引
let item = collectionView.indexPath(for: previewingContext.sourceView as! RITLPhotosCell)?.item
//获得当前的资源
let asset : PHAsset = viewModel.assetResult?[item!] as! PHAsset
guard asset.mediaType == .image else {
return nil
}
let viewController = RITLPhotoPreviewController()
viewController.showAsset = asset
return viewController
}
}
|
mit
|
dc34891f4b70e7696302fed5b67d5449
| 29.904661 | 255 | 0.615205 | 5.51285 | false | false | false | false |
Zewo/Mustache
|
Sources/Mustache/Goodies/EachFilter.swift
|
1
|
4894
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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.
let EachFilter = Filter { (box: MustacheBox) -> MustacheBox in
// {{# each(nothing) }}...{{/ }}
if box.isEmpty {
return box
}
// {{# each(dictionary) }}...{{/ }}
//
// // Renders "firstName: Charles, lastName: Bronson."
// let dictionary = ["firstName": "Charles", "lastName": "Bronson"]
// let template = try! Template(string: "{{# each(dictionary) }}{{ @key }}: {{ . }}{{^ @last }}, {{/ @last }}{{/ each(dictionary) }}.")
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// try! template.render(Box(["dictionary": dictionary]))
//
// The dictionaryValue box property makes sure to return a
// [String: MustacheBox] whatever the boxed dictionary-like value
// (NSDictionary, [String: Int], [String: CustomObject], etc.
if let dictionary = box.dictionaryValue {
let count = dictionary.count
let transformedBoxes = dictionary.enumerated().map { (index: Int, element: (key: String, box: MustacheBox)) -> MustacheBox in
let customRenderFunction: RenderFunction = { info in
var info = info
// Push positional keys in the context stack and then perform
// a regular rendering.
var position: [String: MustacheBox] = [:]
position["@index"] = Box(boxable: index)
position["@indexPlusOne"] = Box(boxable: index + 1)
position["@indexIsEven"] = Box(boxable: index % 2 == 0)
position["@first"] = Box(boxable: index == 0)
position["@last"] = Box(boxable: (index == count - 1))
position["@key"] = Box(boxable: element.key)
info.context = info.context.extendedContext(Box(boxable: position))
return try element.box.render(info: info)
}
return Box(render: customRenderFunction)
}
return Box(boxable: transformedBoxes)
}
// {{# each(array) }}...{{/ }}
//
// // Renders "1: bread, 2: ham, 3: butter"
// let array = ["bread", "ham", "butter"]
// let template = try! Template(string: "{{# each(array) }}{{ @indexPlusOne }}: {{ . }}{{^ @last }}, {{/ @last }}{{/ each(array) }}.")
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// try! template.render(Box(["array": array]))
//
// The arrayValue box property makes sure to return a [MustacheBox] whatever
// the boxed collection: NSArray, NSSet, [String], [CustomObject], etc.
if let boxes = box.arrayValue {
let count = boxes.count
let transformedBoxes = boxes.enumerated().map { (index: Int, box: MustacheBox) -> MustacheBox in
let customRenderFunction: RenderFunction = { info in
var info = info
// Push positional keys in the context stack and then perform
// a regular rendering.
var position: [String: MustacheBox] = [:]
position["@index"] = Box(boxable: index)
position["@indexPlusOne"] = Box(boxable: index + 1)
position["@indexIsEven"] = Box(boxable: index % 2 == 0)
position["@first"] = Box(boxable: index == 0)
position["@last"] = Box(boxable: (index == count - 1))
info.context = info.context.extendedContext(Box(boxable: position))
return try box.render(info: info)
}
return Box(render: customRenderFunction)
}
return Box(boxable: transformedBoxes)
}
// Non-iterable value
throw MustacheError(kind: .RenderError, message: "Non-enumerable argument in each filter: \(box.value)")
}
|
mit
|
fdebf4a87e746b5cce641fcc39dc8f9e
| 49.443299 | 143 | 0.607398 | 4.452229 | false | false | false | false |
pawan007/SmartZip
|
SmartZip/Controllers/FileBrowser/FBFile.swift
|
1
|
4359
|
//
// FBFile.swift
// FileBrowser
//
// Created by Roy Marmelstein on 14/02/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
import UIKit
/// FBFile is a class representing a file in FileBrowser
public class FBFile: NSObject {
/// Display name. String.
public let displayName: String
// is Directory. Bool.
public let isDirectory: Bool
/// File extension.
public let fileExtension: String?
/// File attributes (including size, creation date etc).
public let fileAttributes: NSDictionary?
/// NSURL file path.
public let filePath: NSURL
// FBFileType
public let type: FBFileType
public var isChecked = false
/**
Initialize an FBFile object with a filePath
- parameter filePath: NSURL filePath
- returns: FBFile object.
*/
init(filePath: NSURL) {
self.filePath = filePath
let isDirectory = checkDirectory(filePath)
self.isDirectory = isDirectory
if self.isDirectory {
self.fileAttributes = nil
self.fileExtension = nil
self.type = .Directory
}
else {
self.fileAttributes = getFileAttributes(self.filePath)
self.fileExtension = filePath.pathExtension
if let fileExtension = fileExtension {
self.type = FBFileType(rawValue: fileExtension) ?? .Default
}
else {
self.type = .Default
}
}
self.displayName = filePath.lastPathComponent ?? String()
}
}
/**
FBFile type
*/
public enum FBFileType: String {
/// Directory
case Directory = "directory"
/// GIF file
case gif = "gif"
case GIF = "GIF"
/// JPG file
case jpg = "jpg"
case JPG = "JPG"
case jpeg = "jpeg"
case JPEG = "JPEG"
/// PLIST file
case json = "json"
case JSON = "JSON"
/// PDF file
case pdf = "pdf"
case PDF = "PDF"
/// PLIST file
case plist = "plist"
case PLIST = "PLIST"
/// PNG file
case png = "png"
case PNG = "PNG"
case doc = "doc"
case DOC = "DOC"
case txt = "txt"
case TXT = "TXT"
/// ZIP file
case zip = "zip"
case ZIP = "ZIP"
case mp3 = "mp3"
case wav = "wav"
case MP3 = "MP3"
case WAV = "WAV"
case m4v = "m4v"
case mp4 = "mp4"
case mov = "mov"
case M4V = "M4V"
case MP4 = "MP4"
case MOV = "MOV"
/// Any file
case Default = "file"
/**
Get representative image for file type
- returns: UIImage for file type
*/
public func image() -> UIImage? {
let bundle = NSBundle(forClass: FileParser.self)
var fileName = String()
switch self {
case Directory: fileName = "myfolder"
// case JPG, jpg, JPEG, jpeg, PNG, png, GIF, gif: fileName = "image"
case JPG, jpg : fileName = "jpg"
case PNG, png : fileName = "png"
case GIF, gif : fileName = "gif"
case PDF, pdf: fileName = "pdf"
case DOC, doc: fileName = "doc"
case TXT, txt: fileName = "txt"
case ZIP, zip: fileName = "zip"
case mp3, MP3,WAV,wav: fileName = "music"
case m4v, M4V, mp4, MP4, MOV, mov: fileName = "video"
default: fileName = "fileIcon"
}
let file = UIImage(named: fileName, inBundle: bundle, compatibleWithTraitCollection: nil)
return file
}
}
/**
Check if file path NSURL is directory or file.
- parameter filePath: NSURL file path.
- returns: isDirectory Bool.
*/
func checkDirectory(filePath: NSURL) -> Bool {
var isDirectory = false
do {
var resourceValue: AnyObject?
try filePath.getResourceValue(&resourceValue, forKey: NSURLIsDirectoryKey)
if let number = resourceValue as? NSNumber where number == true {
isDirectory = true
}
}
catch { }
return isDirectory
}
func getFileAttributes(filePath: NSURL) -> NSDictionary? {
guard let path = filePath.path else {
return nil
}
let fileManager = FileParser.sharedInstance.fileManager
do {
let attributes = try fileManager.attributesOfItemAtPath(path) as NSDictionary
return attributes
} catch {}
return nil
}
|
mit
|
c8e5dc2def5d6629649fb721f0b99555
| 24.940476 | 97 | 0.578706 | 4.26002 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
step2.1-dice-incomplete/Dice Incomplete/RollViewController.swift
|
1
|
1473
|
//
// RollViewController.swift
// Dice
//
// Created by Jason Schatz on 11/6/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - RollViewController: UIViewController
class RollViewController: UIViewController {
// MARK: Generate Dice Value
// randomly generates a Int from 1 to 6
func randomDiceValue() -> Int {
// generate a random Int32 using arc4Random
let randomValue = 1 + arc4random() % 6
// return a more convenient Int, initialized with the random value
return Int(randomValue)
}
// MARK: Actions
@IBAction func rollTheDice() {
// var controller: DiceViewController
//
// controller = self.storyboard?.instantiateViewControllerWithIdentifier("DiceViewController") as! DiceViewController
//
// controller.firstValue = self.randomDiceValue()
// controller.secondValue = self.randomDiceValue()
//
// presentViewController(controller, animated: true, completion: nil)
self.performSegueWithIdentifier("rollDice", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "rollDice" {
let controller = segue.destinationViewController as! DiceViewController
controller.firstValue = self.randomDiceValue()
controller.secondValue = self.randomDiceValue()
}
}
}
|
mit
|
114358988c543de6d16ad5c99adc3a7a
| 30.340426 | 124 | 0.655126 | 4.798046 | false | false | false | false |
nickdex/cosmos
|
code/sorting/src/median_sort/median_sort.swift
|
5
|
2848
|
/* Part of Cosmos by OpenGenus Foundation */
//
// median_sort.swift
// Created by DaiPei on 2017/10/25.
//
import Foundation
func medianSort(_ array: inout [Int]) {
recursiveMediaSort(&array, left: 0, right: array.count - 1)
}
private func recursiveMediaSort(_ array: inout [Int], left: Int, right: Int) {
if left < right {
var piv = pivot(&array, left: left, right: right)
piv = partition(&array, left: left, right: right, pivot: piv)
recursiveMediaSort(&array, left: left, right: piv - 1)
recursiveMediaSort(&array, left: piv + 1, right: right)
}
}
// find a good pivot for quick sort
private func pivot(_ array: inout [Int], left: Int, right: Int) -> Int {
let range = right - left + 1
if range < 6 {
return median5(&array, left: left, right: right)
}
for subLeft in stride(from: left, to: right + 1, by: 5) {
var subRight = subLeft + 4
if subRight > right {
subRight = right
}
let medianIndex = median5(&array, left: subLeft, right: subRight)
swap(&array, at: medianIndex, and: Int(floor(Double(subLeft - left) / 5)) + left)
}
return select(&array, left: left, right: left + (range - 1) / 5, of: left + range / 10)
}
// find median in 5 number
private func median5(_ array: inout [Int], left: Int, right: Int) -> Int {
let mid = (left + right) / 2
if left < right {
for i in left..<right {
var p = i
for j in i + 1...right {
if array[j] < array[p] {
p = j
}
}
swap(&array, at: p, and: i)
if i >= mid {
break
}
}
}
return mid
}
// select the rank k number in array
private func select(_ array: inout [Int], left: Int, right: Int, of k: Int) -> Int {
if (left == right) {
return left
}
var piv: Int
var r = right
var l = left
repeat {
piv = pivot(&array, left: l, right: r)
piv = partition(&array, left: l, right: r, pivot: piv)
if piv == k {
break
} else if piv > k {
r = piv - 1
} else {
l = piv + 1
}
} while piv != k
return k
}
// normal partition method in quick sort
private func partition(_ array: inout [Int], left: Int, right: Int, pivot: Int) -> Int {
var p1 = left
var p2 = left
swap(&array, at: pivot, and: right)
while p2 < right {
if array[p2] < array[right] {
swap(&array, at: p2, and: p1)
p1 += 1
}
p2 += 1
}
swap(&array, at: right, and: p1)
return p1
}
private func swap(_ array: inout [Int], at indexA: Int, and indexB: Int) {
let tmp = array[indexA]
array[indexA] = array[indexB]
array[indexB] = tmp
}
|
gpl-3.0
|
9cc02ead9140158d20590c99c232b551
| 26.650485 | 91 | 0.530197 | 3.390476 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Foundation/Accessibility/Accessibility.swift
|
1
|
2416
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
/// Accessibility construct that to support multiple accessibility assignments at once
public struct Accessibility {
/// The accessibility identifier
public let id: String?
/// The accessibility label
public let label: String?
/// The accessibility hint
public let hint: String?
/// The accessibility traits of the view
public let traits: UIAccessibilityTraits
/// Is accessibility element
public let isAccessible: Bool
/// Initializes inner properties by defaulting all parameters to `nil`.
public init(
id: String? = .none,
label: String? = .none,
hint: String? = .none,
traits: UIAccessibilityTraits = .none,
isAccessible: Bool = true
) {
self.id = id
self.label = label
self.hint = hint
self.traits = traits
self.isAccessible = isAccessible
}
func with(idSuffix: String) -> Accessibility {
Accessibility(
id: id == nil ? nil : "\(id.printable)\(idSuffix)",
label: label,
hint: hint,
traits: traits,
isAccessible: isAccessible
)
}
public func copy(
id: String? = nil,
label: String? = nil,
hint: String? = nil,
traits: UIAccessibilityTraits? = nil
) -> Accessibility {
Accessibility(
id: id != nil ? id : self.id,
label: label != nil ? label : self.label,
hint: hint != nil ? hint : self.hint,
traits: traits != nil ? traits ?? .none : self.traits
)
}
}
// MARK: - Conveniences
extension Accessibility {
public static func id(_ rawValue: String) -> Accessibility {
.init(id: rawValue)
}
public static func label(_ rawValue: String) -> Accessibility {
.init(label: rawValue)
}
/// `.none` represents an inaccessible element
public static var none: Accessibility {
Accessibility(isAccessible: false)
}
}
extension Accessibility: Equatable {
public static func == (lhs: Accessibility, rhs: Accessibility) -> Bool {
lhs.id == rhs.id
}
}
extension Optional {
public var printable: Any {
switch self {
case .none:
return ""
case .some(let value):
return value
}
}
}
|
lgpl-3.0
|
1d4cad61e41dbcdc8db7a2dfe0ea5204
| 24.421053 | 86 | 0.583851 | 4.644231 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/PackageCollectionsSigning/Key/ASN1/SubjectPublicKeyInfo.swift
|
2
|
3759
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See http://swift.org/LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
//===----------------------------------------------------------------------===//
import Foundation
// Source: https://github.com/apple/swift-crypto/blob/main/Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift
extension ASN1 {
struct SubjectPublicKeyInfo: ASN1Parseable {
var algorithmIdentifier: RFC5480AlgorithmIdentifier
var key: ASN1.ASN1BitString
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
// The SPKI block looks like this:
//
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING
// }
self = try ASN1.sequence(rootNode) { nodes in
let algorithmIdentifier = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
let key = try ASN1.ASN1BitString(asn1Encoded: &nodes)
return SubjectPublicKeyInfo(algorithmIdentifier: algorithmIdentifier, key: key)
}
}
private init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: ASN1.ASN1BitString) {
self.algorithmIdentifier = algorithmIdentifier
self.key = key
}
}
enum RFC5480AlgorithmIdentifier: ASN1Parseable {
case ecdsaP256
case ecdsaP384
case ecdsaP521
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
// The AlgorithmIdentifier block looks like this.
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL
// }
//
// ECParameters ::= CHOICE {
// namedCurve OBJECT IDENTIFIER
// -- implicitCurve NULL
// -- specifiedCurve SpecifiedECDomain
// }
//
// We don't bother with helpers: we just try to decode it directly.
self = try ASN1.sequence(rootNode) { nodes in
let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
guard algorithmOID == ASN1ObjectIdentifier.AlgorithmIdentifier.idEcPublicKey else {
throw ASN1Error.invalidASN1Object
}
let curveNameOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
switch curveNameOID {
case ASN1ObjectIdentifier.NamedCurves.secp256r1:
return .ecdsaP256
case ASN1ObjectIdentifier.NamedCurves.secp384r1:
return .ecdsaP384
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
return .ecdsaP521
default:
throw ASN1Error.invalidASN1Object
}
}
}
}
}
|
apache-2.0
|
984401ab6dcb692199b3930b843220de
| 37.357143 | 105 | 0.557595 | 4.881818 | false | false | false | false |
remypanicker/firefox-ios
|
Client/Frontend/Settings/SettingsTableViewController.swift
|
7
|
41100
|
/* 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 Account
import Base32
import Shared
import UIKit
import XCGLogger
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var _title: NSAttributedString?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign in", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
private class SyncNowSetting: WithAccountSetting {
private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIConstants.DefaultStandardFont])
private let syncingTitle = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var style: UITableViewCellStyle { return .Value1 }
override var title: NSAttributedString? {
return profile.syncManager.isSyncing ? syncingTitle : syncNowTitle
}
override func onConfigureCell(cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.userInteractionEnabled = !profile.syncManager.isSyncing
}
override func onClick(navigationController: UINavigationController?) {
profile.syncManager.syncEverything()
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
if let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) {
cs.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs.URL
}
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// For great debugging!
private class HiddenSetting: Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
extension NSFileManager {
public func removeItemInDirectory(directory: String, named: String) throws {
if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named).path {
try self.removeItemAtPath(file)
}
}
}
private class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
do {
try NSFileManager.defaultManager().removeItemInDirectory(documentsPath, named: "browser.db")
} catch {
print("Couldn't delete exported data: \(error).")
}
}
}
private class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
if let browserDB = NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("browser.db").path {
do {
try self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB)
} catch {
print("Couldn't export browser data: \(error).")
}
}
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens about:rights page in the content view controller
private class YourRightsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"))
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("rights", module: "about"))
}
private override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(true)
}
})
}
}
private class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
class UseCompactTabLayoutSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("CompactTabLayout") ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "CompactTabLayout")
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let clearable = EverythingClearable(profile: profile, tabmanager: tabManager)
var title: String { return NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") }
var message: String { return NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") }
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let clearString = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
alert.addAction(UIAlertAction(title: clearString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in
clearable.clear() >>== { NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataCleared, object: nil) }
}))
let cancelString = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
alert.addAction(UIAlertAction(title: cancelString, style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in }))
navigationController?.presentViewController(alert, animated: true) { () -> Void in }
}
}
private class SendCrashReportsSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("crashreports.send.always") ?? false
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "crashreports.send.always")
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
}
}
private class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
private class PopupBlockingSettings: Setting {
let prefs: Prefs
let tabManager: TabManager!
let prefKey = "blockPopups"
init(settings: SettingsTableViewController) {
self.prefs = settings.profile.prefs
self.tabManager = settings.tabManager
let title = NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")
let attributes = [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]
super.init(title: NSAttributedString(string: title, attributes: attributes))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(toggle: UISwitch) {
prefs.setObject(toggle.on, forKey: prefKey)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
var generalSettings = [
SearchSetting(settings: self),
PopupBlockingSettings(settings: self),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [UseCompactTabLayoutSetting(settings: self)]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: [
ClearPrivateDataSetting(settings: self),
SendCrashReportsSetting(settings: self),
PrivacyPolicySetting(),
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
YourRightsSetting(),
DisconnectSetting(settings: self),
ExportBrowserDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidFinishSyncingNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil)
}
@objc private func SELsyncDidChangeState() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0 && indexPath.row == 0) { return 64 } //make account/sign-in row taller, as per design specs
return 44
}
}
class SettingsTableFooterView: UIView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
layer.addSublayer(topBorder)
addSubview(logo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
}
class SettingsTableSectionHeaderView: UITableViewHeaderFooterView {
var showTopBorder: Bool = true {
didSet {
topBorder.hidden = !showTopBorder
}
}
var showBottomBorder: Bool = true {
didSet {
bottomBorder.hidden = !showBottomBorder
}
}
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
private lazy var bottomBorder: CALayer = {
let bottomBorder = CALayer()
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
clipsToBounds = true
layer.addSublayer(topBorder)
layer.addSublayer(bottomBorder)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
bottomBorder.frame = CGRectMake(0.0, frame.size.height - 0.5, frame.size.width, 0.5)
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
titleLabel.sizeToFit()
}
}
|
mpl-2.0
|
374ab594c9fffb6b3ec39cb8c9aca1ad
| 41.498449 | 303 | 0.688437 | 5.717307 | false | false | false | false |
coinbase/coinbase-ios-sdk
|
Source/Resources/Accounts/Models/Currency.swift
|
1
|
3350
|
//
// CurrencyInfo.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc.. All rights reserved.
//
/// Represents account's currency.
///
open class Currency: Decodable {
/// Currency code.
///
/// Currency codes will conform to the ISO 4217 standard where possible.
/// Currencies which have or had no representation in ISO 4217 may use a custom code in ISO format, ex. `"BTC"`, `"USD"`.
///
public let code: String
/// Human readable name of this currency (e.g. 'Bitcoin').
public let name: String?
/// Color of this currency.
public let color: String?
/// Decimal precision.
///
/// Bitcoin, Bitcoin Cash, Litecoin and Ethereum values will have 8 decimal points and fiat currencies will have two.
public let exponent: Int?
/// Currency type.
///
/// See also: `CurrencyType` constants.
public let type: String?
/// A regular expression to check whether crypto currency address is valid.
///
/// - Note:
/// This property is not present for fiat currencies.
///
public let addressRegex: String?
/// An asset id that can be used to get a particular crypto asset
public let assetId: String?
/// Presence of this parameter indicates that the currency requires a destination tag for send/receive
public let destinationTagName: String?
/// The destination tag regex
public let destinationTagRegex: String?
private enum CodingKeys: String, CodingKey {
case code, name, color, exponent, type, addressRegex, assetId, destinationTagName, destinationTagRegex
}
public required init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self) {
self.code = try container.decode(String.self, forKey: .code)
self.name = try container.decodeIfPresent(String.self, forKey: .name)
self.color = try container.decodeIfPresent(String.self, forKey: .color)
self.exponent = try container.decodeIfPresent(Int.self, forKey: .exponent)
self.type = try container.decodeIfPresent(String.self, forKey: .type)
self.addressRegex = try container.decodeIfPresent(String.self, forKey: .addressRegex)
self.assetId = try container.decodeIfPresent(String.self, forKey: .assetId)
self.destinationTagName = try container.decodeIfPresent(String.self, forKey: .destinationTagName)
self.destinationTagRegex = try container.decodeIfPresent(String.self, forKey: .destinationTagRegex)
} else if let code = try? decoder.singleValueContainer().decode(String.self) {
self.code = code
self.name = nil
self.color = nil
self.exponent = nil
self.type = nil
self.addressRegex = nil
self.assetId = nil
self.destinationTagName = nil
self.destinationTagRegex = nil
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Undefined resource type. Failed to decode."))
}
}
}
/// List of available currency types.
public struct CurrencyType {
/// Crypto currency.
public static let crypto = "crypto"
/// Fiat currency.
public static let fiat = "fiat"
}
|
apache-2.0
|
387fb137e570d9d5cfe305e17eb9ec7a
| 37.94186 | 148 | 0.654225 | 4.670851 | false | false | false | false |
liuyx7894/Notifier
|
Notifier/Notifier.swift
|
1
|
5367
|
//
// Notifier.swift
// Notifier
//
// Created by Louis Liu on 28/04/2017.
// Copyright © 2017 Louis Liu. All rights reserved.
//
import UIKit
class Notifier: NSObject {
struct NotifyModel {
var title:String = ""
var body:String = ""
var userObject:Any?
init(title:String, body:String, userObject:Any?) {
self.title = title
self.body = body
self.userObject = userObject
}
}
typealias OnTapNotifierCallback = ((Any?)->Void)
private static let exhibitionSec:Double = 3.0
private let notifierHeight:CGFloat = 54 + 20
private let titleHeight:CGFloat = 15
private let margin:CGFloat = 15
private let notifierMargin:CGFloat = 0
private var processQueue = [NotifyModel]()
private var notifiView:UIView!
private var label_title:UILabel!
private var label_body:UILabel!
private static var NotifierAssociatedKey = "NotifierAssociatedKey"
static let shared = Notifier()
var onTapped:OnTapNotifierCallback?
private var isShowing:Bool = false {
didSet {
self.showCurrentNotifier()
}
}
lazy var keyWindow:UIWindow! = {
var tmp = UIApplication.shared.keyWindow
if(tmp == nil ){
tmp = UIApplication.shared.windows.first
}
return tmp
}()
override init() {
super.init()
initNotifier()
}
func showNotifier(title:String, body:String, onTapNotifier:OnTapNotifierCallback?){
showNotifier(title:title, body:body, withObject: nil, onTapNotifier:onTapNotifier)
}
func showNotifier(title:String, body:String, withObject obj:Any?, onTapNotifier:OnTapNotifierCallback?){
onTapped = onTapNotifier
processQueue.append(NotifyModel(title: title, body: body, userObject:obj))
if(isShowing == false){
isShowing = true
}
}
func dismissNotifier(withSec sec:Double){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(sec * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
self.dismissNotifier()
})
}
func dismissNotifier(){
if let _ = processQueue.first {
DispatchQueue.main.async {
UIView.animate(withDuration: 0.33, animations: {
self.notifiView.frame.origin.y = -self.notifierHeight
}, completion: { (complete) in
if complete {
self.notifiView.removeFromSuperview()
self.processQueue.remove(at: 0)
self.isShowing = false
}
})
}
}
}
private func showCurrentNotifier(){
if let model = processQueue.first {
DispatchQueue.main.async {
self.notifiView.frame.origin.y = -self.notifierHeight
self.keyWindow.addSubview(self.notifiView)
self.label_title.text = model.title
self.label_body.text = model.body
UIView.animate(withDuration: 0.33, animations: {
self.notifiView.frame.origin.y = 0
})
self.dismissNotifier(withSec: Notifier.exhibitionSec)
}
}
}
private func initNotifier(){
let screenWidth = keyWindow!.bounds.width
notifiView = UIView(frame: CGRect.init(x: CGFloat(notifierMargin),
y: CGFloat(notifierMargin),
width: screenWidth - notifierMargin*2,
height: notifierHeight))
let effectiveView = UIVisualEffectView(frame: notifiView.frame)
let effect = UIBlurEffect.init(style: .prominent)
effectiveView.effect = effect
notifiView.insertSubview(effectiveView, at: 0)
label_title = UILabel(frame: CGRect.init(x: margin, y: 25, width: screenWidth-margin, height: titleHeight))
label_title.text = "您有一条新消息"
label_title.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightHeavy)
label_title.textColor = UIColor.black
label_body = UILabel(frame: CGRect.init(x: margin, y: label_title.frame.maxY, width: screenWidth-margin, height: 24))
label_body.text = "学习学习经历卡绝世独立卡就收到了空啊实打实的离开家啊收到了空间阿斯利康多久啊啥的间"
label_body.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightThin)
label_body.numberOfLines = 0
label_body.textColor = UIColor.black
notifiView.addSubview(label_title)
notifiView.addSubview(label_body)
notifiView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.onTappedNotifier)))
}
@objc private func onTappedNotifier(){
if let model = processQueue.first {
let obj = model.userObject
if(onTapped != nil){
onTapped!(obj)
}
}
}
}
|
mit
|
28d9f1475c4405c8587cdfdc885c9586
| 31.9375 | 145 | 0.570588 | 4.667848 | false | false | false | false |
jmkr/SimpleAssetPicker
|
SimpleAssetPicker/AssetCollectionViewCell.swift
|
1
|
5515
|
//
// AssetCollectionViewCell.swift
// SimpleAssetPicker
//
// Created by John Meeker on 6/27/16.
// Copyright © 2016 John Meeker. All rights reserved.
//
import UIKit
import PureLayout
class AssetCollectionViewCell: UICollectionViewCell {
var representedAssetIdentifier: String = ""
fileprivate var didSetupConstraints: Bool = false
lazy var imageView: UIImageView! = {
let imageView = UIImageView.newAutoLayout()
imageView.contentMode = .scaleAspectFill
return imageView
}()
lazy var gradientView: GradientView! = {
return GradientView.newAutoLayout()
}()
lazy var checkMarkImageView: UIImageView! = {
let imageView = UIImageView.newAutoLayout()
imageView.alpha = 0.0
return imageView
}()
lazy var livePhotoBadgeImageView: UIImageView! = {
return UIImageView.newAutoLayout()
}()
lazy var cameraIconImageView: UIImageView! = {
return UIImageView.newAutoLayout()
}()
lazy var videoLengthLabel: UILabel! = {
let label = UILabel.newAutoLayout()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 13.0)
return label
}()
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
self.livePhotoBadgeImageView.image = nil
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
updateConstraints()
}
fileprivate func setupViews() {
self.clipsToBounds = true
self.backgroundColor = .white
self.addSubview(self.imageView)
self.addSubview(self.gradientView)
self.addSubview(self.checkMarkImageView)
self.addSubview(self.livePhotoBadgeImageView)
self.addSubview(self.cameraIconImageView)
self.addSubview(self.videoLengthLabel)
}
override var isSelected: Bool {
get {
return super.isSelected
}
set {
if newValue {
super.isSelected = true
self.imageView.alpha = 0.6
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseIn, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 0.98, y: 0.98)
self.checkMarkImageView.alpha = 1.0
}, completion: { (finished) -> Void in
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform.identity
}, completion:nil)
})
} else if newValue == false {
super.isSelected = false
self.imageView.alpha = 1.0
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseIn, .allowUserInteraction], animations: { () -> Void in
//self.transform = CGAffineTransformMakeScale(1.02, 1.02)
self.checkMarkImageView.alpha = 0.0
}, completion: { (finished) -> Void in
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform.identity
}, completion:nil)
})
}
}
}
override func updateConstraints() {
if !didSetupConstraints {
self.imageView.autoPinEdgesToSuperviewEdges()
self.gradientView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top)
self.gradientView.autoSetDimension(.height, toSize: 30)
self.checkMarkImageView.autoPinEdge(toSuperviewEdge: .top, withInset: 4)
self.checkMarkImageView.autoPinEdge(toSuperviewEdge: .right, withInset: 4)
self.checkMarkImageView.autoSetDimensions(to: CGSize(width: 18, height: 18))
self.livePhotoBadgeImageView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.livePhotoBadgeImageView.autoPinEdge(toSuperviewEdge: .left, withInset: 4)
self.livePhotoBadgeImageView.autoSetDimensions(to: CGSize(width: 20, height: 20))
self.cameraIconImageView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.cameraIconImageView.autoPinEdge(toSuperviewEdge: .left, withInset: 4)
self.cameraIconImageView.autoSetDimensions(to: CGSize(width: 20, height: 17))
self.videoLengthLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.videoLengthLabel.autoPinEdge(toSuperviewEdge: .right, withInset: 4)
didSetupConstraints = true
}
super.updateConstraints()
}
func getTimeStringOfTimeInterval(_ timeInterval: TimeInterval) -> String {
let ti = NSInteger(timeInterval)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
if hours > 0 {
return String(format: "%0.d:%0.d:%0.2d",hours,minutes,seconds)
} else if minutes > 0 {
return String(format: "%0.d:%0.2d",minutes,seconds)
} else {
return String(format: "0:%0.2d",seconds)
}
}
}
|
mit
|
29f765279b9f88f1e21d60dfdad8c2a0
| 35.516556 | 146 | 0.60827 | 4.994565 | false | false | false | false |
authorfeng/argparse.swift
|
argparse.swift
|
1
|
56951
|
//
// argparse.swift
//
// Created by authorfeng on 27/08/2017.
// Copyright © 2017 Author Feng. All rights reserved.
//
import Foundation
// MARK:- Const
let SUPPRESS = "==SUPPRESS=="
let OPTIONAL = "?"
let ZERO_OR_MORE = "*"
let ONE_OR_MORE = "+"
let PARSER = "A..."
let REMAINDER = "..."
let _UNRECOGNIZED_ARGS_ATTR = "_unrecognized_args"
// MARK:- Utility functions and classes
func hasatter(_ obj: Any, _ name: String) -> Bool {
let mirror = Mirror(reflecting: obj)
for case let (label?, _) in mirror.children {
if label == name {
return true
}
}
return false
}
func getEnvironmentVar(_ name: String) -> String? {
guard let rawValue = getenv(name) else { return nil }
return String(utf8String: rawValue)
}
func setEnvironmentVar(name: String, value: String, overwrite: Bool) {
setenv(name, value, overwrite ? 1 : 0)
}
struct RegexHelper {
let regex: NSRegularExpression?
init(_ pattern: String) {
regex = try! NSRegularExpression(pattern: "^-\\d+$|^-\\d*\\.\\d+$",
options: NSRegularExpression.Options.caseInsensitive)
}
func match(_ input: String) -> Bool {
if let matchs = regex?.matches(in: input,
range: NSMakeRange(0, input.utf8.count)) {
return matchs.count > 0
} else {
return false
}
}
}
extension String {
static let None = ""
static let identifierMatcher = RegexHelper("[a-z0-9A-Z\\_]*")
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return self[start..<end]
}
subscript (r: ClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return self[start...end]
}
func substring(from index: Int) -> String {
return self.substring(from: self.index(self.startIndex, offsetBy: index))
}
func substring(to index: Int) -> String {
return self.substring(to: self.index(self.startIndex, offsetBy: index))
}
func lstrip(inStr: String=" ") -> String {
let trimedStr = self.trimmingCharacters(in: CharacterSet(charactersIn: inStr))
if trimedStr.isEmpty {
return trimedStr
}
let range = self.localizedStandardRange(of: trimedStr)
return self.substring(from:range!.lowerBound)
}
func join(_ objs: Array<Any>) -> String {
var js = ""
if objs.isEmpty {
return js
}
for obj in objs {
js += "\(obj)\(self)"
}
return js.substring(to: js.index(js.startIndex, offsetBy: js.utf8.count - self.utf8.count))
}
func split(_ separator: String, _ maxSplits: Int) -> Array<String> {
if maxSplits == 0 {
return [self]
}
let arr = self.components(separatedBy: separator)
if maxSplits < 0 || maxSplits + 1 >= arr.count {
return arr
}
var retArr = Array(arr[arr.startIndex ..< maxSplits])
retArr.append("=".join(Array(arr[maxSplits ..< arr.endIndex])))
return retArr
}
func isidentifier() -> Bool {
return String.identifierMatcher.match(self)
}
}
extension Dictionary {
func hasKey(_ key: Key) -> Bool {
return self.keys.contains(key)
}
func hasattr(_ key: Key) -> Bool {
return self.hasKey(key)
}
mutating func setattr(_ key: Key, _ value: Value) -> Void {
self.updateValue(value, forKey: key)
}
mutating func setdefault(forKey key: Key, _ `default`: Value?=nil) -> Value? {
if self.hasKey(key) {
return self[key]!
} else {
if let deft = `default` {
self.updateValue(deft, forKey: key)
return deft
} else {
return nil
}
}
}
func get(forKey: Key, `default`: Value) -> Value {
if self.hasKey(forKey) {
return self[forKey]!
} else {
return `default`
}
}
mutating func pop(forKey: Key, _ `default`: Value) -> Value {
self.setdefault(forKey: forKey, `default`)
return self.removeValue(forKey: forKey)!
}
mutating func update(_ dic: Dictionary<Key, Value>) {
for k in dic.keys {
self.updateValue(dic[k]!, forKey: k)
}
}
}
protocol _AttributeHolder {
typealias Attribute = (String, Any?)
var __dict__: Dictionary<String, Any?> { get }
func __repr__() -> String
func _get_kwargs() -> [Attribute]
func _get_args() -> [Any]
}
extension _AttributeHolder {
public func __repr__() -> String {
let type_name = type(of: self)
var arg_strings: [String] = []
var star_args: [String: Any] = [:]
for arg in self._get_args() {
arg_strings.append("\(arg)")
}
for (name, value) in self._get_kwargs() {
if name.isidentifier() {
arg_strings.append("\(name)=\(String(describing: value))")
} else {
star_args[name] = value
}
}
if !star_args.isEmpty {
arg_strings.append("**\(star_args)")
}
return "\(type_name)(\(", ".join(arg_strings))))"
}
public func _get_kwargs() -> [Attribute] {
var kwargs: [Attribute] = []
for key in self.__dict__.keys.sorted() {
kwargs.append((key, self.__dict__[key]))
}
return kwargs
}
public func _get_args() -> [Any] {
return []
}
}
// MARK:- Formatting Help
class _Formatter {
func _indent() {
}
}
class HelpFormatter: _Formatter {
var _current_indent = 0
var _indent_increment = 0
var _max_help_position = 0
var _action_max_length = 0
var _level = 0
var _width = 80
var _prog = String.None
var _root_section: _Section = _Section()
let _whitespace_matcher: RegexHelper
let _long_break_matcher: RegexHelper
override init() {
self._whitespace_matcher = RegexHelper(String.None)
self._long_break_matcher = self._whitespace_matcher
}
required init(_ prog: String, _ indent_increment: Int, _ max_help_position: Int, _ width: Int) {
// default setting for width
let indent_increment = (indent_increment < 0) ? 2 : indent_increment
let max_help_position = (max_help_position < 0) ? 24 : max_help_position
let width = (width < 0) ? 80 : width
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = max_help_position
self._max_help_position = min(max_help_position, max(width - 20, indent_increment))
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._whitespace_matcher = RegexHelper("\\s+")
self._long_break_matcher = RegexHelper("\\n\\n\\n+")
super.init()
self._root_section = _Section(self, nil)
}
// MARK: Section and indentation methods
override func _indent() {
self._current_indent += self._indent_increment
self._level += 1
}
func _dedent() {
self._current_indent -= self._indent_increment
assert(self._current_indent >= 0, "Indent decreased below 0.")
self._level -= 1
}
class _Section {
let formatter: _Formatter
let parent: String // todo
let heading: String
var items: Array<Any> = []
init() {
self.formatter = _Formatter()
self.parent = String.None
self.heading = String.None
}
init(_ formatter: HelpFormatter, _ parent: String?, _ heading: String=String.None) {
self.formatter = formatter
if (parent != nil) {
self.parent = parent!
} else {
self.parent = String.None
}
self.heading = heading
self.items = []
}
func format_help() -> String {
if !self.parent.isEmpty {
self.formatter._indent()
}
return String.None
}
}
func _add_item() {
}
// MARK: Message building methods
func start_section() {
}
func end_section() {
}
func add_text(_ text: String) {
}
func add_usage(_ usage: String) {
}
func add_argument(_ action: Action) {
}
func add_arguments(_ actions: Array<Action>) {
for action in actions {
self.add_argument(action)
}
}
// MARK: Help-formatting methods
func format_help() -> String {
return ""
}
func _join_parts(_ part_strings: Array<String>) -> String {
return ""
}
func _format_usage(_ useage: String) -> String {
return ""
}
func _format_actions_usage() -> String {
return ""
}
func _format_text(_ text: String) -> String {
return ""
}
func _format_action(_ action: Action) -> String {
return ""
}
func _format_action_invocation(_ action: Action) -> String {
return ""
}
func _metavar_formatter(_ action: Action, _ default_metavar: String) -> (Int) -> String {
let result: String
if action.metavar != nil {
result = action.metavar!
} else if !action.choices.isEmpty {
let choice_strs = action.choices.map {String(describing: $0)}
result = String("{\(", ".join(choice_strs))}")
} else {
result = default_metavar
}
func format(_ tuple_size: Int) -> String {
// todo:
return result
}
return format
}
func _format_args(_ action: Action, _ default_metavar: String) -> String {
let get_metavar = self._metavar_formatter(action, default_metavar)
var result = ""
let metaver = get_metavar(1)
if action.nargs == nil {
result = metaver
} else if let nargs = action.nargs as? String {
if nargs == OPTIONAL {
result = String("[\(metaver)]")
} else if nargs == ZERO_OR_MORE {
result = String("[\(metaver) [\(metaver) ...]]")
} else if nargs == REMAINDER {
result = "..."
} else if nargs == PARSER {
result = String("\(get_metavar(1)) ...)")
}
} else if let nargs = action.nargs as? Int {
result = " ".join(Array(repeating: metaver, count: nargs))
}
return result
}
func _expand_help(_ action: Action) -> String {
return ""
}
func _iter_indented_subactions(_ action: Action) {
}
func _split_lines(_ text: String, _ width: Int) -> String {
return ""
}
func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String {
return ""
}
func _get_help_string(_ action: Action) -> String {
return action.help
}
func _get_default_metavar_for_optional(_ action: Action) -> String {
return action.dest!.uppercased()
}
func _get_default_metavar_for_positional(_ action: Action) -> String {
return action.dest!
}
}
class RawDescriptionHelpFormatter: HelpFormatter {
override func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String {
return ""
}
}
class RawTextHelpFormatter: RawDescriptionHelpFormatter {
func _fill_text(_ text: String, _ width: Int) -> String {
return ""
}
}
class ArgumentDefaultsHelpFormatter: HelpFormatter {
override func _get_help_string(_ action: Action) -> String {
return ""
}
}
class MetavarTypeHelpFormatter: HelpFormatter {
override func _get_default_metavar_for_optional(_ action: Action) -> String {
return ""
}
override func _get_default_metavar_for_positional(_ action: Action) -> String {
return ""
}
}
// MARK:- Options and Arguments
func _get_action_name(_ argument: Action) -> String {
if !argument.option_strings.isEmpty {
return "/".join(argument.option_strings)
}
else if let metavar = argument.metavar {
if metavar != SUPPRESS {
return metavar
}
}
else if let dest = argument.dest {
if dest != SUPPRESS {
return dest
}
}
return String.None
}
enum AE: Error {
case ArgumentError(argument: Any, message: String)
case ArgumentTypeError
}
// MARK:- Action classes
let _ACTIONS_DICTIONARY = [
"_StoreAction.Type": _StoreAction.self,
"_StoreConstAction.Type": _StoreConstAction.self,
"_StoreTrueAction.Type": _StoreTrueAction.self,
"_StoreFalseAction.Type": _StoreFalseAction.self,
"_AppendAction.Type": _AppendAction.self,
"_AppendConstAction.Type": _AppendConstAction.self,
"_CountAction.Type": _CountAction.self,
"_HelpAction.Type": _HelpAction.self,
"_VersionAction.Type": _VersionAction.self,
"_SubParsersAction.Type": _SubParsersAction.self,
]
func isAction(_ actionName: String) -> Bool {
return _ACTIONS_DICTIONARY.hasKey(actionName)
}
func getAction(_ actionName: String, _ kwargs: Dictionary<String, Any>) -> Action {
switch actionName {
case "_StoreAction.Type":
return _StoreAction(kwargs)
case "_StoreConstAction.Type":
return _StoreConstAction(kwargs)
// case "_StoreTrueAction.Type":
// action = _StoreTrueAction(kwargs)
// case "_StoreFalseAction.Type":
// action = _StoreFalseAction(kwargs)
// case "_AppendAction.Type":
// action = _AppendAction(kwargs)
// case "_AppendConstAction.Type":
// action = _AppendConstAction(kwargs)
// case "_CountAction.Type":
// action = _CountAction(kwargs)
case "_HelpAction.Type":
return _HelpAction(kwargs)
// case "_VersionAction.Type":
// action = _VersionAction(kwargs)
// case "_SubParsersAction.Type":
// action = _SubParsersAction(kwargs)
default:
return Action()
}
}
class Action: _AttributeHolder, Hashable, Equatable {
var __dict__: Dictionary<String, Any?>
var container: _ActionsContainer=_ActionsContainer()
var required: Bool=false
var option_strings: [String] {
get {
if let option_strings = self.__dict__["option_strings"] as? [String] {
return option_strings
} else {
return []
}
}
set {
self.__dict__.updateValue(newValue, forKey: "option_strings")
}
}
var dest: String? {
get {
return self.__dict__["dest"] as! String?
}
set {
self.__dict__.updateValue(newValue, forKey: "dest")
}
}
var nargs: Any? {
get {
return self.__dict__["nargs"] as Any
}
set {
self.__dict__.updateValue(newValue, forKey: "nargs")
}
}
var `const`: Any? {
get {
return self.__dict__["const"] as Any
}
set {
self.__dict__.updateValue(newValue, forKey: "const")
}
}
var `default`: Any? {
get {
return self.__dict__["default"] as Any
}
set {
self.__dict__.updateValue(newValue, forKey: "default")
}
}
var type: Any.Type? {
get {
return self.__dict__["type"] as! Any.Type?
}
set {
self.__dict__.updateValue(newValue, forKey: "type")
}
}
var choices: [Any] {
get {
if let option_strings = self.__dict__["choices"] as? [Any] {
return option_strings
} else {
return []
}
}
set {
self.__dict__.updateValue(newValue, forKey: "choices")
}
}
var help: String {
get {
if let help = self.__dict__["help"] as? String {
return help
} else {
return ""
}
}
set {
self.__dict__.updateValue(newValue, forKey: "help")
}
}
var metavar: String? {
get {
return self.__dict__["metavar"] as! String?
}
set {
self.__dict__.updateValue(newValue, forKey: "metavar")
}
}
init() { self.__dict__ = [:] }
init(option_strings: Array<String>,
dest: String,
nargs: String?=nil,
`const`: Any?=nil,
`default`: Any?=nil,
type: Any.Type?=nil,
choices: Array<Any>=[],
required: Bool=false,
help: String=String.None,
metavar: String=String.None
) {
self.__dict__ = [:]
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.`const` = `const`
self.`default` = `default`
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
}
func _get_kwargs() -> [Attribute] {
let names = [
"option_strings",
"dest",
"nargs",
"const",
"default",
"type",
"choices",
"help",
"metavar",
]
return names.map { ($0, self.__dict__[$0]) }
}
func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) {
fatalError("\(type(of: self)).__call__() not defined")
}
var hashValue: Int {
return self.dest!.hashValue
}
static func == (lhs: Action, rhs: Action) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
class _StoreAction: Action {
init(_ kwargs: Dictionary<String, Any>) {
if let nargsStr = kwargs["nargs"] as! String? {
if let nargNum = Int(nargsStr) {
if nargNum == 0 {
fatalError("nargs for store actions must be > 0; if you have nothing to store, actions such as store true or store const may be more appropriate")
}
}
}
if let constStr = kwargs["const"] as! String? {
if !constStr.isEmpty && (kwargs["nargs"] as! String) != OPTIONAL {
fatalError("nargs must be \"\(OPTIONAL)\" to supply const")
}
}
super.init(option_strings: kwargs["option_strings"] as! Array<String>,
dest: kwargs["dest"] as! String,
nargs: kwargs["nargs"] as! String?,
const: kwargs.hasKey("const") ? kwargs["const"] as! String : String.None,
default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None,
type: kwargs["type"] as? Any.Type,
required: kwargs.hasKey("required") ? kwargs["required"] as! Bool : false,
help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None,
metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None)
}
override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) {
// setattr(namespace, self.dest, values)
}
}
class _StoreConstAction: Action {
init(_ kwargs: Dictionary<String, Any>) {
super.init(option_strings: kwargs["option_strings"] as! Array<String>,
dest: kwargs["dest"] as! String,
nargs: "0",
const: kwargs["const"] as! String,
default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None,
help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None,
metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None)
}
override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) {
}
}
class _StoreTrueAction: Action {
}
class _StoreFalseAction: Action {
}
class _AppendAction: Action {
}
class _AppendConstAction: Action {
}
class _CountAction: Action {
}
class _HelpAction: Action {
init(_ kwargs: Dictionary<String, Any>) {
super.init(option_strings: kwargs["option_strings"] as! Array<String>,
dest: kwargs.hasKey("dest") ? kwargs["dest"] as! String : SUPPRESS,
nargs: "0",
default: kwargs.hasKey("default") ? kwargs["default"] as! String : SUPPRESS,
help: kwargs["help"] as! String)
}
override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) {
}
}
class _VersionAction: Action {
}
class _SubParsersAction: Action {
}
// MARK:- Type classes
class FileType {
init() {
}
}
// MARK:- Optional and Positional Parsing
class Namespace: _AttributeHolder {
var __dict__: Dictionary<String, Any?>
init(_ kwargs: Dictionary<String, Any?>=[:]) {
self.__dict__ = [:]
for item in kwargs {
self.__dict__.updateValue(item.value, forKey: item.key)
}
}
}
class _ActionsContainer {
var _get_formatter_enable: Bool { get { return false } }
var description: String? = nil
var prefix_chars: String = "-"
var `default`: String? = nil
var conflict_handler: String = String.None
var _defaults: Dictionary<String, Any> = [:]
var _registries: Dictionary<String, Dictionary<String, String>> = [:]
var _actions: Array<Action> = []
var _option_string_actions: Dictionary<String, Action> = [:]
var _action_groups: Array<_ArgumentGroup> = []
var _mutually_exclusive_groups: Array<_ArgumentGroup> = []
var _negative_number_matcher: RegexHelper = RegexHelper(String.None)
var _has_negative_number_optionals: Array<Any> = []
static let _CONFLICT_HANDLER = [
"_handle_conflict_error" : _handle_conflict_error,
"_handle_conflict_resolve" : _handle_conflict_resolve,
]
init() {
}
init(description: String?,
prefix_chars: String,
`default`: String?,
conflict_handler: String) {
self.description = description
self.`default` = `default`
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
// set up registries
self._registries = [:]
// register actions
self.register(registry_name: "action", value: String.None, object: "_StoreAction.Type")
self.register(registry_name: "action", value: "store", object: "_StoreAction.Type")
self.register(registry_name: "action", value: "store_const", object: "_StoreConstAction.Type")
self.register(registry_name: "action", value: "store_true", object: "_StoreTrueAction.Type")
self.register(registry_name: "action", value: "store_false", object: "_StoreFalseAction.Type")
self.register(registry_name: "action", value: "append", object: "_AppendAction.Type")
self.register(registry_name: "action", value: "append_const", object: "_AppendConstAction.Type")
self.register(registry_name: "action", value: "count", object: "_CountAction.Type")
self.register(registry_name: "action", value: "help", object: "_HelpAction.Type")
self.register(registry_name: "action", value: "version", object: "_VersionAction.Type")
self.register(registry_name: "action", value: "parsers", object: "_SubParsersAction.Type")
// raise an exception if the conflict handler is invalid
self._get_handler()
// action storage
self._actions = []
self._option_string_actions = [:]
// groups
self._action_groups = []
self._mutually_exclusive_groups = []
// defaults storage
self._defaults = [:]
// determines whether an "option" looks like a negative number
self._negative_number_matcher = RegexHelper("^-\\d+$|^-\\d*\\.\\d+$")
// whether or not there are any optionals that look like negative
// numbers -- uses a list so it can be shared and edited
self._has_negative_number_optionals = []
}
// MARK: Registration methods
func register(registry_name: String, value: String, object: String) -> Void {
self._registries.setdefault(forKey: registry_name, [:])
self._registries[registry_name]?.updateValue(object, forKey: value)
}
func _registry_get(registry_name: String, value: String, `default`: String=String.None) -> String {
return self._registries[registry_name]!.get(forKey: value, default: `default`)
}
// MARK: Namespace default accessor methods
func set_defaultsset_defaults(_ kwargs: Dictionary<String, Any>){
}
func get_default() -> Any {
return ""
}
// MARK: Adding argument actions
func add_argument(_ args: String..., kwargs: Dictionary<String, Any>=[:]) -> Action {
// if no positional args are supplied or only one is supplied and
// it doesn't look like an option string, parse a positional argument
let chars = self.prefix_chars
var kwargs = kwargs
if args.isEmpty || args.count == 1 && !chars.contains(args[0][0]){
if !args.isEmpty && kwargs.hasKey("dest") {
fatalError("dest supplied twice for positional argument")
}
kwargs = self._get_positional_kwargs(dest: args.first!, kwargs: kwargs)
} else {
kwargs = self._get_optional_kwargs(args: args, kwargs: kwargs)
}
// otherwise, we're adding an optional argument
if !kwargs.hasKey("default") {
let dest = kwargs["dest"] as! String
if self._defaults.keys.contains(dest) {
kwargs["default"] = self._defaults[dest]
} else if let deft = self.`default` {
kwargs["default"] = deft
}
}
// create the action object, and add it to the parser
let actionName = self._pop_action_class(kwargs: kwargs)
if !isAction(actionName) {
fatalError("unknown action \"\(actionName)\"")
}
let action = getAction(actionName, kwargs)
// raise an error if the metavar does not match the type
let type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))")
// todo
// if not callable(type_func) {
// fatalError("\(actionName) is not callable")
// }
// raise an error if the metavar does not match the type
if self._get_formatter_enable {
self._get_formatter()._format_args(action, String.None)
// todo
// catch TypeError
// fatalError("length of metavar tuple does not match nargs")
}
return self._add_action(action)
}
func add_argument_group(args: String..., kwargs: Dictionary<String, Any>=[:]) -> _ArgumentGroup {
let title = (args.count > 0) ? args.first : String.None
let description = (args.count > 1) ? args[1] : String.None
let group = _ArgumentGroup(container: self, title: title!, description: description, kwargs: kwargs)
self._action_groups.append(group)
return group
}
func add_mutually_exclusive_group() -> Void {
}
func _add_action(_ action: Action) -> Action {
// resolve any conflicts
self._check_conflict(action)
// add to actions list
self._actions.append(action)
action.container = self
// index the action by any option strings it has
for option_string in action.option_strings {
self._option_string_actions[option_string] = action
}
// set the flag if any option strings look like negative numbers
for option_string in action.option_strings {
if self._negative_number_matcher.match(option_string) {
if !self._has_negative_number_optionals.isEmpty {
self._has_negative_number_optionals.append(true)
}
}
}
// return the created action
return action
}
func _get_handler() -> String {
let handler_func_name = "_handle_conflict_\(self.conflict_handler)"
if _ActionsContainer._CONFLICT_HANDLER.hasKey(handler_func_name) {
return handler_func_name
} else {
fatalError("invalid conflict_resolution value: \(handler_func_name)")
}
}
func _check_conflict(_ action: Action) {
// find all options that conflict with this option
var confl_optionals: Array<(String, Action)> = []
for option_string in action.option_strings {
if self._option_string_actions.hasKey(option_string) {
let confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional!))
}
}
// resolve any conflicts
if !confl_optionals.isEmpty {
let conflict_handler_func_name = self._get_handler()
self._do_conflict_handle(conflict_handler_func_name, action, confl_optionals)
}
}
func _handle_conflict_error(_ action: Action, _ conflicting_actions: Array<(String, Action)>) {
var message = ""
// todo
", ".join(conflicting_actions)
// todo: ArgumentError
fatalError(message)
}
func _handle_conflict_resolve(_ action: Action, _ confl_optionals: Array<(String, Action)>) {
}
func _do_conflict_handle(_ conflict_handler_func_name: String, _ action: Action, _ confl_optionals: Array<(String, Action)>) {
switch conflict_handler_func_name {
case "_handle_conflict_error":
self._handle_conflict_error(action, confl_optionals)
break
case "_handle_conflict_resolve":
self._handle_conflict_resolve(action, confl_optionals)
break
default:
break
}
}
func _add_container_actions(_ container: _ActionsContainer) -> Void {
}
func _get_positional_kwargs(dest: String, kwargs: Dictionary<String, Any>)
-> Dictionary<String, Any> {
var kwargs = kwargs
if kwargs.hasKey("required") {
fatalError("'required' is an invalid argument for positionals")
}
if ![OPTIONAL, ZERO_OR_MORE].contains(kwargs["nargs"] as! String) {
kwargs["required"] = true
}
if kwargs["nargs"] as! String == ZERO_OR_MORE && !kwargs.keys.contains("default") {
kwargs["required"] = true
}
kwargs["dest"] = dest
kwargs["option_strings"] = []
return kwargs
}
func _get_optional_kwargs(args: Array<String>, kwargs: Dictionary<String, Any>) -> Dictionary<String, Any> {
// determine short and long option strings
var kwargs = kwargs
var option_strings: Array<String> = []
var long_option_strings: Array<String> = []
for option_string in args {
// error on strings that don't start with an appropriate prefix
if !self.prefix_chars.contains(option_string[0]) {
fatalError("invalid option string \(option_string): must start with a character \(self.prefix_chars)")
}
// strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string.lengthOfBytes(using: String.Encoding.utf8) > 1 &&
self.prefix_chars.contains(option_string[1]) {
long_option_strings.append(option_string)
}
}
// infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
var dest:String = String.None
if kwargs.hasKey("dest") {
dest = kwargs["dest"] as! String
}
if dest.isEmpty {
var dest_option_string:String
if !long_option_strings.isEmpty {
dest_option_string = long_option_strings.first!
} else {
dest_option_string = option_strings.first!
}
dest = dest_option_string.lstrip(inStr: self.prefix_chars)
if dest.isEmpty {
fatalError("dest: is required for options like \(option_strings)")
}
dest = dest.replacingOccurrences(of: "-", with: "_")
}
// return the updated keyword arguments
kwargs["dest"] = dest
kwargs["option_strings"] = option_strings
return kwargs
}
func _pop_action_class(kwargs: Dictionary<String, Any>, _ `default`: String=String.None) -> String {
var kwargs = kwargs
let action = kwargs.pop(forKey: "action", `default`) as! String
return self._registry_get(registry_name: "action", value: action, default: action)
}
func _get_formatter() -> HelpFormatter {
fatalError("_get_formatter() not implemented in \(Mirror(reflecting: self).subjectType))")
}
}
class _ArgumentGroup: _ActionsContainer {
var title: String = String.None
var _group_actions: Array<Action.Type> = []
override init() {
super.init()
}
init(container: _ActionsContainer, title: String=String.None, description: String=String.None, kwargs: Dictionary<String, Any>) {
var kwargs = kwargs
// add any missing keyword arguments by checking the container
kwargs.setdefault(forKey: "conflict_handler", container.conflict_handler)
kwargs.setdefault(forKey: "prefix_chars", container.prefix_chars)
kwargs.setdefault(forKey: "default", container.`default`)
super.init(description: description, prefix_chars: kwargs["prefix_chars"] as! String, default: kwargs["default"] as? String, conflict_handler: kwargs["conflict_handler"] as! String)
// group attributes
self.title = title
self._group_actions = []
// share most attributes with the container
self._registries = container._registries
self._actions = container._actions
self._option_string_actions = container._option_string_actions
self._defaults = container._defaults
self._has_negative_number_optionals = container._has_negative_number_optionals
self._mutually_exclusive_groups = container._mutually_exclusive_groups
}
}
class _MutuallyExclusiveGroup: _ArgumentGroup {
}
class ArgumentParser: _ActionsContainer, _AttributeHolder {
var __dict__: Dictionary<String, Any?>
override var _get_formatter_enable: Bool { get { return true } }
var allow_abbrev: Bool=true
var epilog: String?
var fromfile_prefix_chars: String?=nil
var _positionals: _ArgumentGroup=_ArgumentGroup()
var _optionals: _ArgumentGroup=_ArgumentGroup()
var _subparsers: _ArgumentGroup?
var prog: String? {
get {
return self.__dict__["prog"] as! String?
}
set {
self.__dict__.updateValue(newValue, forKey: "prog")
}
}
var formatter_class: HelpFormatter.Type {
get {
if let formatter_class = self.__dict__["formatter_class"] as? HelpFormatter.Type {
return formatter_class
} else {
return HelpFormatter.self
}
}
set {
self.__dict__.updateValue(newValue, forKey: "formatter_class")
}
}
var add_help: Bool {
get {
if let add_help = self.__dict__["add_help"] as? Bool {
return add_help
} else {
return true
}
}
set {
self.__dict__.updateValue(newValue, forKey: "add_help")
}
}
var usage: String? {
get {
return self.__dict__["usage"] as! String?
}
set {
self.__dict__.updateValue(newValue, forKey: "usage")
}
}
override var description: String? {
get {
return self.__dict__["description"] as! String?
}
set {
self.__dict__.updateValue(newValue, forKey: "description")
}
}
override var conflict_handler: String {
get {
if let conflict_handler = self.__dict__["conflict_handler"] as? String {
return conflict_handler
} else {
return "error"
}
}
set {
self.__dict__.updateValue(newValue, forKey: "conflict_handler")
}
}
init(prog: String? = nil,
usage: String? = nil,
description: String? = nil,
epilog: String? = nil,
parents: Array<_ActionsContainer>=[],
formatter_class: HelpFormatter.Type = HelpFormatter.self,
prefix_chars: String = "-",
fromfile_prefix_chars: String? = nil,
`default`: String? = nil,
conflict_handler: String = "error",
add_help: Bool=true,
allow_abbrev: Bool=true) {
self.__dict__ = [:]
super.init(description: description, prefix_chars: prefix_chars,
default: `default`, conflict_handler: conflict_handler)
// default setting for prog
if let _ = prog {
self.prog = prog
} else {
// todo: path.basename
self.prog = CommandLine.arguments[0]
}
self.usage = usage
self.epilog = epilog
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
self.allow_abbrev = allow_abbrev
self._positionals = self.add_argument_group(args: "positional arguments")
self._optionals = self.add_argument_group(args: "optional arguments")
self._subparsers = nil
// register types
class identity: Action {
}
self.register(registry_name: "type", value: String.None, object: "identity.self")
// add help argument if necessary
// (using explicit default to override global default)
let default_prefix = prefix_chars.contains("-") ? "-" : prefix_chars[0]
if self.add_help {
self.add_argument(default_prefix+"h", default_prefix+default_prefix+"help",
kwargs: ["action": "help", "default": SUPPRESS,
"help": "show this help message and exit"])
}
// add parent arguments and defaults
for parent in parents {
self._add_container_actions(parent)
// todo
// let defaults = parent._defaults
// self._defaults.update(defaults)
}
}
// MARK: Pretty __repr__ methods
func _get_kwargs() -> [Attribute] {
let names = [
"prog",
"usage",
"description",
"formatter_class",
"conflict_handler",
"add_help",
]
return names.map { ($0, self.__dict__[$0]) }
}
// MARK: Optional/Positional adding methods
func add_subparsers(_ kwargs: Dictionary<String, Any>) -> Action {
return Action()
}
// MARK: Command line argument parsing methods
func parse_args(_ args: Array<String>=[], _ namespace: Dictionary<String, Any>=[:]) -> Dictionary<String, Any> {
let (args, argv) = self.parse_known_args(args: args, namespace: namespace)
if !argv.isEmpty {
fatalError("unrecognized arguments: \(argv.joined(separator: " "))")
}
return args
}
func parse_known_args( args: Array<String>=[], namespace: Dictionary<String, Any>=[:]) -> (Dictionary<String, Any>, Array<String>) {
var namespace = namespace
var args = args
if args.isEmpty {
// args default to the system args
args = Array(CommandLine.arguments.suffix(from: 1))
} else {
// make sure that args are mutable
}
// default Namespace built from parser defaults
// if namespace is None:
// namespace = Namespace()
// add any action defaults that aren't present
for action in self._actions {
if action.dest != SUPPRESS {
// if !hasattr(obj: namespace, name: action.dest) {
if !namespace.hasattr(action.dest!) {
var defaultEqualSUPPRESS = false
if let `default` = action.`default` as? String {
defaultEqualSUPPRESS = (`default` == SUPPRESS)
}
if !defaultEqualSUPPRESS {
namespace.updateValue(action.`default`, forKey: action.dest!)
}
}
}
}
// add any parser defaults that aren't present
for dest in self._defaults.keys {
// if !hasattr(obj: namespace, name: dest) {
if !namespace.hasattr(dest) {
namespace.updateValue(self._defaults[dest], forKey: dest)
}
}
//# parse the arguments and exit if there are any errors
(namespace, args) = self._parse_known_args(arg_strings: args, namespace: namespace)
// if hasattr(obj: namespace, name: _UNRECOGNIZED_ARGS_ATTR) {
if namespace.hasattr(_UNRECOGNIZED_ARGS_ATTR) {
args += namespace[_UNRECOGNIZED_ARGS_ATTR] as! Array<String>
namespace.removeValue(forKey: _UNRECOGNIZED_ARGS_ATTR)
}
return (namespace, args)
}
func _parse_known_args(arg_strings: Array<String>, namespace: Dictionary<String, Any>) -> (Dictionary<String, Any>, Array<String>) {
var arg_strings = arg_strings
// replace arg strings that are file references
if (self.fromfile_prefix_chars != String.None) {
arg_strings = self._read_args_from_files(arg_strings: arg_strings)
}
// map all mutually exclusive arguments to the other arguments
// they can't occur with
var action_conflicts: Dictionary<Action, Any> = [:]
for mutex_group in self._mutually_exclusive_groups {
let group_actions = mutex_group._group_actions
var c = 0
for mutex_action in mutex_group._group_actions {
c += 1
// todo
}
}
// find all option indices, and determine the arg_string_pattern
// which has an 'O' if there is an option at an index,
// an 'A' if there is an argument, or a '-' if there is a '--'
var option_string_indices: Dictionary<Int, Any> = [:]
var arg_string_pattern_parts: Array<String> = []
var i = 0
for arg_string in arg_strings {
// all args after -- are non-options
if arg_string == "--" {
arg_string_pattern_parts.append("-")
for arg_string in arg_strings {
arg_string_pattern_parts.append("A")
}
}
// otherwise, add the arg to the arg strings
// and note the index if it was an option
else {
let option_tuple = self._parse_optional(arg_string)
var pattern: String
if option_tuple.isEmpty {
pattern = "A"
} else {
option_string_indices[i] = option_tuple
pattern = "O"
}
arg_string_pattern_parts.append(pattern)
}
}
// join the pieces together to form the pattern
let arg_strings_pattern = "".join(arg_string_pattern_parts)
// converts arg strings to the appropriate and then takes the action
var seen_actions = Set<Action>()
var seen_non_default_actions = Set<Action>()
func take_action(_ action: Action, _ argument_strings: Array<String>, option_string: String?=nil) {
seen_actions.insert(action)
let argument_values = self._get_values(action, argument_strings)
// error if this argument is not allowed with other previously seen arguments,
// assuming that actions that use the default value don't really count as "present"
if argument_values as! _OptionalNilComparisonType != action.`default` {
seen_non_default_actions.insert(action)
if let actions = action_conflicts[action] {
if let actionArray = actions as? Array<Action> {
for conflict_action in actionArray {
if seen_non_default_actions.contains(conflict_action) {
// raise ArgumentError
fatalError("not allowed with argument \(_get_action_name(conflict_action))")
}
}
}
}
}
// take the action if we didn't receive a SUPPRESS value (e.g. from a default)
var takeAction = true
if let avStr = argument_values as? String {
if avStr == SUPPRESS {
takeAction = false
}
}
if takeAction {
action.__call__(self, namespace, argument_values, option_string)
}
}
return ([:], [])
}
func _read_args_from_files(arg_strings: Array<String>) -> Array<String> {
return arg_strings
}
func convert_arg_line_to_args(_ arg_line: String) -> Array<String> {
return [arg_line]
}
func _match_argument(_ action: Action, _ arg_strings_pattern: String) -> Int {
return 0
}
func _match_arguments_partial(_ action: Action, _ arg_strings_pattern: String) -> Array<String> {
var result: Array<String> = []
return result
}
func _parse_optional(_ arg_string: String) -> Array<Any> {
// if it's an empty string, it was meant to be a positional
if arg_string.isEmpty {
return []
}
// if it doesn't start with a prefix, it was meant to be positional
if !self.prefix_chars.contains(arg_string[0]) {
return []
}
// if the option string is present in the parser, return the action
if self._option_string_actions.hasKey(arg_string) {
let action = self._option_string_actions[arg_string]
return [action, arg_string, String.None]
}
// if it's just a single character, it was meant to be positional
if arg_string.utf8.count == 1 {
return []
}
// if the option string before the "=" is present, return the action
if arg_string.contains("=") {
let splitedStr = arg_string.split("=", 1)
let option_string = splitedStr.first!
let explicit_arg = splitedStr.last!
if self._option_string_actions.hasKey(option_string) {
let action = self._option_string_actions[option_string]
return [action, option_string, explicit_arg]
}
}
if self.allow_abbrev {
// search through all possible prefixes of the option string
// and all actions in the parser for possible interpretations
let option_tuples = self._get_option_tuples(arg_string)
// if multiple actions match, the option string was ambiguous
if option_tuples.count > 1 {
let options = ", ".join(option_tuples.map {"\($0[1] as! String)"})
self.error("ambiguous option: \(arg_string) could match \(options)")
}
// if exactly one action matched, this segmentation is good,
// so return the parsed action
else if option_tuples.count == 1 {
return option_tuples.first!
}
}
// if it was not found as an option, but it looks like a negative
// number, it was meant to be positional
// unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string) {
if self._has_negative_number_optionals.isEmpty {
return []
}
}
// if it contains a space, it was meant to be a positional
if arg_string.contains(" ") {
return []
}
// it was meant to be an optional but there is no such option
// in this parser (though it might be a valid option in a subparser)
return [String.None, arg_string, String.None]
}
func _get_option_tuples(_ option_string: String) -> Array<Array<Any>> {
var result: Array<Array<Any>> = []
// option strings starting with two prefix characters are only split at the '='
let chars = self.prefix_chars
var option_prefix: String
var explicit_arg: String
if chars.contains(option_string[0]) && chars.contains(option_string[1]) {
if option_string.contains("=") {
let arr = option_string.split("=", 1)
option_prefix = arr.first!
explicit_arg = arr.last!
} else {
option_prefix = option_string
explicit_arg = String.None
}
for option_string in self._option_string_actions.keys {
if option_string.hasPrefix(option_prefix) {
let action: Action = self._option_string_actions[option_string]!
let tup: Array<Any> = [action, option_string, explicit_arg]
result.append(tup)
}
}
}
// single character options can be concatenated with their arguments
// but multiple character options always have to have their argument separate
else if chars.contains(option_string[0]) && !chars.contains(option_string[1]) {
option_prefix = option_string
explicit_arg = String.None
let short_option_prefix = option_string.substring(to: 2)
let short_explicit_arg = option_string.substring(from: 2)
for option_string in self._option_string_actions.keys {
if option_string == short_option_prefix {
let action = self._option_string_actions[option_string]
let tup: Array<Any> = [action, option_string, short_explicit_arg]
result.append(tup)
}
else if option_string.hasPrefix(option_prefix) {
let action = self._option_string_actions[option_string]
let tup: Array<Any> = [action, option_string, short_explicit_arg]
result.append(tup)
}
}
}
// shouldn't ever get here
else {
self.error("unexpected option string: \(option_string)")
}
// return the collected option tuples
return result
}
func _get_nargs_pattern(_ action: Action) -> String {
return String.None
}
// MAKR: Value conversion methods
func _get_values(_ action: Action, _ arg_strings: Array<String>) -> Any {
// for everything but PARSER, REMAINDER args, strip out first '--'
var arg_strings = arg_strings
var needRemove = true
if let nargs = action.nargs as? String {
if [PARSER, REMAINDER].contains(nargs) {
needRemove = false
}
}
if needRemove {
// arg_strings.remove("--")
var index = arg_strings.count - 1
while index >= 0 {
if "--" == arg_strings[index] {
arg_strings.remove(at: index)
}
index -= 1
}
}
// optional argument produces a default when not present
var value: Any?
var otherType = true // all other types of nargs produce a list
if let nargs = action.nargs as? String {
otherType = false
if arg_strings.isEmpty && nargs == OPTIONAL {
if action.option_strings.isEmpty {
value = action.`const`
} else {
value = action.`default`
}
if let valueStr = value as? String {
value = self._get_value(action, valueStr)
self._check_value(action, value)
}
}
// when nargs='*' on a positional, if there were no command-line
// args, use the default if it is anything other than None
else if arg_strings.isEmpty && nargs == ZERO_OR_MORE && action.option_strings.isEmpty {
if (action.`default` != nil) {
value = action.`default`
} else {
value = arg_strings
}
self._check_value(action, value)
}
// single argument or optional argument produces a single value
else if arg_strings.count == 1 && nargs == OPTIONAL {
let arg_string = arg_strings.first
value = self._get_value(action, arg_string!)
self._check_value(action, value)
}
// REMAINDER arguments convert all values, checking none
else if nargs == REMAINDER {
value = arg_strings.map {self._get_value(action, $0)}
}
// PARSER arguments convert all values, but check only the first
else if nargs == PARSER {
value = arg_strings.map {self._get_value(action, $0)}
self._check_value(action, (value as! Array<Any>).first)
}
else {
otherType = true
}
}
// single argument or optional argument produces a single value
if arg_strings.count == 1 && action.nargs == nil {
let arg_string = arg_strings.first
value = self._get_value(action, arg_string!)
self._check_value(action, value)
otherType = false
}
// all other types of nargs produce a list
if otherType {
value = arg_strings.map {self._get_value(action, $0)}
for v in value as! Array<Any> {
self._check_value(action, v)
}
}
// return the converted value
return value
}
func _get_value(_ action: Action, _ arg_string: String) -> Any {
var type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))")
// todo
// check if type_func callable
// convert the value to the appropriate type
// todo
// ArgumentTypeErrors indicate errors
// TypeErrors or ValueErrors also indicate errors
// return the converted value
return arg_string
}
func _check_value(_ action: Action, _ value: Any) {
// converted value must be one of the choices (if specified)
// if !action.choices.isEmpty && !action.choices.contains(where: value as! (Any) throws -> Bool) {
if false {
fatalError("invalid choice: \(value) (choose from \(action.choices))")
}
}
// MARK: Help-formatting methods
func format_usage() -> String {
return ""
}
func format_help() -> String {
return ""
}
override func _get_formatter() -> HelpFormatter {
return self.formatter_class.init(self.prog!, -1, -1, -1)
}
// MARK: Help-printing methods
func print_usage() {
}
func print_help() {
}
func _print_message() {
}
// MARK: Exiting methods
func exit(_ status: Int=0, _ message: String=String.None) {
if !message.isEmpty {
}
}
func error(_ message: String) {
}
}
|
unlicense
|
49f63731d52c228a7980c092f749248d
| 31.542857 | 189 | 0.553468 | 4.187808 | false | false | false | false |
kujenga/euler
|
lib/swift/Euler/Sources/Euler/Euler.swift
|
1
|
1195
|
import Foundation
// Helper functions on the Int type.
extension Int {
// Check if a number is prime, efficiently.
public func isPrime() -> Bool {
if self == 2 || self == 3 {
return true;
}
if self <= 1 || self % 2 == 0 || self % 3 == 0 {
return false;
}
var i = 5;
while i * i <= self {
if self % i == 0 || self % (i + 2) == 0 {
return false;
}
i += 6;
}
return true;
}
}
// Helper to allow for exponentiation on integers directly. Required because
// Decimal cannot cast directly to Int.
public func pow(_ base: Int, _ power: Int) -> Int {
// Call into Foundation function.
let r = pow(Decimal(base), power)
return NSDecimalNumber(decimal: r).intValue;
}
public func digitsToInt(_ digits: [Int], base: Int = 10) -> Int {
digitsToInt(digits[...], base: base)
}
// Converts an array of base 10 digits into an Int.
public func digitsToInt(_ digits: ArraySlice<Int>, base: Int = 10) -> Int {
var v = 0;
for (index, digit) in digits.reversed().enumerated() {
v += digit * pow(base, index)
}
return v;
}
|
gpl-3.0
|
f58002fbc7086b09947aeb6fed4b6f58
| 26.790698 | 76 | 0.543933 | 3.87987 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Public/SMSyncServerTypes.swift
|
1
|
13609
|
//
// SMSyncServerTypes.swift
// SMSyncServer
//
// Created by Christopher Prince on 2/26/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
// Misc public utility types for SMSyncServer
import Foundation
import SMCoreLib
public typealias SMInternalUserId = String
// Modified from http://www.swift-studies.com/blog/2015/6/17/exploring-swift-20-optionsettypes
public struct SMSharingUserCapabilityMask : OptionSetType {
private enum UserCapability : Int, CustomStringConvertible {
case Create /* Objects */ = 1
case Read /* Objects */ = 2
case Update /* Objects */ = 4
case Delete /* Objects */ = 8
case Invite /* New users to share */ = 16
// Upload-- Create for new versions of files; Update for existing versions.
// Download-- Read
// Invite-- Other users to share
// Delete-- delete files
private init?(capabilityName: String) {
var rawValue = 1
for name in UserCapability.allAsStrings {
if name == capabilityName {
self = UserCapability(rawValue: rawValue)!
return
}
rawValue = rawValue << 1
}
Log.error("Unknown capabilityName: \(capabilityName)")
return nil
}
private static var allAsStrings:[String] {
// We depend here on the ordering and values of elements in the following array!
return SMServerConstants.possibleUserCapabilityValues
}
private var description : String {
return SMMaskUtilities.enumDescription(rawValue: self.rawValue, allAsStrings: UserCapability.allAsStrings)
}
}
public let rawValue : Int
public init(rawValue:Int){ self.rawValue = rawValue}
private init(_ enumValue:UserCapability) {
self.rawValue = enumValue.rawValue
}
public init?(capabilityNameArray:[String]) {
var mask = SMSharingUserCapabilityMask()
for capabilityName in capabilityNameArray {
if let capabilityEnum = UserCapability(capabilityName: capabilityName) {
mask.insert(SMSharingUserCapabilityMask(capabilityEnum))
}
else {
return nil
}
}
self = mask
}
public static let Create = SMSharingUserCapabilityMask(.Create)
public static let Read = SMSharingUserCapabilityMask(.Read)
public static let Update = SMSharingUserCapabilityMask(.Update)
public static let Delete = SMSharingUserCapabilityMask(.Delete)
public static let CRUD:SMSharingUserCapabilityMask = [.Create, .Read, .Update, .Delete]
public static let Invite = SMSharingUserCapabilityMask(UserCapability.Invite)
public static let ALL:SMSharingUserCapabilityMask = [.CRUD, .Invite]
public var description : String {
return SMMaskUtilities.maskDescription(stringArray: self.stringArray)
}
// An array of capability strings, possibly empty.
public var stringArray: [String] {
return SMMaskUtilities.maskArrayOfStrings(self) { (maskObj:SMSharingUserCapabilityMask, enumValue:UserCapability) -> Bool in
return maskObj.contains(SMSharingUserCapabilityMask(enumValue))
}
}
}
public enum SMSyncClientAPIError: ErrorType {
case BadAutoCommitInterval
case CouldNotCreateTemporaryFile
case CouldNotWriteToTemporaryFile
case MimeTypeNotGiven
case RemoteFileNameNotGiven
case DifferentRemoteFileNameThanOnServer
case FileWasAlreadyDeleted(specificLocation: String)
case DeletingUnknownFile
case UserNotSignedIn
}
public typealias SMAppMetaData = [String:AnyObject]
// Attributes for a data object being synced.
public class SMSyncAttributes {
// The identifier for the file/data item.
public var uuid:NSUUID!
// Must be provided when uploading for a new uuid. (If you give a remoteFileName for an existing uuid it *must* match that already present in cloud storage). Will be provided when a file is downloaded from the server.
public var remoteFileName:String?
// Must be provided when uploading for a new uuid; optional after that. The mimeType of an uploaded object must be consistent across its lifetime.
public var mimeType:String?
// When uploading or downloading, optionally provides the app with app-specific meta information about the object. This must be encodable to JSON for upload/download to the server. This is stored on the SMSyncServer server (not the users cloud storage), so you may want to be careful about not making this too large. On each upload, you can alter this.
public var appMetaData:SMAppMetaData?
// Only used by SMSyncServer fileStatus method. true indicates that the file was deleted on the server.
public var deleted:Bool?
// TODO: An optional app-specific identifier for a logical group or category that the file/data item belongs to. The intent behind this identifier is to make downloading logical groups of files easier. E.g., so that not all changed files need to be downloaded at once.
//public var appGroupId:NSUUID?
public init(withUUID id:NSUUID) {
self.uuid = id
}
public init(withUUID theUUID:NSUUID, mimeType theMimeType:String, andRemoteFileName theRemoteFileName:String) {
self.mimeType = theMimeType
self.uuid = theUUID
self.remoteFileName = theRemoteFileName
}
}
// MARK: Events
public enum SMSyncServerEvent {
// Deletion operations have been sent to the SyncServer. All pending deletion operations are sent as a group. Deletion of the file from cloud storage hasn't yet occurred.
case DeletionsSent(uuids:[NSUUID])
// A single file/item has been uploaded to the SyncServer. Transfer of the file to cloud storage hasn't yet occurred.
case SingleUploadComplete(uuid:NSUUID)
// This was introduced to allow for a specific test case internally.
case FrameworkUploadMetaDataUpdated
// Server has finished performing the outbound transfers of files to cloud storage/deletions to cloud storage. numberOperations is a heuristic value that includes upload and upload-deletion operations. It is heuristic in that it includes retries if retries occurred due to error/recovery handling. We used to call this the "committed" or "CommitComplete" event because the SMSyncServer commit operation is done at this point.
case AllUploadsComplete(numberOperations:Int?)
// Similarly, for inbound transfers of files from cloud storage to the sync server. The numberOperations value has the same heuristic meaning.
case InboundTransferComplete(numberOperations:Int?)
// As said elsewhere, this information is for debugging/testing. The url/attr here may not be consistent with the atomic/transaction-maintained results from syncServerDownloadsComplete in the SMSyncServerDelegate method. (Because of possible recovery steps).
case SingleDownloadComplete(url:SMRelativeLocalURL, attr:SMSyncAttributes)
// Called at the end of a download when one or more files were downloaded, or at the end of a check for downloads if no downloads were performed.
case DownloadsFinished
// Commit was called, but there were no files to upload and no upload-deletions to send to the server.
case NoFilesToUpload
// Attempted to do an operation but a lock was already held. This can occur both at the local app level and with the server lock.
case LockAlreadyHeld
// Internal error recovery event.
case Recovery
}
// MARK: Conflict management
// If you receive a non-nil conflict in a callback method, you must resolve the conflict by calling resolveConflict.
public class SMSyncServerConflict {
internal typealias callbackType = ((resolution:ResolutionType)->())!
internal var conflictResolved:Bool = false
internal var resolutionCallback:((resolution:ResolutionType)->())!
internal init(conflictType: ClientOperation, resolutionCallback:callbackType) {
self.conflictType = conflictType
self.resolutionCallback = resolutionCallback
}
// Because downloads are higher-priority (than uploads) with the SMSyncServer, all conflicts effectively originate from a server download operation: A download-deletion or a file-download. The type of server operation will be apparent from the context.
// And the conflict is between the server operation and a local, client operation:
public enum ClientOperation : String {
case UploadDeletion
case FileUpload
}
public var conflictType:ClientOperation!
public enum ResolutionType {
// E.g., suppose a download-deletion and a file-upload (ClientOperation.FileUpload) are conflicting.
// Example continued: The client chooses to delete the conflicting file-upload and accept the download-deletion by using this resolution.
case DeleteConflictingClientOperations
// Example continued: The client chooses to keep the conflicting file-upload, and override the download-deletion, by using this resolution.
case KeepConflictingClientOperations
}
public func resolveConflict(resolution resolution:ResolutionType) {
Assert.If(self.conflictResolved, thenPrintThisString: "Already resolved!")
self.conflictResolved = true
self.resolutionCallback(resolution: resolution)
}
}
public enum SMSyncServerMode {
// The SMSyncServer client is not performing any operation.
case Idle
// SMSyncServer client is performing an operation, e.g., downloading or uploading.
case Synchronizing
// The SMSyncServer resetFromError method was called, asynchronous operation was required, and the process of resetting from an error is occurring.
case ResettingFromError
// This is not an error, but indicates a loss of network connection. Normal operation will resume once the network is connected again.
case NetworkNotConnected
// The modes below are errors that the SMSyncServer couldn't recover from. It's up to the client app to deal with these.
// There was an error that, after internal SMSyncServer recovery attempts, could not be dealt with.
case NonRecoverableError(NSError)
// An error within the SMSyncServer framework. Ooops. Please report this to the SMSyncServer developers!
case InternalError(NSError)
}
public func ==(lhs:SMSyncServerMode, rhs:SMSyncServerMode) -> Bool {
switch lhs {
case .Idle:
switch rhs {
case .Idle: return true
default: return false
}
case .Synchronizing:
switch rhs {
case .Synchronizing: return true
default: return false
}
case .ResettingFromError:
switch rhs {
case .ResettingFromError: return true
default: return false
}
case .NetworkNotConnected:
switch rhs {
case .NetworkNotConnected: return true
default: return false
}
case .NonRecoverableError:
switch rhs {
case .NonRecoverableError: return true
default: return false
}
case .InternalError:
switch rhs {
case .InternalError: return true
default: return false
}
}
}
internal class SMSyncServerModeWrapper : NSObject, NSCoding
{
var mode:SMSyncServerMode
init(withMode mode:SMSyncServerMode) {
self.mode = mode
super.init()
}
@objc required init(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey("name") as! String
switch name {
case "Idle":
self.mode = .Idle
case "Synchronizing":
self.mode = .Synchronizing
case "ResettingFromError":
self.mode = .ResettingFromError
case "NetworkNotConnected":
self.mode = .NetworkNotConnected
case "NonRecoverableError":
let error = aDecoder.decodeObjectForKey("error") as! NSError
self.mode = .NonRecoverableError(error)
case "InternalError":
let error = aDecoder.decodeObjectForKey("error") as! NSError
self.mode = .InternalError(error)
default:
Assert.badMojo(alwaysPrintThisString: "Should not get here")
self.mode = .Idle // Without this, get compiler error.
}
super.init()
}
@objc func encodeWithCoder(aCoder: NSCoder) {
var name:String!
var error:NSError?
switch self.mode {
case .Idle:
name = "Idle"
case .Synchronizing:
name = "Synchronizing"
case .ResettingFromError:
name = "ResettingFromError"
case .NetworkNotConnected:
name = "NetworkNotConnected"
case .NonRecoverableError(let err):
name = "NonRecoverableError"
error = err
case .InternalError(let err):
name = "InternalError"
error = err
}
aCoder.encodeObject(name, forKey: "name")
if error != nil {
aCoder.encodeObject(error, forKey: "error")
}
}
}
|
gpl-3.0
|
b115134eb075ccdf71613514ae74eca8
| 38.103448 | 429 | 0.673942 | 5.127355 | false | false | false | false |
jdbateman/Lendivine
|
Lendivine/KivaRepayment.swift
|
1
|
1241
|
//
// KivaRepayment.swift
// Lendivine
//
// Created by john bateman on 4/28/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This model class describes information about the future repayment schedule for all Kiva Loans associated with a Kiva account.
import Foundation
class KivaRepayment {
var userRepayments: String = ""
var promoRepayments: String = ""
var loansMakingRepayments: String = ""
var repaymentDate: String = ""
var repaymentId: String = ""
// designated initializer
init(key:String, dictionary: [String: AnyObject]?) {
if let dictionary = dictionary {
repaymentId = key
if let repayments = dictionary["user_repayments"] as? String {
userRepayments = repayments
}
if let promo = dictionary["promo_repayments"] as? String {
promoRepayments = promo
}
if let numloans = dictionary["loans_making_repayments"] as? String {
loansMakingRepayments = numloans
}
if let date = dictionary["repayment_date"] as? String {
repaymentDate = date
}
}
}
}
|
mit
|
e0ac2efb4a5bfa24f632483887e5d24e
| 29.268293 | 129 | 0.583871 | 4.366197 | false | false | false | false |
alobanov/Dribbble
|
Dribbble/helpers/AZText/AZTextFrame.swift
|
1
|
2870
|
import UIKit
class AZTextFrameAttributes: NSObject {
// MARK: - Properties
fileprivate(set) var width: CGFloat = 0
fileprivate(set) var string: String?
fileprivate(set) var attributedString: NSAttributedString?
// MARK: - Attributes
var attributes: [String: AnyObject] = [:]
var lineBreakingMode: NSLineBreakMode = NSLineBreakMode.byWordWrapping {
didSet {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = lineBreakingMode
attributes[NSParagraphStyleAttributeName] = paragraph
}
}
// MARK: - Init
init(string: String, font: UIFont) {
self.string = string
self.attributes = [NSFontAttributeName: font]
}
init(string: String, width: CGFloat, font: UIFont) {
self.string = string
self.width = width
self.attributes = [NSFontAttributeName: font]
}
init(attributedString: NSAttributedString) {
self.attributedString = attributedString
}
init(attributedString: NSAttributedString, width: CGFloat) {
self.attributedString = attributedString
self.width = width
}
// MARK: - Calculation
func calculatedTextWidth() -> CGFloat {
return AZTextFrame(attributes: self).width
}
func calculatedTextHeight() -> CGFloat {
return AZTextFrame(attributes: self).height
}
}
class AZTextFrame: NSObject {
// MARK: - Properties
let attributes: AZTextFrameAttributes
fileprivate(set) var width: CGFloat = 0
fileprivate(set) var height: CGFloat = 0
// MARK: - Init
init(attributes: AZTextFrameAttributes) {
self.attributes = attributes
super.init()
self.calculate()
}
private func calculate() {
let sizeForHeight = CGSize(width: attributes.width, height: CGFloat.greatestFiniteMagnitude / 2)
let sizeForWidth = CGSize(width: CGFloat.greatestFiniteMagnitude / 2, height: CGFloat.greatestFiniteMagnitude / 2)
if let string = attributes.string {
height = (string as NSString).boundingRect(with: sizeForHeight, options: .usesLineFragmentOrigin, attributes: attributes.attributes, context: nil).height
width = (string as NSString).boundingRect(with: sizeForWidth, options: .usesLineFragmentOrigin, attributes: attributes.attributes, context: nil).width
} else if let attributedString = attributes.attributedString {
height = attributedString.boundingRect(with: sizeForHeight, options: .usesLineFragmentOrigin, context: nil).height
width = attributedString.boundingRect(with: sizeForWidth, options: .usesLineFragmentOrigin, context: nil).width
}
height = roundTillHalf(value: height)
width = roundTillHalf(value: width)
}
private func roundTillHalf(value: CGFloat) -> CGFloat {
if value - CGFloat(Int(value)) >= 0.5 {
return CGFloat(Int(value)) + 1
} else {
return CGFloat(Int(value)) + 0.5
}
}
}
|
mit
|
7e50a3a231ac4c8ecbacc0921115935d
| 29.531915 | 159 | 0.704181 | 4.659091 | false | false | false | false |
zerdzhong/LeetCode
|
swift/LeetCode.playground/Pages/9_Palindrome_Number.xcplaygroundpage/Contents.swift
|
1
|
543
|
//: [Previous](@previous)
//https://leetcode.com/problems/palindrome-number/
import Foundation
class Solution {
func isPalindrome(_ x: Int) -> Bool {
if x < 0 || (x != 0 && x % 10 == 0) {
return false
}
var reverse = 0, origin = x
while origin > reverse {
reverse = reverse * 10 + origin % 10
origin = origin / 10
}
return (reverse == origin || origin == reverse / 10)
}
}
Solution().isPalindrome(121)
//: [Next](@next)
|
mit
|
c3e8f6dd7bb144e4d40cb1254bca445f
| 20.72 | 60 | 0.495396 | 4.145038 | false | false | false | false |
WhisperSystems/Signal-iOS
|
SignalServiceKit/src/Devices/OWSDevice+SDS.swift
|
1
|
21331
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
import SignalCoreKit
// NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py.
// Do not manually edit it, instead run `sds_codegen.sh`.
// MARK: - Record
public struct DeviceRecord: SDSRecord {
public var tableMetadata: SDSTableMetadata {
return OWSDeviceSerializer.table
}
public static let databaseTableName: String = OWSDeviceSerializer.table.tableName
public var id: Int64?
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
public let recordType: SDSRecordType
public let uniqueId: String
// Base class properties
public let createdAt: Double
public let deviceId: Int
public let lastSeenAt: Double
public let name: String?
public enum CodingKeys: String, CodingKey, ColumnExpression, CaseIterable {
case id
case recordType
case uniqueId
case createdAt
case deviceId
case lastSeenAt
case name
}
public static func columnName(_ column: DeviceRecord.CodingKeys, fullyQualified: Bool = false) -> String {
return fullyQualified ? "\(databaseTableName).\(column.rawValue)" : column.rawValue
}
}
// MARK: - Row Initializer
public extension DeviceRecord {
static var databaseSelection: [SQLSelectable] {
return CodingKeys.allCases
}
init(row: Row) {
id = row[0]
recordType = row[1]
uniqueId = row[2]
createdAt = row[3]
deviceId = row[4]
lastSeenAt = row[5]
name = row[6]
}
}
// MARK: - StringInterpolation
public extension String.StringInterpolation {
mutating func appendInterpolation(deviceColumn column: DeviceRecord.CodingKeys) {
appendLiteral(DeviceRecord.columnName(column))
}
mutating func appendInterpolation(deviceColumnFullyQualified column: DeviceRecord.CodingKeys) {
appendLiteral(DeviceRecord.columnName(column, fullyQualified: true))
}
}
// MARK: - Deserialization
// TODO: Rework metadata to not include, for example, columns, column indices.
extension OWSDevice {
// This method defines how to deserialize a model, given a
// database row. The recordType column is used to determine
// the corresponding model class.
class func fromRecord(_ record: DeviceRecord) throws -> OWSDevice {
guard let recordId = record.id else {
throw SDSError.invalidValue
}
switch record.recordType {
case .device:
let uniqueId: String = record.uniqueId
let createdAtInterval: Double = record.createdAt
let createdAt: Date = SDSDeserialization.requiredDoubleAsDate(createdAtInterval, name: "createdAt")
let deviceId: Int = record.deviceId
let lastSeenAtInterval: Double = record.lastSeenAt
let lastSeenAt: Date = SDSDeserialization.requiredDoubleAsDate(lastSeenAtInterval, name: "lastSeenAt")
let name: String? = record.name
return OWSDevice(uniqueId: uniqueId,
createdAt: createdAt,
deviceId: deviceId,
lastSeenAt: lastSeenAt,
name: name)
default:
owsFailDebug("Unexpected record type: \(record.recordType)")
throw SDSError.invalidValue
}
}
}
// MARK: - SDSModel
extension OWSDevice: SDSModel {
public var serializer: SDSSerializer {
// Any subclass can be cast to it's superclass,
// so the order of this switch statement matters.
// We need to do a "depth first" search by type.
switch self {
default:
return OWSDeviceSerializer(model: self)
}
}
public func asRecord() throws -> SDSRecord {
return try serializer.asRecord()
}
public var sdsTableName: String {
return DeviceRecord.databaseTableName
}
public static var table: SDSTableMetadata {
return OWSDeviceSerializer.table
}
}
// MARK: - Table Metadata
extension OWSDeviceSerializer {
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
static let idColumn = SDSColumnMetadata(columnName: "id", columnType: .primaryKey, columnIndex: 0)
static let recordTypeColumn = SDSColumnMetadata(columnName: "recordType", columnType: .int64, columnIndex: 1)
static let uniqueIdColumn = SDSColumnMetadata(columnName: "uniqueId", columnType: .unicodeString, isUnique: true, columnIndex: 2)
// Base class properties
static let createdAtColumn = SDSColumnMetadata(columnName: "createdAt", columnType: .double, columnIndex: 3)
static let deviceIdColumn = SDSColumnMetadata(columnName: "deviceId", columnType: .int64, columnIndex: 4)
static let lastSeenAtColumn = SDSColumnMetadata(columnName: "lastSeenAt", columnType: .double, columnIndex: 5)
static let nameColumn = SDSColumnMetadata(columnName: "name", columnType: .unicodeString, isOptional: true, columnIndex: 6)
// TODO: We should decide on a naming convention for
// tables that store models.
public static let table = SDSTableMetadata(collection: OWSDevice.collection(),
tableName: "model_OWSDevice",
columns: [
idColumn,
recordTypeColumn,
uniqueIdColumn,
createdAtColumn,
deviceIdColumn,
lastSeenAtColumn,
nameColumn
])
}
// MARK: - Save/Remove/Update
@objc
public extension OWSDevice {
func anyInsert(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .insert, transaction: transaction)
}
// This method is private; we should never use it directly.
// Instead, use anyUpdate(transaction:block:), so that we
// use the "update with" pattern.
private func anyUpdate(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .update, transaction: transaction)
}
@available(*, deprecated, message: "Use anyInsert() or anyUpdate() instead.")
func anyUpsert(transaction: SDSAnyWriteTransaction) {
let isInserting: Bool
if OWSDevice.anyFetch(uniqueId: uniqueId, transaction: transaction) != nil {
isInserting = false
} else {
isInserting = true
}
sdsSave(saveMode: isInserting ? .insert : .update, transaction: transaction)
}
// This method is used by "updateWith..." methods.
//
// This model may be updated from many threads. We don't want to save
// our local copy (this instance) since it may be out of date. We also
// want to avoid re-saving a model that has been deleted. Therefore, we
// use "updateWith..." methods to:
//
// a) Update a property of this instance.
// b) If a copy of this model exists in the database, load an up-to-date copy,
// and update and save that copy.
// b) If a copy of this model _DOES NOT_ exist in the database, do _NOT_ save
// this local instance.
//
// After "updateWith...":
//
// a) Any copy of this model in the database will have been updated.
// b) The local property on this instance will always have been updated.
// c) Other properties on this instance may be out of date.
//
// All mutable properties of this class have been made read-only to
// prevent accidentally modifying them directly.
//
// This isn't a perfect arrangement, but in practice this will prevent
// data loss and will resolve all known issues.
func anyUpdate(transaction: SDSAnyWriteTransaction, block: (OWSDevice) -> Void) {
block(self)
guard let dbCopy = type(of: self).anyFetch(uniqueId: uniqueId,
transaction: transaction) else {
return
}
// Don't apply the block twice to the same instance.
// It's at least unnecessary and actually wrong for some blocks.
// e.g. `block: { $0 in $0.someField++ }`
if dbCopy !== self {
block(dbCopy)
}
dbCopy.anyUpdate(transaction: transaction)
}
func anyRemove(transaction: SDSAnyWriteTransaction) {
sdsRemove(transaction: transaction)
}
func anyReload(transaction: SDSAnyReadTransaction) {
anyReload(transaction: transaction, ignoreMissing: false)
}
func anyReload(transaction: SDSAnyReadTransaction, ignoreMissing: Bool) {
guard let latestVersion = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else {
if !ignoreMissing {
owsFailDebug("`latest` was unexpectedly nil")
}
return
}
setValuesForKeys(latestVersion.dictionaryValue)
}
}
// MARK: - OWSDeviceCursor
@objc
public class OWSDeviceCursor: NSObject {
private let cursor: RecordCursor<DeviceRecord>?
init(cursor: RecordCursor<DeviceRecord>?) {
self.cursor = cursor
}
public func next() throws -> OWSDevice? {
guard let cursor = cursor else {
return nil
}
guard let record = try cursor.next() else {
return nil
}
return try OWSDevice.fromRecord(record)
}
public func all() throws -> [OWSDevice] {
var result = [OWSDevice]()
while true {
guard let model = try next() else {
break
}
result.append(model)
}
return result
}
}
// MARK: - Obj-C Fetch
// TODO: We may eventually want to define some combination of:
//
// * fetchCursor, fetchOne, fetchAll, etc. (ala GRDB)
// * Optional "where clause" parameters for filtering.
// * Async flavors with completions.
//
// TODO: I've defined flavors that take a read transaction.
// Or we might take a "connection" if we end up having that class.
@objc
public extension OWSDevice {
class func grdbFetchCursor(transaction: GRDBReadTransaction) -> OWSDeviceCursor {
let database = transaction.database
do {
let cursor = try DeviceRecord.fetchCursor(database)
return OWSDeviceCursor(cursor: cursor)
} catch {
owsFailDebug("Read failed: \(error)")
return OWSDeviceCursor(cursor: nil)
}
}
// Fetches a single model by "unique id".
class func anyFetch(uniqueId: String,
transaction: SDSAnyReadTransaction) -> OWSDevice? {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return OWSDevice.ydb_fetch(uniqueId: uniqueId, transaction: ydbTransaction)
case .grdbRead(let grdbTransaction):
let sql = "SELECT * FROM \(DeviceRecord.databaseTableName) WHERE \(deviceColumn: .uniqueId) = ?"
return grdbFetchOne(sql: sql, arguments: [uniqueId], transaction: grdbTransaction)
}
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
block: @escaping (OWSDevice, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerate(transaction: transaction, batched: false, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (OWSDevice, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerate(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (OWSDevice, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
OWSDevice.ydb_enumerateCollectionObjects(with: ydbTransaction) { (object, stop) in
guard let value = object as? OWSDevice else {
owsFailDebug("unexpected object: \(type(of: object))")
return
}
block(value, stop)
}
case .grdbRead(let grdbTransaction):
do {
let cursor = OWSDevice.grdbFetchCursor(transaction: grdbTransaction)
try Batching.loop(batchSize: batchSize,
loopBlock: { stop in
guard let value = try cursor.next() else {
stop.pointee = true
return
}
block(value, stop)
})
} catch let error {
owsFailDebug("Couldn't fetch models: \(error)")
}
}
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerateUniqueIds(transaction: transaction, batched: false, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerateUniqueIds(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
ydbTransaction.enumerateKeys(inCollection: OWSDevice.collection()) { (uniqueId, stop) in
block(uniqueId, stop)
}
case .grdbRead(let grdbTransaction):
grdbEnumerateUniqueIds(transaction: grdbTransaction,
sql: """
SELECT \(deviceColumn: .uniqueId)
FROM \(DeviceRecord.databaseTableName)
""",
batchSize: batchSize,
block: block)
}
}
// Does not order the results.
class func anyFetchAll(transaction: SDSAnyReadTransaction) -> [OWSDevice] {
var result = [OWSDevice]()
anyEnumerate(transaction: transaction) { (model, _) in
result.append(model)
}
return result
}
// Does not order the results.
class func anyAllUniqueIds(transaction: SDSAnyReadTransaction) -> [String] {
var result = [String]()
anyEnumerateUniqueIds(transaction: transaction) { (uniqueId, _) in
result.append(uniqueId)
}
return result
}
class func anyCount(transaction: SDSAnyReadTransaction) -> UInt {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.numberOfKeys(inCollection: OWSDevice.collection())
case .grdbRead(let grdbTransaction):
return DeviceRecord.ows_fetchCount(grdbTransaction.database)
}
}
// WARNING: Do not use this method for any models which do cleanup
// in their anyWillRemove(), anyDidRemove() methods.
class func anyRemoveAllWithoutInstantation(transaction: SDSAnyWriteTransaction) {
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydbTransaction.removeAllObjects(inCollection: OWSDevice.collection())
case .grdbWrite(let grdbTransaction):
do {
try DeviceRecord.deleteAll(grdbTransaction.database)
} catch {
owsFailDebug("deleteAll() failed: \(error)")
}
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyRemoveAllWithInstantation(transaction: SDSAnyWriteTransaction) {
// To avoid mutationDuringEnumerationException, we need
// to remove the instances outside the enumeration.
let uniqueIds = anyAllUniqueIds(transaction: transaction)
var index: Int = 0
do {
try Batching.loop(batchSize: Batching.kDefaultBatchSize,
loopBlock: { stop in
guard index < uniqueIds.count else {
stop.pointee = true
return
}
let uniqueId = uniqueIds[index]
index = index + 1
guard let instance = anyFetch(uniqueId: uniqueId, transaction: transaction) else {
owsFailDebug("Missing instance.")
return
}
instance.anyRemove(transaction: transaction)
})
} catch {
owsFailDebug("Error: \(error)")
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyExists(uniqueId: String,
transaction: SDSAnyReadTransaction) -> Bool {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.hasObject(forKey: uniqueId, inCollection: OWSDevice.collection())
case .grdbRead(let grdbTransaction):
let sql = "SELECT EXISTS ( SELECT 1 FROM \(DeviceRecord.databaseTableName) WHERE \(deviceColumn: .uniqueId) = ? )"
let arguments: StatementArguments = [uniqueId]
return try! Bool.fetchOne(grdbTransaction.database, sql: sql, arguments: arguments) ?? false
}
}
}
// MARK: - Swift Fetch
public extension OWSDevice {
class func grdbFetchCursor(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> OWSDeviceCursor {
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
let cursor = try DeviceRecord.fetchCursor(transaction.database, sqlRequest)
return OWSDeviceCursor(cursor: cursor)
} catch {
Logger.error("sql: \(sql)")
owsFailDebug("Read failed: \(error)")
return OWSDeviceCursor(cursor: nil)
}
}
class func grdbFetchOne(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> OWSDevice? {
assert(sql.count > 0)
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
guard let record = try DeviceRecord.fetchOne(transaction.database, sqlRequest) else {
return nil
}
return try OWSDevice.fromRecord(record)
} catch {
owsFailDebug("error: \(error)")
return nil
}
}
}
// MARK: - SDSSerializer
// The SDSSerializer protocol specifies how to insert and update the
// row that corresponds to this model.
class OWSDeviceSerializer: SDSSerializer {
private let model: OWSDevice
public required init(model: OWSDevice) {
self.model = model
}
// MARK: - Record
func asRecord() throws -> SDSRecord {
let id: Int64? = nil
let recordType: SDSRecordType = .device
let uniqueId: String = model.uniqueId
// Base class properties
let createdAt: Double = archiveDate(model.createdAt)
let deviceId: Int = model.deviceId
let lastSeenAt: Double = archiveDate(model.lastSeenAt)
let name: String? = model.name
return DeviceRecord(id: id, recordType: recordType, uniqueId: uniqueId, createdAt: createdAt, deviceId: deviceId, lastSeenAt: lastSeenAt, name: name)
}
}
|
gpl-3.0
|
0c70334034233be7aa8c74ab263e9353
| 36.357268 | 157 | 0.612958 | 5.186239 | false | false | false | false |
acavanaghww/PagedArray
|
Source/PagedArray.swift
|
1
|
6317
|
//
// PagedArray.swift
//
// Created by Alek Åström on 2015-02-14.
// Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek)
//
// 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.
///
/// A paging collection type for arbitrary elements. Great for implementing paging
/// mechanisms to scrolling UI elements such as `UICollectionView` and `UITableView`.
///
public struct PagedArray<T> {
public typealias Element = T
/// The datastorage
public private(set) var pages = [Int: [Element]]()
// MARK: Public properties
/// The size of each page
public let pageSize: Int
/// The total count of supposed elements, including nil values
public var count: Int
/// The starting page index
public let startPageIndex: Int
/// When set to true, no size or upper index checking
/// is done when setting pages, making the paged array
/// adjust its size dynamically.
///
/// Useful for infinite lists and when data count cannot
/// be guaranteed not to change while loading new pages.
public var updatesCountWhenSettingPages: Bool = false
/// The last valid page index
public var lastPageIndex: Int {
if count == 0 {
return 0
} else if count%pageSize == 0 {
return count/pageSize+startPageIndex-1
} else {
return count/pageSize+startPageIndex
}
}
/// All elements currently set, in order
public var loadedElements: [Element] {
return self.filter{ $0 != nil }.map{ $0! }
}
// MARK: Initializers
/// Creates an empty `PagedArray`
public init(count: Int, pageSize: Int, startPageIndex: Int = 0) {
self.count = count
self.pageSize = pageSize
self.startPageIndex = startPageIndex
}
// MARK: Public functions
/// Returns the page index for an element index
public func pageNumberForIndex(index: Index) -> Int {
assert(index >= startIndex && index < endIndex, "Index out of bounds")
return index/pageSize+startPageIndex
}
/// Returns a `Range` corresponding to the indexes for a page
public func indexes(pageIndex: Int) -> Range<Index> {
assert(pageIndex >= startPageIndex && pageIndex <= lastPageIndex, "Page index out of bounds")
let startIndex: Index = (pageIndex-startPageIndex)*pageSize
let endIndex: Index
if pageIndex == lastPageIndex {
endIndex = count
} else {
endIndex = startIndex+pageSize
}
return (startIndex..<endIndex)
}
// MARK: Public mutating functions
/// Sets a page of elements for a page index
public mutating func setElements(elements: [Element], pageIndex: Int) {
assert(pageIndex >= startPageIndex, "Page index out of bounds")
assert(count == 0 || elements.count > 0, "Can't set empty elements page on non-empty array")
let pageIndexForExpectedSize = (pageIndex > lastPageIndex) ? lastPageIndex : pageIndex
let expectedSize = sizeForPage(pageIndexForExpectedSize)
if !updatesCountWhenSettingPages {
assert(pageIndex <= lastPageIndex, "Page index out of bounds")
assert(elements.count == expectedSize, "Incorrect page size")
} else {
// High Chaparall mode, array can change in size
count += elements.count-expectedSize
if pageIndex > lastPageIndex {
count += (pageIndex-lastPageIndex)*pageSize
}
}
pages[pageIndex] = elements
}
/// Removes the elements corresponding to the page, replacing them with `nil` values
public mutating func removePage(pageNumber: Int) {
pages[pageNumber] = nil
}
/// Removes all loaded elements, replacing them with `nil` values
public mutating func removeAllPages() {
pages.removeAll(keepCapacity: true)
}
}
// MARK: SequenceType
extension PagedArray : SequenceType {
public func generate() -> IndexingGenerator<PagedArray> {
return IndexingGenerator(self)
}
}
// MARK: CollectionType
extension PagedArray : CollectionType {
public typealias Index = Int
public var startIndex: Index { return 0 }
public var endIndex: Index { return count }
public subscript (index: Index) -> Element? {
let pageNumber = pageNumberForIndex(index)
if let page = pages[pageNumber] {
return page[index%pageSize]
} else {
// Return nil for all pages that haven't been set yet
return nil
}
}
}
// MARK: Printable
extension PagedArray : CustomStringConvertible {
public var description: String {
return "PagedArray(\(Array(self)))"
}
}
// MARK: DebugPrintable
extension PagedArray : CustomDebugStringConvertible {
public var debugDescription: String {
return "PagedArray(Pages: \(pages), Array representation: \(Array(self)))"
}
}
// MARK: Private functions
private extension PagedArray {
func sizeForPage(pageIndex: Int) -> Int {
let indexes = self.indexes(pageIndex)
return indexes.endIndex-indexes.startIndex
}
}
|
mit
|
ad2df20b183a1d2badab2cf6cf4d8888
| 32.226316 | 101 | 0.652305 | 4.852421 | false | false | false | false |
Farteen/RAReorderableLayout
|
RAReorderableLayout-Demo/RAReorderableLayout-Demo/ViewController.swift
|
3
|
2638
|
//
// ViewController.swift
// RAReorderableLayout-Demo
//
// Created by Ryo Aoyama on 10/29/14.
// Copyright (c) 2014 Ryo Aoyama. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var verticalButton: RAButton!
@IBOutlet weak var horizontalButton: RAButton!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "RAReorderableLayout"
self.verticalButton.exclusiveTouch = true
self.horizontalButton.exclusiveTouch = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let num1: CGFloat = CGFloat(arc4random_uniform(256)) / 255.0
let num2: CGFloat = CGFloat(arc4random_uniform(256)) / 255.0
let num3: CGFloat = CGFloat(arc4random_uniform(256)) / 255.0
let color1: UIColor = UIColor(red: num1, green: num2, blue: num3, alpha: 1.0)
let color2: UIColor = UIColor(red: num3, green: num2, blue: num1, alpha: 1.0)
if (num1 + num2 + num3) / 3.0 >= 0.5 {
self.verticalButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.horizontalButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
}else {
self.verticalButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.horizontalButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
}
self.verticalButton.backgroundColor = color1
self.horizontalButton.backgroundColor = color2
}
}
class RAButton: UIButton {
var baseView: UIView!
override var highlighted: Bool {
didSet {
let transform: CGAffineTransform = highlighted ?
CGAffineTransformMakeScale(1.1, 1.1) : CGAffineTransformIdentity
UIView.animateWithDuration(0.05, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in
self.transform = transform
}, completion: nil)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configure()
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = CGRectGetWidth(self.bounds) / 2;
}
private func configure() {
self.baseView = UIView(frame: self.bounds)
self.layer.cornerRadius = CGRectGetWidth(self.bounds)
self.baseView.addSubview(self)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
}
}
|
mit
|
4acaf9ab0413dcf597c7c2fcc51cba72
| 33.723684 | 115 | 0.644428 | 4.374793 | false | false | false | false |
johnpatrickmorgan/URLPatterns
|
Sources/FoundationExtensions.swift
|
1
|
1533
|
//
// FoundationExtensions.swift
// Pods
//
// Created by John Morgan on 29/04/2016.
//
//
import Foundation
extension URLComponents {
public func queryArguments() -> [String : String?] {
var arguments = [String : String?]()
for item in queryItems ?? [] {
arguments[item.name] = item.value
}
return arguments
}
public func flatQueryArguments() -> [String : String] {
var arguments = [String : String]()
for (key, value) in queryArguments() {
if value != nil {
arguments[key] = value
}
}
return arguments
}
}
extension URL {
public func countedPathComponents(_ excludingLeadingBackslash: Bool = true) -> Counted<String> {
if let first = pathComponents.first , excludingLeadingBackslash && first == "/" {
return Counted(sequence: pathComponents.dropFirst())
}
return Counted(pathComponents)
}
}
extension URL {
public func queryArguments() -> [String : String?] {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return [:] }
return components.queryArguments()
}
public func flatQueryArguments() -> [String : String] {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return [:] }
return components.flatQueryArguments()
}
}
|
mit
|
2aa5cc9243665769f821639b28e08cbe
| 23.725806 | 106 | 0.567515 | 4.961165 | false | false | false | false |
jegumhon/URWeatherView
|
Example/URExampleWeatherView/URExampleWeatherTableViewCell.swift
|
1
|
2097
|
//
// URExampleWeatherTableViewCell.swift
// URExampleWeatherView
//
// Created by DongSoo Lee on 2017. 5. 22..
// Copyright © 2017년 zigbang. All rights reserved.
//
import UIKit
import URWeatherView
class URExampleWeatherTableViewCell: UITableViewCell {
@IBOutlet var btnApplyWeather: UIButton!
@IBOutlet var slBirthRate: UISlider!
@IBOutlet var lbBirthRateCurrent: UILabel!
@IBOutlet var lbBirthRateMax: UILabel!
var weather: URWeatherType = .snow
var applyWeatherBlock: (() -> Void)?
var stopWeatherBlock: (() -> Void)?
var removeToneFilterBlock: (() -> Void)?
var birthRateDidChange: ((CGFloat) -> Void)?
func configCell(_ weather: URWeatherType) {
self.weather = weather
self.btnApplyWeather.setTitle(weather.name, for: .normal)
self.slBirthRate.value = Float(weather.defaultBirthRate)
self.slBirthRate.maximumValue = Float(weather.maxBirthRate)
self.lbBirthRateCurrent.text = "\(self.slBirthRate.value)"
self.lbBirthRateMax.text = "\(self.slBirthRate.maximumValue)"
switch weather {
case .lightning, .hot:
self.slBirthRate.isEnabled = false
default:
break
}
}
@IBAction func tapApplyWeather(_ sender: Any) {
guard let apply = self.applyWeatherBlock else { return }
apply()
guard let setBirthRate = self.birthRateDidChange else { return }
setBirthRate(CGFloat(self.slBirthRate.value))
}
@IBAction func tapWeatherInit(_ sender: Any) {
self.slBirthRate.value = Float(self.weather.defaultBirthRate)
self.lbBirthRateCurrent.text = "\(self.slBirthRate.value)"
if let block = self.removeToneFilterBlock {
block()
}
guard let block = self.stopWeatherBlock else { return }
block()
}
@IBAction func changeBirthRate(_ sender: Any) {
self.lbBirthRateCurrent.text = "\(self.slBirthRate.value)"
guard let block = self.birthRateDidChange else { return }
block(CGFloat(self.slBirthRate.value))
}
}
|
mit
|
8604349279d69d1020054d5ad13dae36
| 29.794118 | 72 | 0.660936 | 4.282209 | false | false | false | false |
hejunbinlan/LTMorphingLabel
|
LTMorphingLabel/LTMorphingLabel+Fall.swift
|
6
|
5027
|
//
// LTMorphingLabel+Fall.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
func FallLoad() {
progressClosures["Fall\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if isNewChar {
return min(1.0, max(0.0, progress - self.morphingCharacterDelay * Float(index) / 1.7))
}
let j: Float = Float(sin(Double(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * Float(j)))
}
effectClosures["Fall\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Fall\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
let currentFontSize = CGFloat(LTEasing.easeOutQuint(progress, 0.0, Float(self.font.pointSize)))
let yOffset = CGFloat(self.font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self.newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
drawingClosures["Fall\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let context = UIGraphicsGetCurrentContext()
var charRect = charLimbo.rect
CGContextSaveGState(context);
let charCenterX = charRect.origin.x + (charRect.size.width / 2.0)
var charBottomY = charRect.origin.y + charRect.size.height - self.font.pointSize / 6
var charColor = self.textColor
// Fall down if drawingProgress is more than 50%
if charLimbo.drawingProgress > 0.5 {
let ease = CGFloat(LTEasing.easeInQuint(Float(charLimbo.drawingProgress - 0.4), 0.0, 1.0, 0.5))
charBottomY = charBottomY + ease * 10.0
let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01))
charColor = self.textColor.colorWithAlphaComponent(fadeOutAlpha)
}
charRect = CGRectMake(
charRect.size.width / -2.0,
charRect.size.height * -1.0 + self.font.pointSize / 6,
charRect.size.width,
charRect.size.height)
CGContextTranslateCTM(context, charCenterX, charBottomY)
let angle = Float(sin(Double(charLimbo.rect.origin.x)) > 0.5 ? 168 : -168)
let rotation = CGFloat(LTEasing.easeOutBack(min(1.0, Float(charLimbo.drawingProgress)), 0.0, 1.0) * angle)
CGContextRotateCTM(context, rotation * CGFloat(M_PI) / 180.0)
let s = String(charLimbo.char)
s.drawInRect(charRect, withAttributes: [
NSFontAttributeName: self.font.fontWithSize(charLimbo.size),
NSForegroundColorAttributeName: charColor
])
CGContextRestoreGState(context);
return true
}
return false
}
}
}
|
mit
|
232c1c2d1a19fd1454acef64747fbc55
| 42.267241 | 122 | 0.579797 | 4.891813 | false | false | false | false |
swift-lang/swift-k
|
tests/checkpoint_restart/checkpoint_restart_parallel.swift
|
2
|
1647
|
type file;
// The app will return a file "done" with string done when complete
app (file out, file err, file done) fibonacci (file script, int count, int sleep, file checkpoint)
{
bash @script "-c" count "-s" 1 "-e" 10000 "-f" @done "-p" @checkpoint stdout=@out stderr=@err;
}
// The app will return a file "done" with string done when complete.
// With the -x option you can set the failure rate, and see simulated failures in the app
// and how swift handles those failures
app (file out, file err, file done) fibonacci_randfail (file script, int count, int sleep, file checkpoint)
{
bash @script "-x" 0.3 "-c" count "-s" 1 "-e" 10000 "-f" @done "-p" @checkpoint stdout=@out stderr=@err;
}
// Create empty files for initial conditions
app (file out) empty ()
{
touch @out;
}
file wrapper <"fibonacci.sh">;
int nsim = toInt(arg("nsim","1"));
int nsteps = toInt(arg("nsteps","5"));
file out[][] <simple_mapper; location="output", prefix="fibonacci", suffix=".out">;
file err[][] <simple_mapper; location="output", prefix="fibonacci", suffix=".err">;
file done[][] <simple_mapper; location="output", prefix="fibonacci", suffix=".done">;
string isdone[][];
foreach sim in [1:nsim]{
// Set the initial conditions to enter the iterate loop
isdone[sim][0] = "notdone";
// Set an empty file to be fed to the initial run of app
out[sim][0] = empty();
iterate steps {
(out[sim][steps+1], err[sim][steps+1], done[sim][steps+1]) = fibonacci_randfail (wrapper , nsteps, 1, out[sim][steps]);
isdone[sim][steps+1] = readData( done[sim][steps+1] );
} until ( isdone[sim][steps] == "done" );
}
|
apache-2.0
|
e2f73ba27238646a75a462ec4bb67cf4
| 35.6 | 127 | 0.652702 | 3.334008 | false | false | false | false |
epeschard/RealmSearchTableViewController
|
CustomTableViewCell.swift
|
1
|
2821
|
//
// CustomTableViewCell.swift
// SearchRealmTableViewController
//
// Created by Eugène Peschard on 19/11/2016.
// Copyright © 2016 PeschApps. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
var object: CustomObject? {
didSet {
updateUI()
setFonts()
}
}
func setFonts() {
textLabel!.font = customBody
}
func updateUI() {
if searchString != "" {
textLabel?.textColor = UIColor.grayColor()
}
textLabel?.attributedText = highlight(searchString, inString: object?.name ?? "N/A")
if let imageData = object?.image {
imageView?.image = UIImage(data: imageData)
}
}
// This part bellow may be extracted and then subclassed
var searchString = ""
// Custom Dynamic Text Fonts
let customHeadline = UIFont(descriptor: UIFontDescriptor.preferredCustomFontWithDescriptor(UIFontTextStyleHeadline), size: 0)
let customSubheadline = UIFont(descriptor: UIFontDescriptor.preferredCustomFontWithDescriptor(UIFontTextStyleSubheadline), size: 0)
let customBody = UIFont(descriptor: UIFontDescriptor.preferredCustomFontWithDescriptor(UIFontTextStyleBody), size: 0)
var attributes : [String: AnyObject] {
get {
// let shadow = NSShadow()
// shadow.shadowBlurRadius = 1.0
// shadow.shadowColor = UIColor.blueColor()
// shadow.shadowOffset = CGSizeMake(0, 1.0)
return [NSForegroundColorAttributeName : UIColor.blueColor()
// NSUnderlineStyleAttributeName: 1,
// NSShadowAttributeName: shadow,
// NSFontAttributeName: customHeadline
]
}
}
// MARK: - Highlight search
func highlight(subString:String,
inString string:String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string)
if subString != "" {
let searchStrings = subString.componentsSeparatedByString(" ") as [String]
for searchString in searchStrings {
let swiftRange = string.rangeOfString(searchString,
options: .CaseInsensitiveSearch,
range: nil,
locale: NSLocale.currentLocale())
if let swiftRange = swiftRange {
let nsRange = string.getNSRangeFrom(swiftRange)
attributedString.setAttributes(attributes, range: nsRange)
}
}
}
return attributedString
}
}
|
mit
|
a8e0ac83db5b5e88bbfdde00a68cffdb
| 34.2375 | 135 | 0.571834 | 5.872917 | false | false | false | false |
orcudy/archive
|
ios/apps/speed/Speed!/Controllers/StartViewController.swift
|
1
|
3266
|
//
// StartViewController.swift
// Speed!
//
// Created by Orcudy on 10/1/15.
// Copyright © 2015 Chris Orcutt. All rights reserved.
//
import UIKit
class StartViewController: UIViewController {
// properties connected to our view objects in Interface Builder
// the "@IBOutlet" keyword indicates to Xcode that these properties are connected to objects in Interface Builder (IB)
@IBOutlet weak var topView: UIView!
@IBOutlet weak var bottomView: UIView!
// properties connected to our "Ready" buttons in IB
@IBOutlet weak var topReadyButton: UIButton!
@IBOutlet weak var bottomReadyButton: UIButton!
// `Player` is a custom class that is defined in the Player.swift file
// because we have two players in our game, we need two `instances` of the `Player` class
let topPlayer = Player(name: "Top Player")
let bottomPlayer = Player(name: "Bottom Player")
// MARK: - LifeCycle
// method defined by UIViewController class
// called after our view is finished loading
// (this method is only called ONCE, the very first time we see our Start Screen)
override func viewDidLoad() {
topReadyButton.transform.rotate(degrees: 180)
}
// method defined by UIViewController class
// called before our view appears on screen
// (this method is called EVERYTIME we see our Start Scene)
override func viewWillAppear(animated: Bool) {
topReadyButton.setTitleColor(UIColor.blue(), forState: UIControlState.Normal)
topView.backgroundColor = UIColor.whiteColor()
bottomReadyButton.setTitleColor(UIColor.red(), forState: UIControlState.Normal)
bottomView.backgroundColor = UIColor.whiteColor()
}
// MARK: - Navigation
// special method that allows us to undue segues
@IBAction func unwindToStart(segue: UIStoryboardSegue) {
topPlayer.ready = false
topPlayer.score = 0
bottomPlayer.ready = false
bottomPlayer.score = 0
}
// called before every segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "gameplayTransition" {
let destinationViewController = segue.destinationViewController as! GameplayViewController
destinationViewController.topPlayer = topPlayer
destinationViewController.bottomPlayer = bottomPlayer
}
}
// MARK: - GameLogic
// called whenever the top "Ready" button is pressed
// (the "@IBAction" indicates to Xcode that this method is connecting to something in Interface Builder)
@IBAction func topReadyButtonTapped(sender: UIButton) {
topReadyButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
topView.backgroundColor = UIColor.blue()
topPlayer.ready = true
startGame()
}
// called whenever the bottom "Ready" button is pressed
@IBAction func bottomReadyButtonTapped(sender: UIButton) {
bottomReadyButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
bottomView.backgroundColor = UIColor.red()
bottomPlayer.ready = true
startGame()
}
// called to check (and optionally) start the game
func startGame() {
if topPlayer.ready && bottomPlayer.ready {
self.performSegueWithIdentifier("gameplayTransition", sender: self)
}
}
}
|
gpl-3.0
|
806fe4d62b37b937676738c6597efa6c
| 33.744681 | 120 | 0.729862 | 4.718208 | false | false | false | false |
MakeAWishFoundation/SwiftyMocky
|
Sources/SwiftyMocky/MockyAssert.swift
|
1
|
1687
|
#if canImport(XCTest)
import XCTest
#endif
import Foundation
/// You can use this class if there is need to define custom
/// assertion handler. You can use its static handler closure to alter default
/// behaviour.
///
/// If it is `nil`, the default `assert` method would be used.
public final class MockyAssertion {
/// You can use it to define assertion behaviour.
/// Leave blank to not assert at all.
public static var handler: ((Bool, String, StaticString, UInt) -> Void)?
}
/// [internal] Assertion used by mocks and Verify methods
///
/// - Parameters:
/// - expression: Expression to assert on
/// - message: Message
/// - file: File name (levae default)
/// - line: Line (levae default)
public func MockyAssert(
_ expression: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = "Verify failed",
file: StaticString = #file,
line: UInt = #line
) {
guard let handler = MockyAssertion.handler else {
return XCTMockyAssert(expression(), message(), file: file, line: line)
}
handler(expression(), message(), file, line)
}
/// [internal] Assertion used by mocks and Verify methods
///
/// - Parameters:
/// - expression: Expression to assert on
/// - message: Message
/// - file: File name (levae default)
/// - line: Line (levae default)
private func XCTMockyAssert(
_ expression: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = "Verify failed",
file: StaticString = #file,
line: UInt = #line
) {
#if canImport(XCTest)
XCTAssert(expression(), message(), file: file, line: line)
#else
assert(expression(), message(), file: file, line: line)
#endif
}
|
mit
|
06de467a51b5d62411b8a2d8b18207f8
| 29.125 | 78 | 0.652638 | 3.923256 | false | true | false | false |
ismailbozk/DateIntervalPicker
|
DateIntervalPicker/DateIntervalPickerView/DateIntervalPickerUtils.swift
|
1
|
2120
|
//
// DateIntervalPickerUtils.swift
// DateIntervalPicker
//
// Created by Ismail Bozkurt on 10/04/2016.
// The MIT License (MIT)
//
// Copyright (c) 2016 Ismail Bozkurt
//
// 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
private let dateUnits:NSCalendarUnit =
[.Year, .Month, .Day, .Hour, .Minute, .Second, .WeekOfYear, .Weekday, .WeekdayOrdinal]
class DateIntervalPickerUtils {
static func numberOfDays(fromDate: NSDate, toDate: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
var fromDateTime: NSDate?, toDateTime: NSDate?
calendar.rangeOfUnit(.Day, startDate: &fromDateTime, interval: nil, forDate: fromDate)
calendar.rangeOfUnit(.Day, startDate: &toDateTime, interval: nil, forDate: toDate)
let difference = calendar.components(.Day, fromDate: fromDateTime!, toDate: toDateTime!, options: [])
return difference.day
}
}
|
mit
|
e1ee49267362a5786a44d1cbbe0003f2
| 41.4 | 111 | 0.713679 | 4.335378 | false | false | false | false |
dduan/swift
|
test/decl/func/complete_object_init.swift
|
5
|
4088
|
// RUN: %target-parse-verify-swift
// ---------------------------------------------------------------------------
// Declaration of complete object initializers and basic semantic checking
// ---------------------------------------------------------------------------
class A {
convenience init(int i: Int) { // expected-note{{convenience initializer is declared here}}
self.init(double: Double(i))
}
convenience init(float f: Float) {
self.init(double: Double(f))
}
init(double d: Double) {
}
convenience init(crazy : A) {
self.init(int: 42)
}
}
class OtherA {
init(double d: Double, negated: Bool) { // expected-error{{designated initializer for 'OtherA' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}}{{3-3=convenience }}
self.init(double: negated ? -d : d) // expected-note{{delegation occurs here}}
}
init(double d: Double) {
}
}
class DerivesA : A {
init(int i: Int) {
super.init(int: i) // expected-error{{must call a designated initializer of the superclass 'A'}}
}
convenience init(string: String) {
super.init(double: 3.14159) // expected-error{{convenience initializer for 'DerivesA' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')}}
}
}
struct S {
convenience init(int i: Int) { // expected-error{{delegating initializers in structs are not marked with 'convenience'}}
self.init(double: Double(i))
}
init(double d: Double) {
}
}
class DefaultInitComplete {
convenience init() {
self.init(string: "foo")
}
init(string: String) { }
}
class SubclassDefaultInitComplete : DefaultInitComplete {
init() { }
}
// ---------------------------------------------------------------------------
// Inheritance of initializers
// ---------------------------------------------------------------------------
// inherits convenience initializers
class B1 : A {
override init(double d: Double) {
super.init(double: d)
}
}
func testConstructB1(i: Int, f: Float, d: Double) {
let b1a = B1(int: i)
let b1b = B1(float: f)
let b1c = B1(double: d)
var b: B1 = b1a
b = b1b
b = b1c
_ = b
}
// does not inherit convenience initializers
class B2 : A {
var s: String
init() {
s = "hello"
super.init(double: 1.5)
}
}
func testConstructB2(i: Int) {
var b2a = B2()
var b2b = B2(int: i) // expected-error{{argument passed to call that takes no arguments}}
var b2: B2 = b2a
}
// Initializer inheritance can satisfy the requirement for an
// @required initializer within a subclass.
class Ab1 {
required init() { }
}
class Ab2 : Ab1 {
var s: String
// Subclasses can use this to satisfy the required initializer
// requirement.
required convenience init() { // expected-note{{'required' initializer is declared in superclass here}}
self.init(string: "default")
}
init(string s: String) {
self.s = s
super.init()
}
}
class Ab3 : Ab2 {
override init(string s: String) {
super.init(string: s)
}
}
class Ab4 : Ab3 {
init(int: Int) {
super.init(string:"four")
}
// expected-error{{'required' initializer 'init()' must be provided by subclass of 'Ab2'}}
func blah() { }
}
// Only complete object initializers are allowed in extensions
class Extensible { }
extension Extensible {
init(int i: Int) { // expected-error{{designated initializer cannot be declared in an extension of 'Extensible'; did you mean this to be a convenience initializer?}}{{3-3=convenience }}
self.init()
}
}
// <rdar://problem/17785840>
protocol Protocol {
init(string: String)
}
class Parent: Protocol {
required init(string: String) {}
}
class Child: Parent {
convenience required init(string: String) {
self.init(string: "")
}
}
// overriding
class Parent2 {
init() { }
convenience init(int: Int) { self.init() }
}
class Child2 : Parent2 {
convenience init(int: Int) { self.init() }
}
func testOverride(int: Int) {
Child2(int: int) // okay, picks Child2.init // expected-warning{{unused}}
}
|
apache-2.0
|
4e4096c4618f5f5cde108edebf55ad7b
| 22.630058 | 205 | 0.610323 | 3.65653 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.