repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ZhengShouDong/CloudPacker
|
refs/heads/master
|
Sources/CloudPacker/Libraries/CryptoSwift/Array+Extensions.swift
|
apache-2.0
|
1
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public extension Array where Element == UInt8 {
public func toHexString() -> String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
public extension Array where Element == UInt8 {
public func md5() -> [Element] {
return Digest.md5(self)
}
public func sha1() -> [Element] {
return Digest.sha1(self)
}
public func sha224() -> [Element] {
return Digest.sha224(self)
}
public func sha256() -> [Element] {
return Digest.sha256(self)
}
public func sha384() -> [Element] {
return Digest.sha384(self)
}
public func sha512() -> [Element] {
return Digest.sha512(self)
}
public func sha2(_ variant: SHA2.Variant) -> [Element] {
return Digest.sha2(self, variant: variant)
}
public func sha3(_ variant: SHA3.Variant) -> [Element] {
return Digest.sha3(self, variant: variant)
}
public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 {
return Checksum.crc32(self, seed: seed, reflect: reflect)
}
public func crc16(seed: UInt16? = nil) -> UInt16 {
return Checksum.crc16(self, seed: seed)
}
public func encrypt(cipher: Cipher) throws -> [Element] {
return try cipher.encrypt(slice)
}
public func decrypt(cipher: Cipher) throws -> [Element] {
return try cipher.decrypt(slice)
}
public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Element] {
return try authenticator.authenticate(self)
}
}
|
d8d6e4e56824ff83e1930bc0f7dc77f7
| 30.719512 | 217 | 0.640138 | false | false | false | false |
cxpyear/SPDBDemo
|
refs/heads/master
|
spdbapp/spdbapp/Classes/Controller/RegisViewController.swift
|
bsd-3-clause
|
1
|
//
// RegisViewController.swift
// spdbapp
//
// Created by GBTouchG3 on 15/6/26.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Alamofire
import SnapKit
var bNeedRefresh = true
var MyDeviceId = "MyDeviceId"
var MyDeviceName = "MyDeviceName"
class RegisViewController: UIViewController, UIAlertViewDelegate, UITextFieldDelegate {
@IBOutlet weak var viewparent: UIView!
@IBOutlet weak var btnOK: UIButton!
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtPwd: UITextField!
@IBOutlet weak var middleView: UIView!
@IBOutlet weak var loading: UIActivityIndicatorView!
@IBOutlet weak var btnOffLine: UIButton!
@IBOutlet weak var viewInput: UIView!
@IBOutlet weak var lblCurrentUserName: UILabel!
@IBOutlet weak var userView: UIView!
var kbHeight: CGFloat!
var myUser = GBUser()
var bNeedMove = true
var bNeedInit = true
var myBox = GBBox()
var bNeedPostNote = false
override func viewDidLoad() {
super.viewDidLoad()
println("path = \(NSHomeDirectory())")
txtName.delegate = self
txtPwd.delegate = self
btnOK.layer.cornerRadius = 8
btnOK.addTarget(self, action: "goLogin", forControlEvents: UIControlEvents.TouchUpInside)
btnOffLine.layer.cornerRadius = 8
// NetConnection().httpGet(server.meetingServiceUrl)
self.loading.hidden = true
//WARNING 记得正式运行时要改过来
// self.btnOK.backgroundColor = UIColor.grayColor()
// self.btnOK.enabled = false
self.btnOK.enabled = true
self.btnOK.backgroundColor = SHColor(143 , 1 , 41)
}
@IBAction func getOffLineMeeting(sender: UIButton) {
bNeedRefresh = false
var userInfoPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt")
var manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(userInfoPath){
UIAlertView(title: "提示", message: "当前无离线会议", delegate: self, cancelButtonTitle: "确定").show()
}
var userinfo = NSDictionary(contentsOfFile: userInfoPath)
self.myUser.id = userinfo?.objectForKey("id") as! String
self.myUser.username = userinfo?.objectForKey("username") as! String
self.myUser.name = userinfo?.objectForKey("name") as! String
self.myUser.password = userinfo?.objectForKey("password") as! String
self.myUser.type = userinfo?.objectForKey("type") as! String
self.myUser.role = userinfo?.objectForKey("role") as! String
println("role = \(userinfo)")
appManager.appGBUser = self.myUser
bNeedRefresh = false
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let agendaVC: AgendaViewController = storyboard.instantiateViewControllerWithIdentifier("agenda") as! AgendaViewController
self.presentViewController(agendaVC, animated: true, completion: nil)
}
/**
登录方法
*/
func goLogin(){
bNeedRefresh = true
self.loading.hidden = false
self.loading.startAnimating()
var name = txtName.text.trimAllString()
var pwd = txtPwd.text.trimAllString()
//如果当前box绑定对象为空,则要进行登录验证,否则获取其权限直接登录
var userInfoPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt")
var userinfo = NSDictionary(contentsOfFile: userInfoPath)
var dictName = userinfo?.objectForKey("username") as? String
if (self.myUser.username == dictName) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let agendaVC: AgendaViewController = storyboard.instantiateViewControllerWithIdentifier("agenda") as! AgendaViewController
self.presentViewController(agendaVC, animated: true, completion: nil)
self.loading.stopAnimating()
}else{
let paras = [ "username" : name, "password" : pwd ]
Alamofire.request(.POST, server.loginServiceUrl ,parameters: paras, encoding: .JSON).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (request,response, data, error) ->
Void in
println("data = \(data)")
if error != nil{
println("login err = \(error)")
UIAlertView(title: "提示", message: "登录失败,无法连接到服务器", delegate: self, cancelButtonTitle: "确定").show()
self.loading.stopAnimating()
return
} else if(response?.statusCode != 200){
UIAlertView(title: "提示", message: "登录失败,用户名或密码错误", delegate: self, cancelButtonTitle: "确定").show()
self.txtName.text = ""
self.txtPwd.text = ""
self.loading.stopAnimating()
self.txtName.becomeFirstResponder()
return
}
self.myUser.username = data?.objectForKey("username") as! String
self.myUser.name = data?.objectForKey("name") as! String
self.myUser.password = data?.objectForKey("password") as! String
self.myUser.type = data?.objectForKey("type") as! String
self.myUser.role = data?.objectForKey("role") as! String
self.saveUserInfo()
appManager.appGBUser = self.myUser
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let agendaVC: AgendaViewController = storyboard.instantiateViewControllerWithIdentifier("agenda") as! AgendaViewController
self.presentViewController(agendaVC, animated: true, completion: nil)
self.loading.stopAnimating()
}
}
}
func saveUserInfo(){
var UserInfoPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt")
var manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath(UserInfoPath){
manager.removeItemAtPath(UserInfoPath, error: nil)
}
manager.createFileAtPath(UserInfoPath, contents: nil, attributes: nil)
var info = NSMutableDictionary()
info["id"] = self.myUser.id
info["username"] = self.myUser.username
info["name"] = self.myUser.name
info["type"] = self.myUser.type
info["role"] = self.myUser.role
info["password"] = self.myUser.password
info.writeToFile(UserInfoPath, atomically: true)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
private var mycontext = 0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//判断jsondata文件或者用户信息文件是否存在,若存在,则可以开启离线会议;否则离线会议按钮隐藏
isOffLineMeetingExist()
self.userView.hidden = true
isCurrentDeviceRegister()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil);
}
func isOffLineMeetingExist(){
var jsonFilePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
var userInfoFilePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt")
var manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(jsonFilePath) || !manager.fileExistsAtPath(userInfoFilePath){
self.btnOffLine.hidden = true
}else{
self.btnOffLine.hidden = false
}
}
func postIdtoRegister(){
var paras = ["id": GBNetwork.getMacId()]
Alamofire.request(.POST, server.boxServiceUrl, parameters: paras, encoding: .JSON).responseJSON(options: NSJSONReadingOptions.AllowFragments, completionHandler: { (request, response, data, error) -> Void in
if error != nil{
println("post macid error = \(error)")
return
}else{
println("post macid response = \(response?.statusCode.description)")
}
self.userView.hidden = true
self.viewInput.hidden = false
})
}
// func getKeys(){
// var user = GBUser()
// var mirror = reflect(user)
// for var i = 0 ; i < mirror.count ; i++ {
// println("mirror\(i) = \(mirror[i].0)")
// }
// }
// func dataToModel(data: AnyObject, model: AnyObject) -> AnyObject {
// // var model = NSObject()
// // getKeys()
//
// var mirror = reflect(model)
//
// var aClass = user.self
//
// if data.isKindOfClass(NSDictionary.self) == false{
// println("data不是一个字典")
// return
// }else{
// var dict = NSDictionary(dictionary: data as! NSDictionary)
// for var i = 0 ; i < dict.count ; i++ {
// var key = dict.keyEnumerator().allObjects[i] as! String
// if let keyValue: AnyObject = dict.valueForKey(key){
// println("key = \(key)==========val = \(keyValue)")
//
// for var i = 1; i < mirror.count ; i++ {
// if mirror[i].0 == key{
// model.setValue(keyValue, forKeyPath: mirror[i].0)
// }
// }
// }
// }
// }
// }
func getMemberInfo(memberid: String){
var urltest = server.memberServiceUrl + "/" + memberid
Alamofire.request(.GET, urltest).responseJSON(options: NSJSONReadingOptions.MutableContainers, completionHandler: { (request, response, data, membererror) -> Void in
//如果返回错误则break
if membererror != nil{
println("membererror error = \(membererror)")
return
}else{
println("response data = \(data)")
//将当前获取到的member信息和userinfo.txt中的member信息比较,若完全一致,则直接跳转到快速登录界面,否则先保存当前的member信息,并跳转到快速登录界面
self.myUser.id = data?.objectForKey("id") as! String
self.myUser.username = data?.objectForKey("username") as! String
self.myUser.name = data?.objectForKey("name") as! String
self.myUser.password = data?.objectForKey("password") as! String
self.myUser.type = data?.objectForKey("type") as! String
self.myUser.role = data?.objectForKey("role") as! String
self.saveUserInfo()
appManager.appGBUser = self.myUser
self.viewInput.hidden = true
self.userView.hidden = false
self.lblCurrentUserName.text = "当前用户: \(self.myUser.username)"
}
})
}
func isCurrentDeviceRegister(){
//将当前Mac-ID发get请求,
//如果返回了memberid,表明该设备已经注册过,则继续将该memberid发get请求,
//若返回了当前用户的所有信息,将其与之前保存的用户信息比较,如果都一样,则直接进入快速登录界面
//若与之前的用户信息不一致,则进入登录界面
//如果未返回当前memberid,表明该设备未注册,发post请求将该设备至web端注册,并且进入登录界面
var str = server.boxServiceUrl + "/" + GBNetwork.getMacId()
var urlStr = NSURL(string: str)!
println("box service url ====== \(urlStr)")
Alamofire.request(.GET, str).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (request, response, data, error) -> Void in
if error != nil{
println("isCurrentDeviceRegister error = \(error)")
return
}else{
println("isCurrentDeviceRegister response = \(response?.statusCode.description) ")
if response?.statusCode.description == "400"{
self.postIdtoRegister()
}else{
var json = JSON(data!)
var memberid = json["memberid"].stringValue
if memberid.isEmpty == false && memberid != "0" {
self.getMemberInfo(memberid)
}
}
}
}
}
override func shouldAutomaticallyForwardRotationMethods() -> Bool {
self.txtName.resignFirstResponder()
self.txtPwd.resignFirstResponder()
return true
}
override func shouldAutorotate() -> Bool {
self.view.endEditing(true)
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == txtName{
txtPwd.becomeFirstResponder()
}else if textField == txtPwd{
goLogin()
}
return true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillHide(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
// println("size hide = \(keyboardSize)======needMove = \(self.bNeedMove)")
if self.bNeedMove == true{
kbHeight = 0
}else{
kbHeight = self.view.frame.height * 0.15
bNeedMove = true
}
self.animateTextField(false)
}
}
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
// println("size show = \(keyboardSize)======needMove = \(self.bNeedMove)")
if keyboardSize.width >= 1024 && self.bNeedMove == true{
kbHeight = self.view.frame.height * 0.15
self.bNeedMove = false
}else{
kbHeight = 0
}
self.animateTextField(true)
}
}
}
func animateTextField(up: Bool) {
var movement = (up ? -kbHeight : kbHeight)
// println("movement = \(movement)")
UIView.animateWithDuration(0.3, animations: {
self.middleView.frame = CGRectOffset(self.middleView.frame, 0, movement)
self.viewInput.frame = CGRectOffset(self.viewInput.frame, 0, movement)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
d3bb048d1f8506bb400499d4fb06f6d8
| 35.530952 | 214 | 0.570944 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift
|
refs/heads/master
|
9-Array/9-Array/Sum.swift
|
mit
|
1
|
//
// Sum.swift
// 9-Array
//
// Created by FlyElephant on 17/1/13.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class Sum {
//求1+2+…+n,要求不能使用乘除法、for、while、if、else...
//题目:求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C).
func sumNumber(n:Int)->Int {
guard n > 0 else {
return 0
}
return n + sumNumber(n: n-1)
}
// var sum:Int = 0;
//n > 0 && (sum = n + sumNumber(n - 1))
//return sum
//var sum:Int = 0;
//n == 0 || (sum = n + sumNumber(n - 1))
//return sum
//不用加减乘除做加法
//题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号.
func add(num1:Int,num2:Int) -> Int {
var a:Int = num1
var b:Int = num2
while b != 0 {
let temp:Int = a ^ b
b = (a & b) << 1
a = temp
}
return a
}
}
|
325d395c849e13368ef21a1c1af5db5c
| 20.604651 | 78 | 0.471475 | false | false | false | false |
Obisoft2017/BeautyTeamiOS
|
refs/heads/master
|
BeautyTeam/BeautyTeam/TeamUserRelation.swift
|
apache-2.0
|
1
|
//
// TeamUserRelation.swift
// BeautyTeam
//
// Created by Carl Lee on 4/16/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import Foundation
class TeamUserRelation: InitialProtocol {
var teamUserRelationId: Int!
var groupTaskTaskId: Int!
var obisoftUserId: String!
required init(rawData: [String : AnyObject?]) {
guard let teamUserRelationId = rawData["TU_RelationId"] as? Int else {
fatalError()
}
guard let groupTaskTaskId = rawData["GroupTaskTaskId"] as? Int else {
fatalError()
}
guard let obisoftUserId = rawData["ObisoftUserId"] as? String else {
fatalError()
}
self.teamUserRelationId = teamUserRelationId
self.groupTaskTaskId = groupTaskTaskId
self.obisoftUserId = obisoftUserId
}
}
|
0b7ef20cfcc5592abadf408b8af42331
| 27.290323 | 78 | 0.640821 | false | false | false | false |
frootloops/swift
|
refs/heads/master
|
test/SILGen/functions.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
import Swift // just for Optional
func markUsed<T>(_ t: T) {}
typealias Int = Builtin.Int64
typealias Int64 = Builtin.Int64
typealias Bool = Builtin.Int1
var zero = getInt()
func getInt() -> Int { return zero }
func standalone_function(_ x: Int, _ y: Int) -> Int {
return x
}
func higher_order_function(_ f: (_ x: Int, _ y: Int) -> Int, _ x: Int, _ y: Int) -> Int {
return f(x, y)
}
func higher_order_function2(_ f: (Int, Int) -> Int, _ x: Int, _ y: Int) -> Int {
return f(x, y)
}
struct SomeStruct {
// -- Constructors and methods are uncurried in 'self'
// -- Instance methods use 'method' cc
init(x:Int, y:Int) {}
mutating
func method(_ x: Int) {}
static func static_method(_ x: Int) {}
func generic_method<T>(_ x: T) {}
}
class SomeClass {
// -- Constructors and methods are uncurried in 'self'
// -- Instance methods use 'method' cc
// CHECK-LABEL: sil hidden @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass
// CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @trivial $@thick SomeClass.Type):
// CHECK-LABEL: sil hidden @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Builtin.Int64, Builtin.Int64, @owned SomeClass) -> @owned SomeClass
// CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @owned $SomeClass):
init(x:Int, y:Int) {}
// CHECK-LABEL: sil hidden @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed SomeClass) -> ()
// CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @guaranteed $SomeClass):
func method(_ x: Int) {}
// CHECK-LABEL: sil hidden @_T09functions9SomeClassC13static_method{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Builtin.Int64, @thick SomeClass.Type) -> ()
// CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $@thick SomeClass.Type):
class func static_method(_ x: Int) {}
var someProperty: Int {
get {
return zero
}
set {}
}
subscript(x:Int, y:Int) -> Int {
get {
return zero
}
set {}
}
func generic<T>(_ x: T) -> T {
return x
}
}
func SomeClassWithBenefits() -> SomeClass.Type {
return SomeClass.self
}
protocol SomeProtocol {
func method(_ x: Int)
static func static_method(_ x: Int)
}
struct ConformsToSomeProtocol : SomeProtocol {
func method(_ x: Int) { }
static func static_method(_ x: Int) { }
}
class SomeGeneric<T> {
init() { }
func method(_ x: T) -> T { return x }
func generic<U>(_ x: U) -> U { return x }
}
// CHECK-LABEL: sil hidden @_T09functions5calls{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> ()
func calls(_ i:Int, j:Int, k:Int) {
var i = i
var j = j
var k = k
// CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @trivial $Builtin.Int64):
// CHECK: [[IBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[IADDR:%.*]] = project_box [[IBOX]]
// CHECK: [[JBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[JADDR:%.*]] = project_box [[JBOX]]
// CHECK: [[KBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[KADDR:%.*]] = project_box [[KBOX]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: apply [[FUNC]]([[I]], [[J]])
standalone_function(i, j)
// -- Curry 'self' onto struct method argument lists.
// CHECK: [[ST_ADDR:%.*]] = alloc_box ${ var SomeStruct }
// CHECK: [[METATYPE:%.*]] = metatype $@thin SomeStruct.Type
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%.*]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%.*]] = load [trivial] [[READJ]]
// CHECK: [[CTOR:%.*]] = function_ref @_T09functions10SomeStructV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct
// CHECK: apply [[CTOR]]([[I]], [[J]], [[METATYPE]]) : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct
var st = SomeStruct(x: i, y: j)
// -- Use of unapplied struct methods as values.
// CHECK: [[THUNK:%.*]] = function_ref @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F
// CHECK: [[THUNK_THICK:%.*]] = thin_to_thick_function [[THUNK]]
var stm1 = SomeStruct.method
stm1(&st)(i)
// -- Curry 'self' onto method argument lists dispatched using class_method.
// CHECK: [[CBOX:%[0-9]+]] = alloc_box ${ var SomeClass }
// CHECK: [[CADDR:%.*]] = project_box [[CBOX]]
// CHECK: [[META:%[0-9]+]] = metatype $@thick SomeClass.Type
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass
// CHECK: [[C:%[0-9]+]] = apply [[FUNC]]([[I]], [[J]], [[META]])
var c = SomeClass(x: i, y: j)
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.method!1
// CHECK: apply [[METHOD]]([[I]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
c.method(i)
// -- Curry 'self' onto unapplied methods dispatched using class_method.
// CHECK: [[METHOD_CURRY_THUNK:%.*]] = function_ref @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[METHOD_CURRY_THUNK]]
var cm1 = SomeClass.method(c)
cm1(i)
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.method!1
// CHECK: apply [[METHOD]]([[I]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
SomeClass.method(c)(i)
// -- Curry the Type onto static method argument lists.
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[META:%.*]] = value_metatype $@thick SomeClass.Type, [[C]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[META]] : {{.*}}, #SomeClass.static_method!1
// CHECK: apply [[METHOD]]([[I]], [[META]])
type(of: c).static_method(i)
// -- Curry property accesses.
// -- FIXME: class_method-ify class getters.
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[GETTER:%[0-9]+]] = class_method {{.*}} : $SomeClass, #SomeClass.someProperty!getter.1
// CHECK: apply [[GETTER]]([[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
i = c.someProperty
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[SETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.someProperty!setter.1 : (SomeClass) -> (Builtin.Int64) -> ()
// CHECK: apply [[SETTER]]([[I]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
c.someProperty = i
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[READK:%.*]] = begin_access [read] [unknown] [[KADDR]]
// CHECK: [[K:%[0-9]+]] = load [trivial] [[READK]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[GETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.subscript!getter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64) -> Builtin.Int64, $@convention(method) (Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> Builtin.Int64
// CHECK: apply [[GETTER]]([[J]], [[K]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
i = c[j, k]
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[READK:%.*]] = begin_access [read] [unknown] [[KADDR]]
// CHECK: [[K:%[0-9]+]] = load [trivial] [[READK]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[SETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.subscript!setter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> (), $@convention(method) (Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> ()
// CHECK: apply [[SETTER]]([[K]], [[I]], [[J]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
c[i, j] = k
// -- Curry the projected concrete value in an existential (or its Type)
// -- onto protocol type methods dispatched using protocol_method.
// CHECK: [[PBOX:%[0-9]+]] = alloc_box ${ var SomeProtocol }
// CHECK: [[PADDR:%.*]] = project_box [[PBOX]]
var p : SomeProtocol = ConformsToSomeProtocol()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PADDR]]
// CHECK: [[TEMP:%.*]] = alloc_stack $SomeProtocol
// CHECK: copy_addr [[READ]] to [initialization] [[TEMP]]
// CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1
// CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
p.method(i)
// CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[PADDR:%.*]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1
// CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]])
var sp : SomeProtocol = ConformsToSomeProtocol()
sp.method(i)
// FIXME: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED:@opened(.*) SomeProtocol]], #SomeProtocol.static_method!1
// FIXME: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// FIXME: apply [[PMETHOD]]([[I]], [[PMETA]])
// Needs existential metatypes
//type(of: p).static_method(i)
// -- Use an apply or partial_apply instruction to bind type parameters of a generic.
// CHECK: [[GBOX:%[0-9]+]] = alloc_box ${ var SomeGeneric<Builtin.Int64> }
// CHECK: [[GADDR:%.*]] = project_box [[GBOX]]
// CHECK: [[META:%[0-9]+]] = metatype $@thick SomeGeneric<Builtin.Int64>.Type
// CHECK: [[CTOR_GEN:%[0-9]+]] = function_ref @_T09functions11SomeGenericC{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@thick SomeGeneric<τ_0_0>.Type) -> @owned SomeGeneric<τ_0_0>
// CHECK: apply [[CTOR_GEN]]<Builtin.Int64>([[META]])
var g = SomeGeneric<Builtin.Int64>()
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[READG:%.*]] = begin_access [read] [unknown] [[GADDR]]
// CHECK: [[G:%[0-9]+]] = load [copy] [[READG]]
// CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]]
// CHECK: [[TMPI:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_G]] : {{.*}}, #SomeGeneric.method!1
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPI]], [[BORROWED_G]])
// CHECK: end_borrow [[BORROWED_G]] from [[G]]
// CHECK: destroy_value [[G]]
g.method(i)
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[READG:%.*]] = begin_access [read] [unknown] [[GADDR]]
// CHECK: [[G:%[0-9]+]] = load [copy] [[READG]]
// CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]]
// CHECK: [[TMPJ:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_G]] : {{.*}}, #SomeGeneric.generic!1
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPJ]], [[BORROWED_G]])
// CHECK: end_borrow [[BORROWED_G]] from [[G]]
// CHECK: destroy_value [[G]]
g.generic(j)
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]]
// CHECK: [[C:%[0-9]+]] = load [copy] [[READC]]
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[TMPK:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.generic!1
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPK]], [[BORROWED_C]])
// CHECK: end_borrow [[BORROWED_C]] from [[C]]
// CHECK: destroy_value [[C]]
c.generic(k)
// FIXME: curried generic entry points
//var gm1 = g.method
//gm1(i)
//var gg1 : (Int) -> Int = g.generic
//gg1(j)
//var cg1 : (Int) -> Int = c.generic
//cg1(k)
// SIL-level "thin" function values need to be able to convert to
// "thick" function values when stored, returned, or passed as arguments.
// CHECK: [[FBOX:%[0-9]+]] = alloc_box ${ var @callee_guaranteed (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 }
// CHECK: [[FADDR:%.*]] = project_box [[FBOX]]
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: store [[FUNC_THICK]] to [init] [[FADDR]]
var f = standalone_function
// CHECK: [[READF:%.*]] = begin_access [read] [unknown] [[FADDR]]
// CHECK: [[F:%[0-9]+]] = load [copy] [[READF]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[BORROW:%.*]] = begin_borrow [[F]]
// CHECK: apply [[BORROW]]([[I]], [[J]])
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value [[F]]
f(i, j)
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: [[CONVERT:%.*]] = convert_function [[FUNC_THICK]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[HOF:%[0-9]+]] = function_ref @_T09functions21higher_order_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}}
// CHECK: apply [[HOF]]([[CONVERT]], [[I]], [[J]])
higher_order_function(standalone_function, i, j)
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%.*]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: [[CONVERT:%.*]] = convert_function [[FUNC_THICK]]
// CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]]
// CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]]
// CHECK: [[HOF2:%[0-9]+]] = function_ref @_T09functions22higher_order_function2{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}}
// CHECK: apply [[HOF2]]([[CONVERT]], [[I]], [[J]])
higher_order_function2(standalone_function, i, j)
}
// -- Curried entry points
// CHECK-LABEL: sil shared [thunk] @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@inout SomeStruct) -> @owned @callee_guaranteed (Builtin.Int64) -> () {
// CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @inout SomeStruct) -> (){{.*}} // user: %2
// CHECK: [[CURRIED:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]]
// CHECK: return [[CURRIED]]
// CHECK-LABEL: sil shared [thunk] @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@owned SomeClass) -> @owned @callee_guaranteed (Builtin.Int64) -> ()
// CHECK: bb0(%0 : @owned $SomeClass):
// CHECK: class_method %0 : $SomeClass, #SomeClass.method!1 : (SomeClass) -> (Builtin.Int64) -> ()
// CHECK: %2 = partial_apply [callee_guaranteed] %1(%0)
// CHECK: return %2
func return_func() -> (_ x: Builtin.Int64, _ y: Builtin.Int64) -> Builtin.Int64 {
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: return [[FUNC_THICK]]
return standalone_function
}
func standalone_generic<T>(_ x: T, y: T) -> T { return x }
// CHECK-LABEL: sil hidden @_T09functions14return_genericBi64_Bi64__Bi64_tcyF
func return_generic() -> (_ x:Builtin.Int64, _ y:Builtin.Int64) -> Builtin.Int64 {
// CHECK: [[GEN:%.*]] = function_ref @_T09functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0
// CHECK: [[SPEC:%.*]] = partial_apply [callee_guaranteed] [[GEN]]<Builtin.Int64>()
// CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, @guaranteed @callee_guaranteed (@in Builtin.Int64, @in Builtin.Int64) -> @out Builtin.Int64) -> Builtin.Int64
// CHECK: [[T0:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[SPEC]])
// CHECK: return [[T0]]
return standalone_generic
}
// CHECK-LABEL: sil hidden @_T09functions20return_generic_tuple{{[_0-9a-zA-Z]*}}F
func return_generic_tuple()
-> (_ x: (Builtin.Int64, Builtin.Int64), _ y: (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) {
// CHECK: [[GEN:%.*]] = function_ref @_T09functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0
// CHECK: [[SPEC:%.*]] = partial_apply [callee_guaranteed] [[GEN]]<(Builtin.Int64, Builtin.Int64)>()
// CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed @callee_guaranteed (@in (Builtin.Int64, Builtin.Int64), @in (Builtin.Int64, Builtin.Int64)) -> @out (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64)
// CHECK: [[T0:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[SPEC]])
// CHECK: return [[T0]]
return standalone_generic
}
// CHECK-LABEL: sil hidden @_T09functions16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
func testNoReturnAttr() -> Never {}
// CHECK-LABEL: sil hidden @_T09functions20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in T) -> Never
func testNoReturnAttrPoly<T>(_ x: T) -> Never {}
// CHECK-LABEL: sil hidden @_T09functions21testNoReturnAttrParam{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Never) -> ()
func testNoReturnAttrParam(_ fptr: () -> Never) -> () {}
// CHECK-LABEL: sil hidden [transparent] @_T09functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
@_transparent func testTransparent(_ x: Bool) -> Bool {
return x
}
// CHECK-LABEL: sil hidden @_T09functions16applyTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 {
func applyTransparent(_ x: Bool) -> Bool {
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
// CHECK: apply [[FUNC]]({{%[0-9]+}}) : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
return testTransparent(x)
}
// CHECK-LABEL: sil hidden [noinline] @_T09functions15noinline_calleeyyF : $@convention(thin) () -> ()
@inline(never)
func noinline_callee() {}
// CHECK-LABEL: sil hidden [always_inline] @_T09functions20always_inline_calleeyyF : $@convention(thin) () -> ()
@inline(__always)
func always_inline_callee() {}
// CHECK-LABEL: sil [serialized] [always_inline] @_T09functions27public_always_inline_calleeyyF : $@convention(thin) () -> ()
@inline(__always)
public func public_always_inline_callee() {}
protocol AlwaysInline {
func alwaysInlined()
}
// CHECK-LABEL: sil hidden [always_inline] @_T09functions19AlwaysInlinedMemberV06alwaysC0{{[_0-9a-zA-Z]*}}F : $@convention(method) (AlwaysInlinedMember) -> () {
// protocol witness for functions.AlwaysInline.alwaysInlined <A : functions.AlwaysInline>(functions.AlwaysInline.Self)() -> () in conformance functions.AlwaysInlinedMember : functions.AlwaysInline in functions
// CHECK-LABEL: sil private [transparent] [thunk] [always_inline] @_T09functions19AlwaysInlinedMemberVAA0B6InlineA2aDP06alwaysC0{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AlwaysInline) (@in_guaranteed AlwaysInlinedMember) -> () {
struct AlwaysInlinedMember : AlwaysInline {
@inline(__always)
func alwaysInlined() {}
}
// CHECK-LABEL: sil hidden [Onone] @_T09functions10onone_funcyyF : $@convention(thin) () -> ()
@_optimize(none)
func onone_func() {}
// CHECK-LABEL: sil hidden [Ospeed] @_T09functions11ospeed_funcyyF : $@convention(thin) () -> ()
@_optimize(speed)
func ospeed_func() {}
// CHECK-LABEL: sil hidden [Osize] @_T09functions10osize_funcyyF : $@convention(thin) () -> ()
@_optimize(size)
func osize_func() {}
struct OptmodeTestStruct {
// CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructV3fooyyF :
@_optimize(speed)
func foo() { }
// CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructVACycfC :
@_optimize(speed)
init() { }
// CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructV1xBi64_vg :
@_optimize(speed)
var x: Int { return getInt() }
// CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructVBi64_Bi64_cig :
@_optimize(speed)
subscript(l: Int) -> Int { return getInt() }
}
// CHECK-LABEL: sil hidden [_semantics "foo"] @_T09functions9semanticsyyF : $@convention(thin) () -> ()
@_semantics("foo")
func semantics() {}
// <rdar://problem/17828355> curried final method on a class crashes in irgen
final class r17828355Class {
func method(_ x : Int) {
var a : r17828355Class
var fn = a.method // currying a final method.
}
}
// The curry thunk for the method should not include a class_method instruction.
// CHECK-LABEL: sil shared [thunk] @_T09functions14r17828355ClassC6method
// CHECK: bb0(%0 : @owned $r17828355Class):
// CHECK-NEXT: // function_ref functions.r17828355Class.method(Builtin.Int64) -> ()
// CHECK-NEXT: %1 = function_ref @_T09functions14r17828355ClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> ()
// CHECK-NEXT: partial_apply [callee_guaranteed] %1(%0) : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> ()
// CHECK-NEXT: return
// <rdar://problem/19981118> Swift 1.2 beta 2: Closures nested in closures copy, rather than reference, captured vars.
func noescapefunc(f: () -> ()) {}
func escapefunc(_ f : @escaping () -> ()) {}
func testNoescape() {
// "a" must be captured by-box into noescapefunc because the inner closure
// could escape it.
var a = 0
noescapefunc {
escapefunc { a = 42 }
}
markUsed(a)
}
// CHECK-LABEL: functions.testNoescape() -> ()
// CHECK-NEXT: sil hidden @_T09functions12testNoescapeyyF : $@convention(thin) () -> ()
// CHECK: function_ref closure #1 () -> () in functions.testNoescape() -> ()
// CHECK-NEXT: function_ref @_T09functions12testNoescapeyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> ()
// Despite being a noescape closure, this needs to capture 'a' by-box so it can
// be passed to the capturing closure.closure
// CHECK: closure #1 () -> () in functions.testNoescape() -> ()
// CHECK-NEXT: sil private @_T09functions12testNoescapeyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
func testNoescape2() {
// "a" must be captured by-box into noescapefunc because the inner closure
// could escape it. This also checks for when the outer closure captures it
// in a way that could be used with escape: the union of the two requirements
// doesn't allow a by-address capture.
var a = 0
noescapefunc {
escapefunc { a = 42 }
markUsed(a)
}
markUsed(a)
}
// CHECK-LABEL: sil hidden @_T09functions13testNoescape2yyF : $@convention(thin) () -> () {
// CHECK: // closure #1 () -> () in functions.testNoescape2() -> ()
// CHECK-NEXT: sil private @_T09functions13testNoescape2yyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: // closure #1 () -> () in closure #1 () -> () in functions.testNoescape2() -> ()
// CHECK-NEXT: sil private @_T09functions13testNoescape2yyFyycfU_yycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
enum PartialApplyEnumPayload<T, U> {
case Left(T)
case Right(U)
}
struct S {}
struct C {}
func partialApplyEnumCases(_ x: S, y: C) {
let left = PartialApplyEnumPayload<S, C>.Left
let left2 = left(S())
let right = PartialApplyEnumPayload<S, C>.Right
let right2 = right(C())
}
// CHECK-LABEL: sil shared [transparent] [thunk] @_T09functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F
// CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]]<T, U>(%0)
// CHECK: return [[CLOSURE]]
// CHECK-LABEL: sil shared [transparent] [thunk] @_T09functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F
// CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]]<T, U>(%0)
// CHECK: return [[CLOSURE]]
|
872d9342c1019541d6e928c82c259e03
| 46.528302 | 308 | 0.612328 | false | false | false | false |
debugsquad/Hyperborea
|
refs/heads/master
|
Hyperborea/View/Search/VSearchBar.swift
|
mit
|
1
|
import UIKit
class VSearchBar:UIView
{
private(set) weak var viewField:VSearchBarField!
private weak var controller:CSearch!
private weak var border:VBorder!
let kFieldTop:CGFloat = 20
private let kBorderHeight:CGFloat = 1
private let kFieldMarginHorizontal:CGFloat = 10
init(controller:CSearch)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1))
self.border = border
let viewField:VSearchBarField = VSearchBarField(
controller:controller)
self.viewField = viewField
addSubview(border)
addSubview(viewField)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.topToTop(
view:viewField,
toView:self,
constant:kFieldTop)
NSLayoutConstraint.bottomToBottom(
view:viewField,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:viewField,
toView:self,
margin:kFieldMarginHorizontal)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: public
func beginEditing()
{
border.backgroundColor = UIColor.black
}
func endEditing()
{
border.backgroundColor = UIColor(white:0, alpha:0.1)
}
}
|
247a28e4a03f316618efa7fe13676945
| 25.101449 | 71 | 0.599667 | false | false | false | false |
airspeedswift/swift
|
refs/heads/master
|
test/AutoDiff/Sema/derivative_attr_type_checking.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s
// Swift.AdditiveArithmetic:3:17: note: cannot yet register derivative default implementation for protocol requirements
import _Differentiation
// Dummy `Differentiable`-conforming type.
struct DummyTangentVector: Differentiable & AdditiveArithmetic {
static var zero: Self { Self() }
static func + (_: Self, _: Self) -> Self { Self() }
static func - (_: Self, _: Self) -> Self { Self() }
typealias TangentVector = Self
}
// Test top-level functions.
func id(_ x: Float) -> Float {
return x
}
@derivative(of: id)
func jvpId(x: Float) -> (value: Float, differential: (Float) -> (Float)) {
return (x, { $0 })
}
@derivative(of: id, wrt: x)
func vjpIdExplicitWrt(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
func generic<T: Differentiable>(_ x: T, _ y: T) -> T {
return x
}
@derivative(of: generic)
func jvpGeneric<T: Differentiable>(x: T, y: T) -> (
value: T, differential: (T.TangentVector, T.TangentVector) -> T.TangentVector
) {
return (x, { $0 + $1 })
}
@derivative(of: generic)
func vjpGenericExtraGenericRequirements<T: Differentiable & FloatingPoint>(
x: T, y: T
) -> (value: T, pullback: (T) -> (T, T)) where T == T.TangentVector {
return (x, { ($0, $0) })
}
// Test `wrt` parameter clauses.
func add(x: Float, y: Float) -> Float {
return x + y
}
@derivative(of: add, wrt: x) // ok
func vjpAddWrtX(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
@derivative(of: add, wrt: (x, y)) // ok
func vjpAddWrtXY(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// Test index-based `wrt` parameters.
func subtract(x: Float, y: Float) -> Float {
return x - y
}
@derivative(of: subtract, wrt: (0, y)) // ok
func vjpSubtractWrt0Y(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
@derivative(of: subtract, wrt: (1)) // ok
func vjpSubtractWrt1(x: Float, y: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x - y, { $0 })
}
// Test invalid original function.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test `@derivative` attribute where `value:` result does not conform to `Differentiable`.
// Invalid original function should be diagnosed first.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound2(_ x: Float) -> (value: Int, pullback: (Float) -> Float) {
fatalError()
}
// Test incorrect `@derivative` declaration type.
// expected-note @+2 {{'incorrectDerivativeType' defined here}}
// expected-note @+1 {{candidate global function does not have expected type '(Int) -> Int'}}
func incorrectDerivativeType(_ x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:' and second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func jvpResultIncorrect(x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectFirstLabel(x: Float) -> (Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectSecondLabel(x: Float) -> (value: Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{referenced declaration 'incorrectDerivativeType' could not be resolved}}
@derivative(of: incorrectDerivativeType)
func vjpResultNotDifferentiable(x: Int) -> (
value: Int, pullback: (Int) -> Int
) {
return (x, { $0 })
}
// expected-error @+2 {{function result's 'pullback' type does not match 'incorrectDerivativeType'}}
// expected-note @+3 {{'pullback' does not have expected type '(Float.TangentVector) -> Float.TangentVector' (aka '(Float) -> Float')}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectPullbackType(x: Float) -> (
value: Float, pullback: (Double) -> Double
) {
return (x, { $0 })
}
// Test invalid `wrt:` differentiation parameters.
func invalidWrtParam(_ x: Float, _ y: Float) -> Float {
return x
}
// expected-error @+1 {{unknown parameter name 'z'}}
@derivative(of: add, wrt: z)
func vjpUnknownParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (y, x))
func vjpParamOrderNotIncreasing(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: invalidWrtParam, wrt: self)
func vjpInvalidSelfParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{parameter index is larger than total number of parameters}}
@derivative(of: invalidWrtParam, wrt: 2)
func vjpSubtractWrt2(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, x))
func vjpSubtractWrt1x(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, 0))
func vjpSubtractWrt10(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
func noParameters() -> Float {
return 1
}
// expected-error @+1 {{'vjpNoParameters()' has no parameters to differentiate with respect to}}
@derivative(of: noParameters)
func vjpNoParameters() -> (value: Float, pullback: (Float) -> Float) {
return (1, { $0 })
}
func noDifferentiableParameters(x: Int) -> Float {
return 1
}
// expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
@derivative(of: noDifferentiableParameters)
func vjpNoDifferentiableParameters(x: Int) -> (
value: Float, pullback: (Float) -> Int
) {
return (1, { _ in 0 })
}
func functionParameter(_ fn: (Float) -> Float) -> Float {
return fn(1)
}
// expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '(Float) -> Float' does not conform to 'Differentiable'}}
@derivative(of: functionParameter, wrt: fn)
func vjpFunctionParameter(_ fn: (Float) -> Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (functionParameter(fn), { $0 })
}
// Test static methods.
protocol StaticMethod: Differentiable {
static func foo(_ x: Float) -> Float
static func generic<T: Differentiable>(_ x: T) -> T
}
extension StaticMethod {
static func foo(_ x: Float) -> Float { x }
static func generic<T: Differentiable>(_ x: T) -> T { x }
}
extension StaticMethod {
@derivative(of: foo)
static func jvpFoo(x: Float) -> (value: Float, differential: (Float) -> Float)
{
return (x, { $0 })
}
// Test qualified declaration name.
@derivative(of: StaticMethod.foo)
static func vjpFoo(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
@derivative(of: generic)
static func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: foo, wrt: (self, x))
static func vjpFooWrtSelf(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
}
// Test instance methods.
protocol InstanceMethod: Differentiable {
func foo(_ x: Self) -> Self
func generic<T: Differentiable>(_ x: T) -> Self
}
extension InstanceMethod {
// expected-note @+1 {{'foo' defined here}}
func foo(_ x: Self) -> Self { x }
// expected-note @+1 {{'generic' defined here}}
func generic<T: Differentiable>(_ x: T) -> Self { self }
}
extension InstanceMethod {
@derivative(of: foo)
func jvpFoo(x: Self) -> (
value: Self, differential: (TangentVector, TangentVector) -> (TangentVector)
) {
return (x, { $0 + $1 })
}
// Test qualified declaration name.
@derivative(of: InstanceMethod.foo, wrt: x)
func jvpFooWrtX(x: Self) -> (
value: Self, differential: (TangentVector) -> (TangentVector)
) {
return (x, { $0 })
}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> (TangentVector, T.TangentVector)
) {
return (self, { ($0, .zero) })
}
@derivative(of: generic, wrt: (self, x))
func jvpGenericWrt<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
// expected-error @+1 {{'self' parameter must come first in the parameter list}}
@derivative(of: generic, wrt: (x, self))
func jvpGenericWrtSelf<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
}
extension InstanceMethod {
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'foo'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)'}}
@derivative(of: foo)
func vjpFoo(x: Self) -> (
value: Self, pullback: (TangentVector) -> TangentVector
) {
return (x, { $0 })
}
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'generic'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, T.TangentVector)'}}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> T.TangentVector
) {
return (self, { _ in .zero })
}
}
// Test `@derivative` declaration with more constrained generic signature.
func req1<T>(_ x: T) -> T {
return x
}
@derivative(of: req1)
func vjpExtraConformanceConstraint<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
func req2<T, U>(_ x: T, _ y: U) -> T {
return x
}
@derivative(of: req2)
func vjpExtraConformanceConstraints<T: Differentiable, U: Differentiable>( _ x: T, _ y: U) -> (
value: T, pullback: (T) -> (T, U)
) where T == T.TangentVector, U == U.TangentVector, T: CustomStringConvertible {
return (x, { ($0, .zero) })
}
// Test `@derivative` declaration with extra same-type requirements.
func req3<T>(_ x: T) -> T {
return x
}
@derivative(of: req3)
func vjpSameTypeRequirementsGenericParametersAllConcrete<T>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) where T: Differentiable, T.TangentVector == Float {
return (x, { $0 })
}
struct Wrapper<T: Equatable>: Equatable {
var x: T
init(_ x: T) { self.x = x }
}
extension Wrapper: AdditiveArithmetic where T: AdditiveArithmetic {
static var zero: Self { .init(.zero) }
static func + (lhs: Self, rhs: Self) -> Self { .init(lhs.x + rhs.x) }
static func - (lhs: Self, rhs: Self) -> Self { .init(lhs.x - rhs.x) }
}
extension Wrapper: Differentiable where T: Differentiable, T == T.TangentVector {
typealias TangentVector = Wrapper<T.TangentVector>
}
extension Wrapper where T: Differentiable, T == T.TangentVector {
@derivative(of: init(_:))
static func vjpInit(_ x: T) -> (value: Self, pullback: (Wrapper<T>.TangentVector) -> (T)) {
fatalError()
}
}
// Test class methods.
class Super {
@differentiable
// expected-note @+1 {{candidate instance method is not defined in the current type context}}
func foo(_ x: Float) -> Float {
return x
}
@derivative(of: foo)
func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (foo(x), { v in v })
}
}
class Sub: Super {
// TODO(TF-649): Enable `@derivative` to override derivatives for original
// declaration defined in superclass.
// expected-error @+1 {{referenced declaration 'foo' could not be resolved}}
@derivative(of: foo)
override func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float)
{
return (foo(x), { v in v })
}
}
// Test non-`func` original declarations.
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Differentiable & AdditiveArithmetic
where T: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Struct<T.TangentVector>
mutating func move(along direction: TangentVector) {
x.move(along: direction.x)
}
}
class Class<T> {
var x: T
init(_ x: T) {
self.x = x
}
}
extension Class: Differentiable where T: Differentiable {}
// Test computed properties.
extension Struct {
var computedProperty: T {
get { x }
set { x = newValue }
_modify { yield &x }
}
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: computedProperty)
func vjpProperty() -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { v in .init(x: v) })
}
@derivative(of: computedProperty.get)
func jvpProperty() -> (value: T, differential: (TangentVector) -> T.TangentVector) {
fatalError()
}
@derivative(of: computedProperty.set)
mutating func vjpPropertySetter(_ newValue: T) -> (
value: (), pullback: (inout TangentVector) -> T.TangentVector
) {
fatalError()
}
// expected-error @+1 {{cannot register derivative for _modify accessor}}
@derivative(of: computedProperty._modify)
mutating func vjpPropertyModify(_ newValue: T) -> (
value: (), pullback: (inout TangentVector) -> T.TangentVector
) {
fatalError()
}
}
// Test initializers.
extension Struct {
init(_ x: Float) {}
init(_ x: T, y: Float) {}
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: init)
static func vjpInit(_ x: Float) -> (
value: Struct, pullback: (TangentVector) -> Float
) {
return (.init(x), { _ in .zero })
}
@derivative(of: init(_:y:))
static func vjpInit2(_ x: T, _ y: Float) -> (
value: Struct, pullback: (TangentVector) -> (T.TangentVector, Float)
) {
return (.init(x, y: y), { _ in (.zero, .zero) })
}
}
// Test subscripts.
extension Struct {
subscript() -> Float {
get { 1 }
set {}
}
subscript(float float: Float) -> Float {
get { 1 }
set {}
}
// expected-note @+1 {{candidate subscript does not have a setter}}
subscript<T: Differentiable>(x: T) -> T { x }
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: subscript.get)
func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript)
func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript().get)
func jvpSubscriptGetter() -> (value: Float, differential: (TangentVector) -> Float) {
return (1, { _ in .zero })
}
@derivative(of: subscript(float:).get, wrt: self)
func vjpSubscriptLabeledGetter(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript(float:), wrt: self)
func vjpSubscriptLabeled(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript(float:).get)
func jvpSubscriptLabeledGetter(float: Float) -> (value: Float, differential: (TangentVector, Float) -> Float) {
return (1, { (_,_) in 1})
}
@derivative(of: subscript(_:).get, wrt: self)
func vjpSubscriptGenericGetter<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript(_:), wrt: self)
func vjpSubscriptGeneric<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { _ in .zero })
}
@derivative(of: subscript.set)
mutating func vjpSubscriptSetter(_ newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> Float
) {
fatalError()
}
@derivative(of: subscript().set)
mutating func jvpSubscriptSetter(_ newValue: Float) -> (
value: (), differential: (inout TangentVector, Float) -> ()
) {
fatalError()
}
@derivative(of: subscript(float:).set)
mutating func vjpSubscriptLabeledSetter(float: Float, newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> (Float, Float)
) {
fatalError()
}
@derivative(of: subscript(float:).set)
mutating func jvpSubscriptLabeledSetter(float: Float, _ newValue: Float) -> (
value: (), differential: (inout TangentVector, Float, Float) -> Void
) {
fatalError()
}
// Error: original subscript has no setter.
// expected-error @+1 {{referenced declaration 'subscript(_:)' could not be resolved}}
@derivative(of: subscript(_:).set, wrt: self)
mutating func vjpSubscriptGeneric_NoSetter<T: Differentiable>(x: T) -> (
value: T, pullback: (T.TangentVector) -> TangentVector
) {
return (x, { _ in .zero })
}
}
extension Class {
subscript() -> Float {
get { 1 }
// expected-note @+1 {{'subscript()' declared here}}
set {}
}
}
extension Class where T: Differentiable {
@derivative(of: subscript.get)
func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// expected-error @+2 {{a derivative already exists for '_'}}
// expected-note @-6 {{other attribute declared here}}
@derivative(of: subscript)
func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
// FIXME(SR-13096): Enable derivative registration for class property/subscript setters.
// This requires changing derivative type calculation rules for functions with
// class-typed parameters. We need to assume that all functions taking
// class-typed operands may mutate those operands.
// expected-error @+1 {{cannot yet register derivative for class property or subscript setters}}
@derivative(of: subscript.set)
func vjpSubscriptSetter(_ newValue: Float) -> (
value: (), pullback: (inout TangentVector) -> Float
) {
fatalError()
}
}
// Test duplicate `@derivative` attribute.
func duplicate(_ x: Float) -> Float { x }
// expected-note @+1 {{other attribute declared here}}
@derivative(of: duplicate)
func jvpDuplicate1(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// expected-error @+1 {{a derivative already exists for 'duplicate'}}
@derivative(of: duplicate)
func jvpDuplicate2(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// Test invalid original declaration kind.
// expected-note @+1 {{candidate var does not have a getter}}
var globalVariable: Float
// expected-error @+1 {{referenced declaration 'globalVariable' could not be resolved}}
@derivative(of: globalVariable)
func invalidOriginalDeclaration(x: Float) -> (
value: Float, differential: (Float) -> (Float)
) {
return (x, { $0 })
}
// Test ambiguous original declaration.
protocol P1 {}
protocol P2 {}
// expected-note @+1 {{candidate global function found here}}
func ambiguous<T: P1>(_ x: T) -> T { x }
// expected-note @+1 {{candidate global function found here}}
func ambiguous<T: P2>(_ x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'ambiguous' is ambiguous}}
@derivative(of: ambiguous)
func jvpAmbiguous<T: P1 & P2 & Differentiable>(x: T)
-> (value: T, differential: (T.TangentVector) -> (T.TangentVector))
{
return (x, { $0 })
}
// Test no valid original declaration.
// Original declarations are invalid because they have extra generic
// requirements unsatisfied by the `@derivative` function.
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: BinaryFloatingPoint>(x: T) -> T { x }
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: CustomStringConvertible>(x: T) -> T { x }
// expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}}
func invalid<T: FloatingPoint>(x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'invalid' could not be resolved}}
@derivative(of: invalid)
func jvpInvalid<T: Differentiable>(x: T) -> (
value: T, differential: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
// Test invalid derivative type context: instance vs static method mismatch.
struct InvalidTypeContext<T: Differentiable> {
// expected-note @+1 {{candidate static method does not have type equal to or less constrained than '<T where T : Differentiable> (InvalidTypeContext<T>) -> (T) -> T'}}
static func staticMethod(_ x: T) -> T { x }
// expected-error @+1 {{referenced declaration 'staticMethod' could not be resolved}}
@derivative(of: staticMethod)
func jvpStatic(_ x: T) -> (
value: T, differential: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
}
// Test stored property original declaration.
struct HasStoredProperty {
// expected-note @+1 {{'stored' declared here}}
var stored: Float
}
extension HasStoredProperty: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Self
}
extension HasStoredProperty {
// expected-error @+1 {{cannot register derivative for stored property 'stored'}}
@derivative(of: stored)
func vjpStored() -> (value: Float, pullback: (Float) -> TangentVector) {
return (stored, { _ in .zero })
}
}
// Test derivative registration for protocol requirements. Currently unsupported.
// TODO(TF-982): Lift this restriction and add proper support.
protocol ProtocolRequirementDerivative {
// expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}}
func requirement(_ x: Float) -> Float
}
extension ProtocolRequirementDerivative {
// expected-error @+1 {{referenced declaration 'requirement' could not be resolved}}
@derivative(of: requirement)
func vjpRequirement(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
}
// Test `inout` parameters.
func multipleSemanticResults(_ x: inout Float) -> Float {
return x
}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(x: inout Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (multipleSemanticResults(&x), { $0 })
}
struct InoutParameters: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
}
extension InoutParameters {
// expected-note @+1 4 {{'staticMethod(_:rhs:)' defined here}}
static func staticMethod(_ lhs: inout Self, rhs: Self) {}
// Test wrt `inout` parameter.
@derivative(of: staticMethod)
static func vjpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func vjpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod)
static func jvpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func jvpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` parameter.
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (inout TangentVector) -> TangentVector
) { fatalError() }
}
extension InoutParameters {
// expected-note @+1 4 {{'mutatingMethod' defined here}}
mutating func mutatingMethod(_ other: Self) {}
// Test wrt `inout` `self` parameter.
@derivative(of: mutatingMethod)
mutating func vjpWrtInout(_ other: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func vjpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod)
mutating func jvpWrtInout(_ other: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func jvpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` `self` parameter.
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInout(_ other: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInout(_ other: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
}
// Test no semantic results.
func noSemanticResults(_ x: Float) {}
// expected-error @+1 {{cannot differentiate void function 'noSemanticResults'}}
@derivative(of: noSemanticResults)
func vjpNoSemanticResults(_ x: Float) -> (value: Void, pullback: Void) {}
// Test multiple semantic results.
extension InoutParameters {
func multipleSemanticResults(_ x: inout Float) -> Float { x }
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(_ x: inout Float) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
func inoutVoid(_ x: Float, _ void: inout Void) -> Float {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: inoutVoid)
func vjpInoutVoidParameter(_ x: Float, _ void: inout Void) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
}
// Test original/derivative function `inout` parameter mismatches.
extension InoutParameters {
// expected-note @+1 {{candidate instance method does not have expected type '(InoutParameters) -> (inout Float) -> Void'}}
func inoutParameterMismatch(_ x: Float) {}
// expected-error @+1 {{referenced declaration 'inoutParameterMismatch' could not be resolved}}
@derivative(of: inoutParameterMismatch)
func vjpInoutParameterMismatch(_ x: inout Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
// expected-note @+1 {{candidate instance method does not have expected type '(inout InoutParameters) -> (Float) -> Void'}}
func mutatingMismatch(_ x: Float) {}
// expected-error @+1 {{referenced declaration 'mutatingMismatch' could not be resolved}}
@derivative(of: mutatingMismatch)
mutating func vjpMutatingMismatch(_ x: Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
}
// Test cross-file derivative registration.
extension FloatingPoint where Self: Differentiable {
@usableFromInline
@derivative(of: rounded)
func vjpRounded() -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector)
) {
fatalError()
}
}
extension Differentiable where Self: AdditiveArithmetic {
// expected-error @+1 {{referenced declaration '+' could not be resolved}}
@derivative(of: +)
static func vjpPlus(x: Self, y: Self) -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)
) {
return (x + y, { v in (v, v) })
}
}
extension AdditiveArithmetic
where Self: Differentiable, Self == Self.TangentVector {
// expected-error @+1 {{referenced declaration '+' could not be resolved}}
@derivative(of: +)
func vjpPlusInstanceMethod(x: Self, y: Self) -> (
value: Self, pullback: (Self) -> (Self, Self)
) {
return (x + y, { v in (v, v) })
}
}
// Test derivatives of default implementations.
protocol HasADefaultImplementation {
func req(_ x: Float) -> Float
}
extension HasADefaultImplementation {
func req(_ x: Float) -> Float { x }
// ok
@derivative(of: req)
func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// Test default derivatives of requirements.
protocol HasADefaultDerivative {
// expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}}
func req(_ x: Float) -> Float
}
extension HasADefaultDerivative {
// TODO(TF-982): Support default derivatives for protocol requirements.
// expected-error @+1 {{referenced declaration 'req' could not be resolved}}
@derivative(of: req)
func vjpReq(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// MARK: - Original function visibility = derivative function visibility
public func public_original_public_derivative(_ x: Float) -> Float { x }
@derivative(of: public_original_public_derivative)
public func _public_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_usablefrominline_derivative(_ x: Float) -> Float { x }
@usableFromInline
@derivative(of: public_original_usablefrominline_derivative)
func _public_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_internal_derivative(_ x: Float) -> Float { x }
@derivative(of: internal_original_internal_derivative)
func _internal_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_private_derivative(_ x: Float) -> Float { x }
@derivative(of: private_original_private_derivative)
private func _private_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_fileprivate_derivative(_ x: Float) -> Float { x }
@derivative(of: fileprivate_original_fileprivate_derivative)
fileprivate func _fileprivate_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_usablefrominline_derivative(_ x: Float) -> Float { x }
@usableFromInline
@derivative(of: internal_original_usablefrominline_derivative)
func _internal_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_inlinable_derivative(_ x: Float) -> Float { x }
@inlinable
@derivative(of: internal_original_inlinable_derivative)
func _internal_original_inlinable_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_alwaysemitintoclient_derivative(_ x: Float) -> Float { x }
@_alwaysEmitIntoClient
@derivative(of: internal_original_alwaysemitintoclient_derivative)
func _internal_original_alwaysemitintoclient_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility < derivative function visibility
@usableFromInline
func usablefrominline_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_usablefrominline_original_public_derivative' is public, but original function 'usablefrominline_original_public_derivative' is internal}}
@derivative(of: usablefrominline_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _usablefrominline_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_public_derivative' is public, but original function 'internal_original_public_derivative' is internal}}
@derivative(of: internal_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _internal_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_usablefrominline_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_usablefrominline_derivative' is internal, but original function 'private_original_usablefrominline_derivative' is private}}
@derivative(of: private_original_usablefrominline_derivative)
@usableFromInline
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-1=private }}
func _private_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_public_derivative' is public, but original function 'private_original_public_derivative' is private}}
@derivative(of: private_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-7=private}}
public func _private_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_internal_derivative' is internal, but original function 'private_original_internal_derivative' is private}}
@derivative(of: private_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}}
func _private_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_fileprivate_original_private_derivative' is private, but original function 'fileprivate_original_private_derivative' is fileprivate}}
@derivative(of: fileprivate_original_private_derivative)
// expected-note @+1 {{mark the derivative function as 'fileprivate' to match the original function}} {{1-8=fileprivate}}
private func _fileprivate_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_fileprivate_derivative' is fileprivate, but original function 'private_original_fileprivate_derivative' is private}}
@derivative(of: private_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-12=private}}
fileprivate func _private_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility > derivative function visibility
public func public_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_private_derivative' is fileprivate, but original function 'public_original_private_derivative' is public}}
@derivative(of: public_original_private_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
fileprivate func _public_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_internal_derivative' is internal, but original function 'public_original_internal_derivative' is public}}
@derivative(of: public_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
func _public_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_fileprivate_derivative' is fileprivate, but original function 'internal_original_fileprivate_derivative' is internal}}
@derivative(of: internal_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-12=internal}}
fileprivate func _internal_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test invalid reference to an accessor of a non-storage declaration.
// expected-note @+1 {{candidate global function does not have a getter}}
func function(_ x: Float) -> Float {
x
}
// expected-error @+1 {{referenced declaration 'function' could not be resolved}}
@derivative(of: function(_:).get)
func vjpFunction(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test ambiguity that exists when Type function name is the same
// as an accessor label.
extension Float {
// Original function name conflicts with an accessor name ("set").
func set() -> Float {
self
}
// Original function name does not conflict with an accessor name.
func method() -> Float {
self
}
// Test ambiguous parse.
// Expected:
// - Base type: `Float`
// - Declaration name: `set`
// - Accessor kind: <none>
// Actual:
// - Base type: <none>
// - Declaration name: `Float`
// - Accessor kind: `set`
// expected-error @+1 {{cannot find 'Float' in scope}}
@derivative(of: Float.set)
func jvpSet() -> (value: Float, differential: (Float) -> Float) {
fatalError()
}
@derivative(of: Float.method)
func jvpMethod() -> (value: Float, differential: (Float) -> Float) {
fatalError()
}
}
// Test original function with opaque result type.
// expected-note @+1 {{candidate global function does not have expected type '(Float) -> Float'}}
func opaqueResult(_ x: Float) -> some Differentiable { x }
// expected-error @+1 {{referenced declaration 'opaqueResult' could not be resolved}}
@derivative(of: opaqueResult)
func vjpOpaqueResult(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
|
42da5631a741576825e91ae47537f5d9
| 37.317324 | 256 | 0.688728 | false | false | false | false |
glbuyer/GbKit
|
refs/heads/master
|
GbKit/Models/GBUser.swift
|
mit
|
1
|
//
// GBUser.swift
// GbKit
//
// Created by Ye Gu on 16/8/17.
// Copyright © 2017 glbuyer. All rights reserved.
//
import Foundation
import ObjectMapper
enum GBUserBindingAccountType : String {
//电话
case phone = "PHONE"
//微信
case wechat = "WECHAT"
//邮箱
case email = "EMAIL"
//未知
case unknown = "UNKNOWN"
}
enum GBUserGenderType : String {
//男
case MALE = "MALE"
//女
case FEMALE = "FEMALE"
//未知
case UNKNOWN = "UNKNOWN"
}
enum GBUserOnlineStatus : String {
//用户上线
case ONLINE = "ONLINE"
//用户下线
case OFFLINE = "OFFLINE"
//未知
case UNKNOWN = "UNKNOWN"
}
enum GBUserPromotionCodeType : String {
//普通用户
case normal = "NORMAL"
//普通企业用户
case normalCompany = "NORMAL_COMPANY"
//未知
case unknown = "UNKNOWN"
}
class GBUser:GBBaseModel {
//用户ID
var userId = ""
//默认用户头像
var defaultUserProfileImageURL = ""
//用户显示姓名
var displayName = ""
//用户绑定手机号
var bindingPhone = ""
//绑定用户名
var bindingUsername = ""
//绑定聊天id
var bindingChatId = ""
//是否是买手
var isBuyer = false
//用户性别
var userGenderType = GBUserGenderType.UNKNOWN
//最近位置纬度
var lastLatitude:Double?
//最近位置纬度
var lastLongitude:Double?
//上次标记在线状态
var lastMarkOnlineStatus = GBUserOnlineStatus.UNKNOWN
//推广码
var promotionCode = ""
//推广码二维码QR code url
var promotion_code_qr_url = ""
//推广码类型
var promotionCodeType = GBUserPromotionCodeType.unknown
//是否能修改用户名
var ifAllowChangeBindingUsername = false
//是否用户已看过优惠券
var ifUserAlreadyViewCoupon = false
//地点
var lastArea = GBArea()
//已绑定的账户类型
var bindingAccountTypes = [GBUserBindingAccountType]()
//账户安全等级
var securityLevel = 1;
// Mappable
override func mapping(map: Map) {
super.mapping(map: map)
}
}
|
1dcdfe322f6594dbd6f6cb10dfc56132
| 15.533333 | 59 | 0.584677 | false | false | false | false |
MaximilianGoetzfried/MXStatusMenu
|
refs/heads/master
|
MXStatusMenu/App.swift
|
mit
|
2
|
import Cocoa
// Visual Parameters
let BarWidth: CGFloat = 7.0
let GapBetweenBars: CGFloat = 6.0
let LeftMargin: CGFloat = 5.5
let RightMargin: CGFloat = 5.5
// Update interval in seconds
let UpdateInterval = 0.5
/// The maximum throughput per second that is used as the 100% mark for the network load
let MaximumNetworkThroughput = Network.Throughput(input: 1_258_291 /* Download: 1,2 MB/s */, output: 133_120 /* Upload: 120 Kb/s */)
/// Our app delegate only holds a reference to the StatusController, nothing more
class App: NSObject, NSApplicationDelegate {
let statusController = StatusController()
}
|
70ec801df979e4101870aa88d74f3a1d
| 33.055556 | 132 | 0.747145 | false | false | false | false |
jixuhui/HJDemo
|
refs/heads/develop
|
HJDemo/Steed/Task.swift
|
mit
|
2
|
//
// Task.swift
// HJDemo
//
// Created by Hubbert on 15/11/14.
// Copyright © 2015年 Hubbert. All rights reserved.
//
import Foundation
class SDURLTask : NSObject{
var ID:String
var reqType:String
var reqURLPath:String
var reqParameters:Dictionary<String,String>
var operation:AFHTTPRequestOperation?
override init() {
ID = ""
reqType = ""
reqURLPath = ""
reqParameters = Dictionary<String,String>(minimumCapacity: 5)
super.init()
}
}
class SDURLPageTask : SDURLTask {
var pageIndex:Int
var pageSize:Int
var hasMoreData:Bool
var pageIndexKey:String
var pageSizeKey:String
override init() {
pageIndex = 0
pageSize = 20
hasMoreData = false
pageIndexKey = ""
pageSizeKey = ""
super.init()
}
}
|
c30d0efff1c4267036a1532a82fb3831
| 19.309524 | 69 | 0.608441 | false | false | false | false |
zpz1237/NirBillBoard
|
refs/heads/master
|
NirBillboard/ProfileViewController.swift
|
mit
|
1
|
//
// ProfileViewController.swift
// NirBillboard
//
// Created by Nirvana on 7/11/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var buttonImage: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
buttonImage.setImage(UIImage(named: "1430891193_photo-128"), forState: UIControlState.Normal)
assert(buttonImage.imageView?.image != nil)
// Do any additional setup after loading the view.
}
@IBAction func choosePhoto(sender: UIButton) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
let deleteAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in
self.goCamera()
}
let archiveAction = UIAlertAction(title: "从相册选择", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in
self.goImage()
}
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
alertController.addAction(archiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func goCamera() {
var sourceType = UIImagePickerControllerSourceType.Camera
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
var picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = sourceType
self.presentViewController(picker, animated: true, completion: nil)
}
func goImage() {
var picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(picker.sourceType)!
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
buttonImage.setImage(image, forState: UIControlState.Normal)
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
36919c84ac8bef6cc0a732b58379d97b
| 33.602041 | 139 | 0.669419 | false | false | false | false |
keyacid/keyacid-iOS
|
refs/heads/master
|
keyacid/LocalProfileTableViewController.swift
|
bsd-3-clause
|
1
|
//
// LocalProfileTableViewController.swift
// keyacid
//
// Created by Yuan Zhou on 6/22/17.
// Copyright © 2017 yvbbrjdr. All rights reserved.
//
import UIKit
class LocalProfileTableViewController: UITableViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var privateKey: UITextField!
@IBOutlet weak var publicKey: UITextField!
static var showProfile: LocalProfile? = nil
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if LocalProfileTableViewController.showProfile != nil {
name.text = LocalProfileTableViewController.showProfile?.name
publicKey.text = LocalProfileTableViewController.showProfile?.publicKey.base64EncodedString()
privateKey.text = LocalProfileTableViewController.showProfile?.privateKey.base64EncodedString()
}
}
@IBAction func cancelClicked() {
LocalProfileTableViewController.showProfile = nil
self.navigationController?.popViewController(animated: true)
}
@IBAction func generateKeyPairClicked() {
let tmpLocalProfile: LocalProfile = LocalProfile.init()
tmpLocalProfile.generateKeyPair()
privateKey.text = tmpLocalProfile.privateKey.base64EncodedString()
publicKey.text = tmpLocalProfile.publicKey.base64EncodedString()
}
@IBAction func generatePublicKeyClicked() {
let tmpLocalProfile: LocalProfile = LocalProfile.init()
let privateKeyData: Data? = Data.init(base64Encoded: privateKey.text!)
if privateKeyData != nil {
tmpLocalProfile.privateKey = privateKeyData!
if tmpLocalProfile.generatePublicKey() {
publicKey.text = tmpLocalProfile.publicKey.base64EncodedString()
return
}
}
let invalidPrivateKey: UIAlertController = UIAlertController.init(title: "Error", message: "You entered an invalid private key!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.privateKey.text = ""
self.privateKey.becomeFirstResponder()
})
invalidPrivateKey.addAction(OKAction)
self.present(invalidPrivateKey, animated: true, completion: nil)
}
@IBAction func showQRCodeClicked() {
ShowQRCodeViewController.publicKey = publicKey.text!
self.performSegue(withIdentifier: "ShowShowQRCode", sender: self)
}
@IBAction func saveClicked() {
if name.text == "" {
let emptyName: UIAlertController = UIAlertController.init(title: "Error", message: "An empty name is not acceptable!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.name.becomeFirstResponder()
})
emptyName.addAction(OKAction)
self.present(emptyName, animated: true, completion: nil)
return
}
let publicKeyData: Data? = Data.init(base64Encoded: publicKey.text!)
let privateKeyData: Data? = Data.init(base64Encoded: privateKey.text!)
if publicKeyData != nil && privateKeyData != nil {
let tmpLocalProfile: LocalProfile = LocalProfile.init()
tmpLocalProfile.name = name.text!
tmpLocalProfile.publicKey = publicKeyData!
tmpLocalProfile.privateKey = privateKeyData!
if tmpLocalProfile.isValidKey() {
if LocalProfileTableViewController.showProfile == nil {
ProfilesTableViewController.localProfiles.append(tmpLocalProfile)
} else {
LocalProfileTableViewController.showProfile?.name = tmpLocalProfile.name
LocalProfileTableViewController.showProfile?.publicKey = tmpLocalProfile.publicKey
LocalProfileTableViewController.showProfile?.privateKey = tmpLocalProfile.privateKey
}
ProfilesTableViewController.securelySaveProfiles()
LocalProfileTableViewController.showProfile = nil
self.navigationController?.popViewController(animated: true)
return
}
}
let invalidKey: UIAlertController = UIAlertController.init(title: "Error", message: "You entered invalid keys!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
invalidKey.addAction(OKAction)
self.present(invalidKey, animated: true, completion: nil)
}
@IBAction func nameDone() {
privateKey.becomeFirstResponder()
}
@IBAction func privateKeyDone() {
privateKey.resignFirstResponder()
}
@IBAction func publicKeyDone() {
publicKey.resignFirstResponder()
}
@IBAction func copyPublicKeyClicked() {
UIPasteboard.general.string = publicKey.text!
let copied: UIAlertController = UIAlertController.init(title: "Success", message: "The public key is copied!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
copied.addAction(OKAction)
self.present(copied, animated: true, completion: nil)
}
}
|
50a280cb78bd6e959706c5ba59d5a464
| 43.775 | 161 | 0.673925 | false | false | false | false |
agilie/AGCircularPicker
|
refs/heads/master
|
Example/AGCircularPicker/MultiPickerViewController.swift
|
mit
|
1
|
//
// MultiPickerViewController.swift
// AGCircularPicker
//
// Created by Sergii Avilov on 6/23/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import AGCircularPicker
class MultiPickerViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var circularPicker: AGCircularPicker!
override func viewDidLoad() {
super.viewDidLoad()
let hourColor1 = UIColor.rgb_color(r: 0, g: 237, b: 233)
let hourColor2 = UIColor.rgb_color(r: 0, g: 135, b: 217)
let hourColor3 = UIColor.rgb_color(r: 138, g: 28, b: 195)
let hourTitleOption = AGCircularPickerTitleOption(title: "hours")
let hourValueOption = AGCircularPickerValueOption(minValue: 0, maxValue: 23, rounds: 2, initialValue: 15)
let hourColorOption = AGCircularPickerColorOption(gradientColors: [hourColor1, hourColor2, hourColor3], gradientAngle: 20)
let hourOption = AGCircularPickerOption(valueOption: hourValueOption, titleOption: hourTitleOption, colorOption: hourColorOption)
let minuteColor1 = UIColor.rgb_color(r: 255, g: 141, b: 0)
let minuteColor2 = UIColor.rgb_color(r: 255, g: 0, b: 88)
let minuteColor3 = UIColor.rgb_color(r: 146, g: 0, b: 132)
let minuteColorOption = AGCircularPickerColorOption(gradientColors: [minuteColor1, minuteColor2, minuteColor3], gradientAngle: -20)
let minuteTitleOption = AGCircularPickerTitleOption(title: "minutes")
let minuteValueOption = AGCircularPickerValueOption(minValue: 0, maxValue: 59)
let minuteOption = AGCircularPickerOption(valueOption: minuteValueOption, titleOption: minuteTitleOption, colorOption: minuteColorOption)
let secondTitleOption = AGCircularPickerTitleOption(title: "seconds")
let secondColorOption = AGCircularPickerColorOption(gradientColors: [hourColor3, hourColor2, hourColor1])
let secondOption = AGCircularPickerOption(valueOption: minuteValueOption, titleOption: secondTitleOption, colorOption: secondColorOption)
circularPicker.options = [hourOption, minuteOption, secondOption]
circularPicker.delegate = self
}
@IBAction func close(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
}
extension MultiPickerViewController: AGCircularPickerDelegate {
func didChangeValues(_ values: Array<AGColorValue>, selectedIndex: Int) {
let valueComponents = values.map { return String(format: "%02d", $0.value) }
let fullString = valueComponents.joined(separator: ":")
let attributedString = NSMutableAttributedString(string:fullString)
let fullRange = (fullString as NSString).range(of: fullString)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.white.withAlphaComponent(0.5), range: fullRange)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 28, weight: UIFontWeightBold), range: fullRange)
let range = NSMakeRange(selectedIndex * 2 + selectedIndex, 2)
attributedString.addAttribute(NSForegroundColorAttributeName, value: values[selectedIndex].color, range: range)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 35, weight: UIFontWeightBlack), range: range)
titleLabel.attributedText = attributedString
}
}
|
335652a7f229633aea3a0d130853c07e
| 52.384615 | 145 | 0.726225 | false | false | false | false |
uias/Tabman
|
refs/heads/main
|
Sources/Tabman/Bar/BarIndicator/Types/TMDotBarIndicator.swift
|
mit
|
1
|
//
// TMDotBarIndicator.swift
// Tabman
//
// Created by Merrick Sapsford on 07/11/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
/// Indicator that displays a circular dot centered along the X-axis.
open class TMDotBarIndicator: TMBarIndicator {
// MARK: Types
public enum Size {
case small
case medium
case large
case custom(size: CGSize)
}
// MARK: Properties
private let dotContainer = UIView()
private let dotLayer = CAShapeLayer()
private var widthConstraint: NSLayoutConstraint?
private var heightConstraint: NSLayoutConstraint?
open override var displayMode: TMBarIndicator.DisplayMode {
return .bottom
}
// MARK: Customization
open var size: Size = .medium {
didSet {
guard size.rawValue != oldValue.rawValue else {
return
}
update(for: size.rawValue)
}
}
/// Color of the dot.
open override var tintColor: UIColor! {
didSet {
dotLayer.fillColor = tintColor.cgColor
}
}
// MARK: Lifecycle
open override func layout(in view: UIView) {
super.layout(in: view)
view.addSubview(dotContainer)
dotContainer.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = dotContainer.widthAnchor.constraint(equalToConstant: size.rawValue.width)
let heightConstraint = dotContainer.heightAnchor.constraint(equalToConstant: size.rawValue.height)
NSLayoutConstraint.activate([
dotContainer.topAnchor.constraint(equalTo: topAnchor),
dotContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
dotContainer.centerXAnchor.constraint(equalTo: centerXAnchor),
widthConstraint,
heightConstraint
])
self.widthConstraint = widthConstraint
self.heightConstraint = heightConstraint
dotLayer.fillColor = tintColor.cgColor
dotContainer.layer.addSublayer(dotLayer)
}
// MARK: Layout
open override func layoutSubviews() {
super.layoutSubviews()
dotLayer.frame = dotContainer.bounds
dotLayer.path = dotPath(for: size.rawValue).cgPath
}
private func update(for size: CGSize) {
widthConstraint?.constant = size.width
heightConstraint?.constant = size.height
setNeedsLayout()
}
}
private extension TMDotBarIndicator {
func dotPath(for size: CGSize) -> UIBezierPath {
let path = UIBezierPath(ovalIn: CGRect(x: 0.0,
y: 0.0,
width: size.width,
height: size.height))
return path
}
}
private extension TMDotBarIndicator.Size {
var rawValue: CGSize {
switch self {
case .small:
return CGSize(width: 6, height: 6)
case .medium:
return CGSize(width: 8, height: 8)
case .large:
return CGSize(width: 12, height: 12)
case .custom(let size):
return size
}
}
}
|
d26a0c1a6051794afd62e95a7f362232
| 27.241379 | 106 | 0.591575 | false | false | false | false |
rastogigaurav/mTV
|
refs/heads/master
|
mTV/mTV/Interactors/DisplayMovies.swift
|
mit
|
1
|
//
// DisplayMovies.swift
// mTV
//
// Created by Gaurav Rastogi on 6/22/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
protocol DisplayMoviesProtocol:NSObjectProtocol{
func displayMovies(forSection section:MovieSections, withPage page:Int, completionHandler:@escaping (_ totalMovies:Int?, _ movies:[Movie]?, _ section:MovieSections?)->())->Void
func filter(movieList list:[Movie], startYear sYear:Int, endYear eYear:Int, completionHandler:@escaping (_ filteredList:[Movie])->Void)->Void
}
class DisplayMoviesMock:NSObject,DisplayMoviesProtocol{
var displayMoviesIsCalled = false
var filterMovieListIsCalled:Bool = false
func displayMovies(forSection section: MovieSections, withPage page: Int, completionHandler: @escaping (Int?, [Movie]?, MovieSections?) -> ()) {
displayMoviesIsCalled = true
completionHandler(0, [Movie(json: Dictionary())], section)
}
func filter(movieList list: [Movie], startYear sYear: Int, endYear eYear: Int, completionHandler: @escaping ([Movie]) -> Void) {
filterMovieListIsCalled = true
completionHandler([Movie(json: Dictionary())])
}
}
class DisplayMovies: NSObject,DisplayMoviesProtocol {
var moviesRepository:MoviesRepositoryProtocol?
init(with mRespository:MoviesRepositoryProtocol) {
super.init()
self.moviesRepository = mRespository
}
func displayMovies(forSection section: MovieSections, withPage page: Int, completionHandler: @escaping (Int?, [Movie]?, MovieSections?) -> ()) {
switch section {
case .topRated:
self.moviesRepository?.getTopRatedMovies(page: page, completionHandler: { (total, movies, error) in
if error == nil{
completionHandler(total,movies,section)
}
})
break
case .upcoming:
self.moviesRepository?.getUpcomingMovies(page: page, completionHandler: { (total, movies, error) in
if error == nil{
completionHandler(total,movies,section)
}
})
break
case .nowPlaying:
self.moviesRepository?.getNowPlayingMovies(page: page, completionHandler: { (total, movies, error) in
if error == nil{
completionHandler(total,movies,section)
}
})
break
case .popular:
self.moviesRepository?.getPopularMovies(page: page, completionHandler: { (total, movies, error) in
if error == nil{
completionHandler(total,movies,section)
}
})
break
default:break
}
}
func filter(movieList list: [Movie], startYear sYear: Int, endYear eYear: Int, completionHandler: @escaping ([Movie]) -> Void) {
let filteredList = list.filter { ($0.releaseYear >= sYear && $0.releaseYear <= eYear)}
completionHandler(filteredList)
}
}
|
827ec8a74b83edaac74db6f8993db8ae
| 36.182927 | 180 | 0.624467 | false | false | false | false |
Jnosh/swift
|
refs/heads/master
|
test/IDE/coloring.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// XFAIL: broken_std_regex
#line 17 "abc.swift"
// CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str>
@available(iOS 8.0, OSX 10.10, *)
// CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *)
func foo() {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>}
if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"}
}
enum List<T> {
case Nil
// rdar://21927124
// CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List)
indirect case Cons(T, List)
}
// CHECK: <kw>struct</kw> S {
struct S {
// CHECK: <kw>var</kw> x : <type>Int</type>
var x : Int
// CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type>
var y : Int.Int
// CHECK: <kw>var</kw> a, b : <type>Int</type>
var a, b : Int
}
enum EnumWithDerivedEquatableConformance : Int {
// CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} {
case CaseA
// CHECK-NEXT: <kw>case</kw> CaseA
case CaseB, CaseC
// CHECK-NEXT: <kw>case</kw> CaseB, CaseC
case CaseD = 30, CaseE
// CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE
}
// CHECK-NEXT: }
// CHECK: <kw>class</kw> MyCls {
class MyCls {
// CHECK: <kw>var</kw> www : <type>Int</type>
var www : Int
// CHECK: <kw>func</kw> foo(x: <type>Int</type>) {}
func foo(x: Int) {}
// CHECK: <kw>var</kw> aaa : <type>Int</type> {
var aaa : Int {
// CHECK: <kw>get</kw> {}
get {}
// CHECK: <kw>set</kw> {}
set {}
}
// CHECK: <kw>var</kw> bbb : <type>Int</type> {
var bbb : Int {
// CHECK: <kw>set</kw> {
set {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
}
// CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> {
subscript (i : Int, j : Int) -> Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> i + j
return i + j
}
// CHECK: <kw>set</kw>(v) {
set(v) {
// CHECK: v + i - j
v + i - j
}
}
// CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {}
func multi(_ name: Int, otherpart x: Int) {}
}
// CHECK-LABEL: <kw>class</kw> Attributes {
class Attributes {
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type>
@IBOutlet var v0: Int
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @IBOutlet var v1: String
// CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type>
@objc @IBOutlet var v2: String
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @objc var v3: String
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {}
@available(*, unavailable) func f1() {}
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {}
@available(*, unavailable) @IBAction func f2() {}
// CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {}
@IBAction @available(*, unavailable) func f3() {}
// CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {}
mutating func func_mutating_1() {}
// CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {}
nonmutating func func_mutating_2() {}
}
func stringLikeLiterals() {
// CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str>
var us1: UnicodeScalar = "a"
// CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str>
var us2: UnicodeScalar = "ы"
// CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str>
var ch1: Character = "a"
// CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str>
var ch2: Character = "あ"
// CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str>
var s1 = "abc абвгд あいうえお"
}
// CHECK: <kw>var</kw> globComp : <type>Int</type>
var globComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
}
// CHECK: <comment-block>/* foo is the best */</comment-block>
/* foo is the best */
// CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> {
func foo(n: Float) -> Int {
// CHECK: <kw>var</kw> fnComp : <type>Int</type>
var fnComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> a: <type>Int</type>
// CHECK: <kw>return</kw> <int>0</int>
var a: Int
return 0
}
}
// CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}()
var q = MyCls()
// CHECK: <kw>var</kw> ee = <str>"yoo"</str>;
var ee = "yoo";
// CHECK: <kw>return</kw> <int>100009</int>
return 100009
}
///- returns: single-line, no space
// CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space
/// - returns: single-line, 1 space
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space
/// - returns: single-line, 2 spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces
/// - returns: single-line, more spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces
// CHECK: <kw>protocol</kw> Prot {
protocol Prot {
// CHECK: <kw>typealias</kw> Blarg
typealias Blarg
// CHECK: <kw>func</kw> protMeth(x: <type>Int</type>)
func protMeth(x: Int)
// CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> }
var protocolProperty1: Int { get }
// CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> }
var protocolProperty2: Int { get set }
}
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}}
infix operator *-* : FunnyPrecedence
// CHECK: <kw>precedencegroup</kw> FunnyPrecedence
// CHECK-NEXT: <kw>associativity</kw>: left{{$}}
// CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence
precedencegroup FunnyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
// CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence
infix operator *-+* : FunnyPrecedence
// CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-+*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}}
infix operator *--*
// CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *--*(l: Int, r: Int) -> Int { return l }
// CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {}
protocol Prot2 : Prot {}
// CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {}
class SubCls : MyCls, Prot {}
// CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {}
func f(x: Int) -> Int {
// CHECK: <comment-line>// string interpolation is the best</comment-line>
// string interpolation is the best
// CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str>
"This is string \(genFn({(a:Int -> Int) in a})) interpolation"
// CHECK: <str>"This is unterminated</str>
"This is unterminated
// CHECK: <str>"This in unterminated with ignored \( "interpolation" ) in it</str>
"This in unterminated with ignored \( "interpolation" ) in it
// CHECK: <str>"This is terminated with \( invalid interpolation" + "in it"</str>
"This is terminated with \( invalid interpolation" + "in it"
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline string.
// CHECK-NEXT: """</str>
"""
This is a multiline string.
"""
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string
// CHECK-NEXT: </str>\<anchor>(</anchor>
// CHECK-NEXT: <str>"inner"</str>
// CHECK-NEXT: <anchor>)</anchor><str>
// CHECK-NEXT: """</str>
"""
This is a multiline\( "interpolated" )string
\(
"inner"
)
"""
}
// CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) {
func bar(x: Int) -> (Int, Float) {
// CHECK: foo({{(<type>)?}}Float{{(</type>)?}}())
foo(Float())
}
class GenC<T1,T2> {}
func test() {
// CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>()
var x = GenC<Int, Float>()
}
// CHECK: <kw>typealias</kw> MyInt = <type>Int</type>
typealias MyInt = Int
func test2(x: Int) {
// CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str>
"\(x)"
}
// CHECK: <kw>class</kw> Observers {
class Observers {
// CHECK: <kw>var</kw> p1 : <type>Int</type> {
var p1 : Int {
// CHECK: <kw>willSet</kw>(newValue) {}
willSet(newValue) {}
// CHECK: <kw>didSet</kw> {}
didSet {}
}
// CHECK: <kw>var</kw> p2 : <type>Int</type> {
var p2 : Int {
// CHECK: <kw>didSet</kw> {}
didSet {}
// CHECK: <kw>willSet</kw> {}
willSet {}
}
}
// CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) {
func test3(o: AnyObject) {
// CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type>
let x = o as! MyCls
}
// CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}}
func test4(inout a: Int) {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}}
if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}}
// CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}}
func test4b(a: inout Int) {
}
// CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> {
class MySubClass : MyCls {
// CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {}
override func foo(x: Int) {}
// CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {}
convenience init(a: Int) {}
}
// CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> }
var g1 = { (x: Int) -> Int in return 0 }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ {
infix operator ~~ {}
// CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ {
prefix operator *~~ {}
// CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* {
postfix operator ~~* {}
func test_defer() {
defer {
// CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int>
let x : Int = 0
}
}
// FIXME: blah.
// FIXME: blah blah
// Something something, FIXME: blah
// CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line>
// CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line>
/* FIXME: blah*/
// CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block>
/*
* FIXME: blah
* Blah, blah.
*/
// CHECK: <comment-block>/*
// CHECK: * <comment-marker>FIXME: blah</comment-marker>
// CHECK: * Blah, blah.
// CHECK: */</comment-block>
// TODO: blah.
// TTODO: blah.
// MARK: blah.
// CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line>
// CHECK: <kw>func</kw> test5() -> <type>Int</type> {
func test5() -> Int {
// CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line>
// TODO: something, something.
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
func test6<T : Prot>(x: T) {}
// CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}}
// http://whatever.com?ee=2&yy=1 and radar://123456
/* http://whatever.com FIXME: see in http://whatever.com/fixme
http://whatever.com */
// CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line>
// CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker>
// CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block>
// CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line>
// http://whatever.com/what-ever
// CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {}
func <#test1#> () {}
/// Brief.
///
/// Simple case.
///
/// - parameter x: A number
/// - parameter y: Another number
/// - PaRamEteR z-hyphen-q: Another number
/// - parameter : A strange number...
/// - parameternope1: Another number
/// - parameter nope2
/// - parameter: nope3
/// -parameter nope4: Another number
/// * parameter nope5: Another number
/// - parameter nope6: Another number
/// - Parameters: nope7
/// - seealso: yes
/// - seealso: yes
/// - seealso:
/// -seealso: nope
/// - seealso : nope
/// - seealso nope
/// - returns: `x + y`
func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number...
// CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3
// CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/// Brief.
///
/// Simple case.
///
/// - Parameters:
/// - x: A number
/// - y: Another number
///
///- note: NOTE1
///
/// - NOTE: NOTE2
/// - note: Not a Note field (not at top level)
/// - returns: `x + y`
func bar(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// - x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/**
Does pretty much nothing.
Not a parameter list: improper indentation.
- Parameters: sdfadsf
- WARNING: - WARNING: Should only have one field
- $$$: Not a field.
Empty field, OK:
*/
func baz() {}
// CHECK: <doc-comment-block>/**
// CHECK: Does pretty much nothing.
// CHECK: Not a parameter list: improper indentation.
// CHECK: - Parameters: sdfadsf
// CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field
// CHECK: - $$$: Not a field.
// CHECK: Empty field, OK:
// CHECK: */</doc-comment-block>
// CHECK: <kw>func</kw> baz() {}
/***/
func emptyDocBlockComment() {}
// CHECK: <doc-comment-block>/***/</doc-comment-block>
// CHECK: <kw>func</kw> emptyDocBlockComment() {}
/**
*/
func emptyDocBlockComment2() {}
// CHECK: <doc-comment-block>/**
// CHECK: */
// CHECK: <kw>func</kw> emptyDocBlockComment2() {}
/** */
func emptyDocBlockComment3() {}
// CHECK: <doc-comment-block>/** */
// CHECK: <kw>func</kw> emptyDocBlockComment3() {}
/**/
func malformedBlockComment(f : () throws -> ()) rethrows {}
// CHECK: <doc-comment-block>/**/</doc-comment-block>
// CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {}
//: playground doc comment line
func playgroundCommentLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-line>//: playground doc comment line</comment-line>
/*:
playground doc comment multi-line
*/
func playgroundCommentMultiLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-block>/*:
// CHECK: playground doc comment multi-line
// CHECK: */</comment-block>
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
// CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url>
func funcTakingFor(for internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {}
func funcTakingIn(in internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {}
_ = 123
// CHECK: <int>123</int>
_ = -123
// CHECK: <int>-123</int>
_ = -1
// CHECK: <int>-1</int>
_ = -0x123
// CHECK: <int>-0x123</int>
_ = -3.1e-5
// CHECK: <float>-3.1e-5</float>
/** aaa
- returns: something
*/
// CHECK: - <doc-comment-field>returns</doc-comment-field>: something
let filename = #file
// CHECK: <kw>let</kw> filename = <kw>#file</kw>
let line = #line
// CHECK: <kw>let</kw> line = <kw>#line</kw>
let column = #column
// CHECK: <kw>let</kw> column = <kw>#column</kw>
let function = #function
// CHECK: <kw>let</kw> function = <kw>#function</kw>
let image = #imageLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal>
let file = #fileLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal>
let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal>
let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)]
// CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>]
"--\"\(x) --"
// CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str>
func keywordAsLabel1(in: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {}
func keywordAsLabel2(for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {}
func keywordAsLabel3(if: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel4(_: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {}
func keywordAsLabel5(_: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel6(if let: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {}
func foo1() {
// CHECK: <kw>func</kw> foo1() {
keywordAsLabel1(in: 1)
// CHECK: keywordAsLabel1(in: <int>1</int>)
keywordAsLabel2(for: 1)
// CHECK: keywordAsLabel2(for: <int>1</int>)
keywordAsLabel3(if: 1, for: 2)
// CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>)
keywordAsLabel5(1, for: 2)
// CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>)
_ = (if: 0, for: 2)
// CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>)
_ = (_: 0, _: 2)
// CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>)
}
func foo2(O1 : Int?, O2: Int?, O3: Int?) {
guard let _ = O1, var _ = O2, let _ = O3 else { }
// CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { }
if let _ = O1, var _ = O2, let _ = O3 {}
// CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {}
}
func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) {
// CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) {
switch(`for`, `in`) {
case (let x, let y):
// CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y):
print(x, y)
}
}
// Keep this as the last test
/**
Trailing off ...
func unterminatedBlockComment() {}
// CHECK: <comment-line>// Keep this as the last test</comment-line>
// CHECK: <doc-comment-block>/**
// CHECK: Trailing off ...
// CHECK: func unterminatedBlockComment() {}
// CHECK: </doc-comment-block>
|
f058ce520f6ccbae83523e01b4aecb73
| 36.193344 | 178 | 0.605778 | false | false | false | false |
barteljan/JBPersistenceStore
|
refs/heads/master
|
JBPersistenceStore/Classes/TransactionalNSCodingPersistenceStore.swift
|
mit
|
1
|
//
// TransactionalNSCodingPersistenceStore.swift
// CocoaLumberjack
//
// Created by bartel on 18.12.17.
//
import Foundation
import JBPersistenceStore_Protocols
import VISPER_Entity
import YapDatabase
import YapDatabase.YapDatabaseView
public class TransactionalNSCodingPersistenceStore: TypedPersistenceStoreProtocol {
public typealias PersistableType = NSCoding & CanBePersistedProtocol
let readTransaction: YapDatabaseReadTransaction?
let writeTransaction: YapDatabaseReadWriteTransaction?
public init(readTransaction: YapDatabaseReadTransaction) {
self.readTransaction = readTransaction
self.writeTransaction = nil
}
public init(writeTransaction: YapDatabaseReadWriteTransaction) {
self.readTransaction = nil
self.writeTransaction = writeTransaction
}
func getReadTransaction() -> YapDatabaseReadTransaction {
if let readTransaction = self.readTransaction {
return readTransaction
} else if let writeTransaction = self.writeTransaction {
return writeTransaction
}
fatalError("Need a f... transaction")
}
public func persist<T>(_ item: T!) throws {
guard let writeTransaction = self.writeTransaction else {
throw TransactionalNSCodingPersistenceStoreError.NoWriteTransactionFound
}
guard let myItem = item as? PersistableType else {
throw PersistenceStoreError.CannotUse(object: item, inStoreWithType: PersistableType.Type.self)
}
writeTransaction.setObject(myItem, forKey: myItem.identifier(), inCollection: type(of: myItem).collectionName())
}
public func persist<T>(_ item: T!, completion: @escaping () -> Void) throws {
try self.persist(item)
completion()
}
public func delete<T>(_ item: T!) throws {
guard let writeTransaction = self.writeTransaction else {
throw TransactionalNSCodingPersistenceStoreError.NoWriteTransactionFound
}
guard let myItem = item as? PersistableType else {
throw PersistenceStoreError.CannotUse(object: item, inStoreWithType: PersistableType.Type.self)
}
let collection = type(of: myItem).collectionName()
let identifier = myItem.identifier()
writeTransaction.removeObject(forKey: identifier, inCollection: collection)
}
public func delete<T>(_ item: T!, completion: @escaping () -> Void) throws {
try self.delete(item)
completion()
}
public func get<T>(_ identifier: String) throws -> T? {
let transaction = self.getReadTransaction()
guard let type = T.self as? PersistableType.Type else {
throw PersistenceStoreError.CannotUseType(type: T.Type.self, inStoreWithType: PersistableType.Type.self)
}
return transaction.object(forKey: identifier, inCollection: type.collectionName()) as! T?
}
public func get<T>(_ identifier: String, completion: @escaping (T?) -> Void) throws {
let item: T? = try self.get(identifier)
completion(item)
}
public func getAll<T>(_ type: T.Type) throws -> [T] {
let transaction = self.getReadTransaction()
guard let type = T.self as? PersistableType.Type else {
throw PersistenceStoreError.CannotUseType(type: T.Type.self, inStoreWithType: PersistableType.Type.self)
}
let collection = type.collectionName()
var items: [T] = [T]()
transaction.enumerateRows(inCollection: collection) { (_: String, object: Any, _: Any?, _: UnsafeMutablePointer<ObjCBool>) -> Void in
items.append(object as! T)
}
return items
}
public func getAll<T>(_ type: T.Type, completion: @escaping ([T]) -> Void) throws {
let items: [T] = try self.getAll(type)
completion(items)
}
public func getAll<T>(_ viewName: String) throws -> [T] {
let transaction = self.getReadTransaction()
guard T.self is PersistableType.Type else {
throw PersistenceStoreError.CannotUseType(type: T.Type.self, inStoreWithType: PersistableType.Type.self)
}
var resultArray: [T] = [T]()
if let viewTransaction: YapDatabaseViewTransaction = transaction.ext(viewName) as? YapDatabaseViewTransaction {
viewTransaction.enumerateGroups { (group: String, _: UnsafeMutablePointer<ObjCBool>) in
viewTransaction.enumerateKeysAndObjects(inGroup: group, with: []) { (_: String, _: String, object: Any, _: UInt, _: UnsafeMutablePointer<ObjCBool>) in
resultArray.append(object as! T)
}
}
}
return resultArray
}
public func getAll<T>(_ viewName: String, completion: @escaping ([T]) -> Void) throws {
let items: [T] = try self.getAll(viewName)
completion(items)
}
public func getAll<T>(_ viewName: String, groupName: String) throws -> [T] {
let transaction = self.getReadTransaction()
guard T.self is PersistableType.Type else {
throw PersistenceStoreError.CannotUseType(type: T.Type.self, inStoreWithType: PersistableType.Type.self)
}
var resultArray: [T] = [T]()
if let viewTransaction: YapDatabaseViewTransaction = transaction.ext(viewName) as? YapDatabaseViewTransaction {
viewTransaction.enumerateKeysAndObjects(inGroup: groupName, with: []) { (_: String, _: String, object: Any, _: UInt, _: UnsafeMutablePointer<ObjCBool>) in
resultArray.append(object as! T)
}
}
return resultArray
}
public func getAll<T>(_ viewName: String, groupName: String, completion: @escaping ([T]) -> Void) throws {
let items: [T] = try self.getAll(viewName, groupName: groupName)
completion(items)
}
public func exists<T>(_ item: T!) throws -> Bool {
let transaction = self.getReadTransaction()
if !self.isResponsible(for: item) {
return false
}
guard let myItem = item as? PersistableType else {
throw PersistenceStoreError.CannotUse(object: item, inStoreWithType: PersistableType.Type.self)
}
let collection = type(of: myItem.self).collectionName()
let identifier = myItem.identifier()
return transaction.hasObject(forKey: identifier, inCollection: collection)
}
public func exists<T>(_ item: T!, completion: @escaping (Bool) -> Void) throws {
let exists = try self.exists(item)
completion(exists)
}
public func exists<T>(_ identifier: String, type: T.Type) throws -> Bool {
let transaction = self.getReadTransaction()
print(type)
if !self.isResponsible(forType: type) {
return false
}
guard let myType = type.self as? PersistableType.Type else {
throw PersistenceStoreError.CannotUseType(type: type.self, inStoreWithType: PersistableType.Type.self)
}
let collection = myType.collectionName()
return transaction.hasObject(forKey: identifier, inCollection: collection)
}
public func exists<T>(_ identifier: String, type: T.Type, completion: @escaping (Bool) -> Void) throws {
let exists = try self.exists(identifier, type: type)
completion(exists)
}
public func filter<T>(_: T.Type, includeElement: @escaping (T) -> Bool) throws -> [T] {
let list = try self.getAll(T.self)
return list.filter(includeElement)
}
public func filter<T>(_: T.Type, includeElement: @escaping (T) -> Bool, completion: @escaping ([T]) -> Void) throws {
try self.getAll(T.self) { (items: [T]) in
let filtered = items.filter(includeElement)
completion(filtered)
}
}
public func addView<T>(_ viewName: String, groupingBlock _: @escaping ((String, String, T) -> String?), sortingBlock _: @escaping ((String, String, String, T, String, String, T) -> ComparisonResult)) throws {
throw TransactionalNSCodingPersistenceStoreError.CannotAddViewInTransaction(viewName: viewName)
}
public func transaction(transaction _: @escaping (EntityStore) throws -> Void) throws {
fatalError("cannot open transaction in an other transaction")
}
}
|
6ef2048966571509d625cac3b9660e80
| 35.836283 | 212 | 0.655375 | false | false | false | false |
0x73/Cherry
|
refs/heads/master
|
Cherry/Shared/Model/KTActiveActivityState.swift
|
mit
|
1
|
//
// KTActiveActivityState.swift
// Cherry
//
// Created by Kenny Tang on 2/22/15.
//
//
class KTActiveActivityState {
var activityID:String
var activityName:String
var status:Int
var currentPomo:Int
var elapsedSecs:Int
init(id: String, name:String, status:Int, currentPomo:Int, elapsed:Int) {
self.activityID = id
self.activityName = name
self.status = status
self.currentPomo = currentPomo
self.elapsedSecs = elapsed
}
}
|
595c629b91a5a4487426817880494839
| 18.96 | 77 | 0.649299 | false | false | false | false |
squimer/DatePickerDialog-iOS-Swift
|
refs/heads/master
|
Demo/ViewController.swift
|
mit
|
1
|
import UIKit
import DatePickerDialog
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
let datePicker = DatePickerDialog(
textColor: .red,
buttonColor: .red,
font: UIFont.boldSystemFont(ofSize: 17),
showCancelButton: true
)
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
func datePickerTapped() {
let currentDate = Date()
var dateComponents = DateComponents()
dateComponents.month = -3
let threeMonthAgo = Calendar.current.date(byAdding: dateComponents, to: currentDate)
datePicker.show("DatePickerDialog",
doneButtonTitle: "Done",
cancelButtonTitle: "Cancel",
minimumDate: threeMonthAgo,
maximumDate: currentDate,
datePickerMode: .date) { (date) in
if let dt = date {
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
self.textField.text = formatter.string(from: dt)
}
}
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == self.textField {
datePickerTapped()
return false
}
return true
}
}
|
7a71294dfa005368d4fef31a6092b637
| 28.1 | 92 | 0.570447 | false | false | false | false |
googlesamples/mlkit
|
refs/heads/master
|
ios/quickstarts/smartreply/SmartReplyExample/DateExtension.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2020 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.
//
import Foundation
extension Date {
func timeAgo() -> String {
let interval = Calendar.current.dateComponents(
[.year, .day, .hour, .minute, .second], from: self, to: Date())
if let year = interval.year, year > 0 {
return DateFormatter.localizedString(from: self, dateStyle: .long, timeStyle: .none)
} else if let day = interval.day, day > 6 {
let format = DateFormatter.dateFormat(
fromTemplate: "MMMMd", options: 0, locale: NSLocale.current)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
} else if let day = interval.day, day > 0 {
return day == 1 ? "\(day) day ago" : "\(day) days ago"
} else if let hour = interval.hour, hour > 0 {
return hour == 1 ? "\(hour) hour ago" : "\(hour) hours ago"
} else if let minute = interval.minute, minute > 0 {
return minute == 1 ? "\(minute) minute ago" : "\(minute) minutes ago"
} else if let second = interval.second, second > 0 {
return second == 1 ? "\(second) second ago" : "\(second) seconds ago"
} else {
return "just now"
}
}
}
|
048aaccb3809289c15e138349758d8cc
| 37.021739 | 90 | 0.650086 | false | false | false | false |
AlexRamey/mbird-iOS
|
refs/heads/master
|
iOS Client/ArticlesController/CategoryArticleTableViewCell.swift
|
mit
|
1
|
//
// CategoryArticleTableViewCell.swift
// iOS Client
//
// Created by Alex Ramey on 4/7/18.
// Copyright © 2018 Mockingbird. All rights reserved.
//
import UIKit
class CategoryArticleTableViewCell: UITableViewCell, ThumbnailImageCell {
@IBOutlet weak var thumbnailImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.thumbnailImage.contentMode = .scaleAspectFill
self.thumbnailImage.clipsToBounds = true
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.MBSelectedCell
self.selectedBackgroundView = bgColorView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setTitle(_ title: NSAttributedString?) {
self.titleLabel.attributedText = title
self.titleLabel.textColor = UIColor.black
self.titleLabel.font = UIFont(name: "IowanOldStyle-Roman", size: 22.0)
self.titleLabel.sizeToFit()
}
}
|
36257616d42a5a45fd844842d30f1287
| 29.916667 | 78 | 0.686433 | false | false | false | false |
omondigeno/ActionablePushMessages
|
refs/heads/master
|
Pods/MK/Sources/SideNavigationViewController.swift
|
apache-2.0
|
1
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of MaterialKit nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public extension UIViewController {
/**
A convenience property that provides access to the SideNavigationViewController.
This is the recommended method of accessing the SideNavigationViewController
through child UIViewControllers.
*/
public var sideNavigationViewController: SideNavigationViewController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is SideNavigationViewController {
return viewController as? SideNavigationViewController
}
viewController = viewController?.parentViewController
}
return nil
}
}
@objc(SideNavigationViewControllerDelegate)
public protocol SideNavigationViewControllerDelegate {
/**
An optional delegation method that is fired before the
SideNavigationViewController opens.
*/
optional func sideNavigationViewWillOpen(sideNavigationViewController: SideNavigationViewController)
/**
An optional delegation method that is fired after the
SideNavigationViewController opened.
*/
optional func sideNavigationViewDidOpen(sideNavigationViewController: SideNavigationViewController)
/**
An optional delegation method that is fired before the
SideNavigationViewController closes.
*/
optional func sideNavigationViewWillClose(sideNavigationViewController: SideNavigationViewController)
/**
An optional delegation method that is fired after the
SideNavigationViewController closed.
*/
optional func sideNavigationViewDidClose(sideNavigationViewController: SideNavigationViewController)
/**
An optional delegation method that is fired when the
SideNavigationViewController pan gesture begins.
*/
optional func sideNavigationViewPanDidBegin(sideNavigationViewController: SideNavigationViewController, point: CGPoint)
/**
An optional delegation method that is fired when the
SideNavigationViewController pan gesture changes position.
*/
optional func sideNavigationViewPanDidChange(sideNavigationViewController: SideNavigationViewController, point: CGPoint)
/**
An optional delegation method that is fired when the
SideNavigationViewController pan gesture ends.
*/
optional func sideNavigationViewPanDidEnd(sideNavigationViewController: SideNavigationViewController, point: CGPoint)
/**
An optional delegation method that is fired when the
SideNavigationViewController tap gesture begins.
*/
optional func sideNavigationViewDidTap(sideNavigationViewController: SideNavigationViewController, point: CGPoint)
}
@objc(SideNavigationViewController)
public class SideNavigationViewController: UIViewController, UIGestureRecognizerDelegate {
/**
A CGPoint property that is used internally to track
the original position of the sideView when panning began.
*/
private var originalPosition: CGPoint = CGPointZero
/**
A UIPanGestureRecognizer property internally used for the
pan gesture.
*/
private var sidePanGesture: UIPanGestureRecognizer?
/**
A UITapGestureRecognizer property internally used for the
tap gesture.
*/
private var sideTapGesture: UITapGestureRecognizer?
/**
A CAShapeLayer property that is used as the backdrop when
opened. To change the opacity and color of the backdrop,
it is recommended to use the backdropOpcaity property and
backdropColor property, respectively.
*/
public private(set) lazy var backdropLayer: CAShapeLayer = CAShapeLayer()
/**
A CGFloat property that accesses the horizontal threshold of
the SideNavigationViewController. When the panning gesture has
ended, if the position is beyond the horizontal threshold,
the sideView is opened, if it is below the threshold, the
sideView is closed. The horizontal threshold is always at half
the width of the sideView.
*/
public private(set) var horizontalThreshold: CGFloat = 0
/**
A SideNavigationViewControllerDelegate property used to bind
the delegation object.
*/
public weak var delegate: SideNavigationViewControllerDelegate?
/**
A Boolean property used to enable and disable interactivity
with the mainViewController.
*/
public var userInteractionEnabled: Bool {
get {
return mainViewController.view.userInteractionEnabled
}
set(value) {
mainViewController.view.userInteractionEnabled = value
}
}
/**
A CGFloat property that sets the animation duration of the
sideView when closing and opening. Defaults to 0.25.
*/
public var animationDuration: CGFloat = 0.25
/**
A Boolean property that enables and disables the sideView from
opening and closing. Defaults to true.
*/
public var enabled: Bool = true {
didSet {
if enabled {
removeGestures(&sidePanGesture, tap: &sideTapGesture)
prepareGestures(&sidePanGesture, panSelector: "handlePanGesture:", tap: &sideTapGesture, tapSelector: "handleTapGesture:")
} else {
removeGestures(&sidePanGesture, tap: &sideTapGesture)
}
}
}
/**
A Boolean property that triggers the status bar to be hidden
when the sideView is opened. Defaults to true.
*/
public var hideStatusBar: Bool = true
/**
A MaterialDepth property that is used to set the depth of the
sideView when opened.
*/
public var depth: MaterialDepth = .Depth2
/**
A MaterialView property that is used to hide and reveal the
sideViewController. It is very rare that this property will
need to be accessed externally.
*/
public private(set) var sideView: MaterialView!
/// A CGFloat property to set the backdropLayer color opacity.
public var backdropOpacity: CGFloat = 0.5 {
didSet {
backdropLayer.backgroundColor = backdropColor?.colorWithAlphaComponent(backdropOpacity).CGColor
}
}
/// A UIColor property to set the backdropLayer color.
public var backdropColor: UIColor? {
didSet {
backdropLayer.backgroundColor = backdropColor?.colorWithAlphaComponent(backdropOpacity).CGColor
}
}
/**
A Boolean property that indicates whether the sideView
is opened.
*/
public var opened: Bool {
return sideView.x != -sideViewWidth
}
/**
A UIViewController property that references the active
main UIViewController. To swap the mainViewController, it
is recommended to use the transitionFromMainViewController
helper method.
*/
public private(set) var mainViewController: UIViewController!
/**
A UIViewController property that references the
active side UIViewController.
*/
public private(set) var sideViewController: UIViewController!
/**
A CGFloat property to access the width the sideView
opens up to.
*/
public private(set) var sideViewWidth: CGFloat = 240
/**
An initializer for the SideNavigationViewController.
- Parameter mainViewController: The main UIViewController.
- Parameter sideViewController: The side UIViewController.
*/
public convenience init(mainViewController: UIViewController, sideViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.sideViewController = sideViewController
prepareView()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
MaterialAnimation.animationDisabled { [unowned self] in
self.backdropLayer.frame = self.view.bounds
self.sideView.width = self.sideViewWidth
self.sideView.height = self.view.bounds.height
}
horizontalThreshold = sideViewWidth / 2
sideViewController.view.frame.size.width = sideView.width
sideViewController.view.frame.size.height = sideView.height
sideViewController.view.center = CGPointMake(sideView.width / 2, sideView.height / 2)
}
/**
A method to swap mainViewController objects.
- Parameter toViewController: The UIViewController to swap
with the active mainViewController.
- Parameter duration: A NSTimeInterval that sets the
animation duration of the transition.
- Parameter options: UIViewAnimationOptions thst are used
when animating the transition from the active mainViewController
to the toViewController.
- Parameter animations: An animation block that is executed during
the transition from the active mainViewController
to the toViewController.
- Parameter completion: A completion block that is execited after
the transition animation from the active mainViewController
to the toViewController has completed.
*/
public func transitionFromMainViewController(toViewController: UIViewController, duration: NSTimeInterval, options: UIViewAnimationOptions, animations: (() -> Void)?, completion: ((Bool) -> Void)?) {
mainViewController.willMoveToParentViewController(nil)
addChildViewController(toViewController)
toViewController.view.frame = view.bounds
transitionFromViewController(mainViewController,
toViewController: toViewController,
duration: duration,
options: options,
animations: animations,
completion: { [unowned self, mainViewController = self.mainViewController] (result: Bool) in
mainViewController.removeFromParentViewController()
toViewController.didMoveToParentViewController(self)
self.mainViewController = toViewController
self.userInteractionEnabled = !self.opened
completion?(result)
})
}
/**
A method that is used to set the width of the sideView when
opened. This is the recommended method of setting the sideView
width.
- Parameter width: A CGFloat value to set as the new width.
- Parameter hidden: A Boolean value of whether the sideView
should be hidden after the width has been updated or not.
- Parameter animated: A Boolean value that indicates to animate
the sideView width change.
*/
public func setSideViewWidth(width: CGFloat, hidden: Bool, animated: Bool) {
let w: CGFloat = (hidden ? -width : width) / 2
sideViewWidth = width
if animated {
MaterialAnimation.animateWithDuration(0.25, animations: { [unowned self] in
self.sideView.width = width
self.sideView.position.x = w
}) { [unowned self] in
self.userInteractionEnabled = false
}
} else {
MaterialAnimation.animationDisabled { [unowned self] in
self.sideView.width = width
self.sideView.position.x = w
}
}
}
/**
A method that toggles the sideView opened if previously closed,
or closed if previously opened.
- Parameter velocity: A CGFloat value that sets the
velocity of the user interaction when animating the
sideView. Defaults to 0.
*/
public func toggle(velocity: CGFloat = 0) {
opened ? close(velocity) : open(velocity)
}
/**
A method that opens the sideView.
- Parameter velocity: A CGFloat value that sets the
velocity of the user interaction when animating the
sideView. Defaults to 0.
*/
public func open(velocity: CGFloat = 0) {
toggleStatusBar(true)
backdropLayer.hidden = false
delegate?.sideNavigationViewWillOpen?(self)
MaterialAnimation.animateWithDuration(Double(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(sideView.x / velocity)))),
animations: { [unowned self] in
self.sideView.position = CGPointMake(self.sideView.width / 2, self.sideView.height / 2)
}) { [unowned self] in
self.userInteractionEnabled = false
self.showSideViewDepth()
self.delegate?.sideNavigationViewDidOpen?(self)
}
}
/**
A method that closes the sideView.
- Parameter velocity: A CGFloat value that sets the
velocity of the user interaction when animating the
sideView. Defaults to 0.
*/
public func close(velocity: CGFloat = 0) {
toggleStatusBar(false)
backdropLayer.hidden = true
delegate?.sideNavigationViewWillClose?(self)
MaterialAnimation.animateWithDuration(Double(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(sideView.x / velocity)))),
animations: { [unowned self] in
self.sideView.position = CGPointMake(-self.sideView.width / 2, self.sideView.height / 2)
}) { [unowned self] in
self.userInteractionEnabled = true
self.hideSideViewDepth()
self.delegate?.sideNavigationViewDidClose?(self)
}
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if enabled {
if gestureRecognizer == sidePanGesture {
return opened || enabled && isPointContainedWithinRect(touch.locationInView(view))
}
if opened && gestureRecognizer == sideTapGesture {
let point: CGPoint = touch.locationInView(view)
delegate?.sideNavigationViewDidTap?(self, point: point)
return !isPointContainedWithinViewController(sideView, point: point)
}
}
return false
}
/**
A method that is fired when the pan gesture is recognized
for the SideNavigationViewController.
- Parameter recognizer: A UIPanGestureRecognizer that is
passed to the handler when recognized.
*/
internal func handlePanGesture(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Began:
backdropLayer.hidden = false
originalPosition = sideView.position
toggleStatusBar(true)
showSideViewDepth()
delegate?.sideNavigationViewPanDidBegin?(self, point: sideView.position)
case .Changed:
let translation: CGPoint = recognizer.translationInView(sideView)
let w: CGFloat = sideView.width
MaterialAnimation.animationDisabled { [unowned self] in
self.sideView.position.x = self.originalPosition.x + translation.x > (w / 2) ? (w / 2) : self.originalPosition.x + translation.x
self.delegate?.sideNavigationViewPanDidChange?(self, point: self.sideView.position)
}
case .Ended, .Cancelled, .Failed:
let point: CGPoint = recognizer.velocityInView(recognizer.view)
let x: CGFloat = point.x >= 1000 || point.x <= -1000 ? point.x : 0
delegate?.sideNavigationViewPanDidEnd?(self, point: sideView.position)
if sideView.x <= CGFloat(floor(-sideViewWidth)) + horizontalThreshold || point.x <= -1000 {
close(x)
} else {
open(x)
}
case .Possible:break
}
}
/**
A method that is fired when the tap gesture is recognized
for the SideNavigationViewController.
- Parameter recognizer: A UITapGestureRecognizer that is
passed to the handler when recognized.
*/
internal func handleTapGesture(recognizer: UITapGestureRecognizer) {
if opened {
close()
}
}
/**
A method that generally prepares the SideNavigationViewController.
*/
private func prepareView() {
prepareBackdropLayer()
prepareMainViewController()
prepareSideView()
}
/**
A method that prepares the mainViewController.
*/
private func prepareMainViewController() {
prepareViewControllerWithinContainer(mainViewController, container: view)
mainViewController.view.frame = view.bounds
}
/**
A method that prepares the sideViewController.
*/
private func prepareSideViewController() {
sideViewController.view.clipsToBounds = true
prepareViewControllerWithinContainer(sideViewController, container: sideView)
}
/**
A method that prepares the sideView.
*/
private func prepareSideView() {
sideView = MaterialView()
sideView.frame = CGRectMake(0, 0, sideViewWidth, view.frame.height)
sideView.backgroundColor = MaterialColor.clear
view.addSubview(sideView)
MaterialAnimation.animationDisabled { [unowned self] in
self.sideView.position.x = -self.sideViewWidth / 2
self.sideView.zPosition = 1000
}
prepareSideViewController()
removeGestures(&sidePanGesture, tap: &sideTapGesture)
prepareGestures(&sidePanGesture, panSelector: "handlePanGesture:", tap: &sideTapGesture, tapSelector: "handleTapGesture:")
}
/**
A method that prepares the backdropLayer.
*/
private func prepareBackdropLayer() {
backdropColor = MaterialColor.black
backdropLayer.zPosition = 900
backdropLayer.hidden = true
view.layer.addSublayer(backdropLayer)
}
/**
A method that adds the passed in controller as a child of
the SideNavigationViewController within the passed in
container view.
- Parameter controller: A UIViewController to add as a child.
- Parameter container: A UIView that is the parent of the
passed in controller view within the view hierarchy.
*/
private func prepareViewControllerWithinContainer(controller: UIViewController, container: UIView) {
addChildViewController(controller)
container.addSubview(controller.view)
controller.didMoveToParentViewController(self)
}
/**
A method that prepares the gestures used within the
SideNavigationViewController.
- Parameter pan: A UIPanGestureRecognizer that is used to
recognize pan gestures.
- Parameter panSelector: A Selector that is fired when the
pan gesture is recognized.
- Parameter tap: A UITapGestureRecognizer that is used to
recognize tap gestures.
- Parameter tapSelector: A Selector that is fired when the
tap gesture is recognized.
*/
private func prepareGestures(inout pan: UIPanGestureRecognizer?, panSelector: Selector, inout tap: UITapGestureRecognizer?, tapSelector: Selector) {
if nil == pan {
pan = UIPanGestureRecognizer(target: self, action: panSelector)
pan!.delegate = self
view.addGestureRecognizer(pan!)
}
if nil == tap {
tap = UITapGestureRecognizer(target: self, action: tapSelector)
tap!.delegate = self
view.addGestureRecognizer(tap!)
}
}
/**
A method that removes the passed in pan and tap gesture
recognizers.
- Parameter pan: A UIPanGestureRecognizer that should be
removed from the SideNavigationViewController.
- Parameter tap: A UITapGestureRecognizer that should be
removed from the SideNavigationViewController.
*/
private func removeGestures(inout pan: UIPanGestureRecognizer?, inout tap: UITapGestureRecognizer?) {
if let v: UIPanGestureRecognizer = pan {
view.removeGestureRecognizer(v)
pan = nil
}
if let v: UITapGestureRecognizer = tap {
view.removeGestureRecognizer(v)
tap = nil
}
}
/**
A method to toggle the status bar from a reveal state to
hidden state. The hideStatusBar property needs to be set
to true in order for this method to have any affect.
- Parameter hide: A Boolean indicating to show or hide
the status bar.
*/
private func toggleStatusBar(hide: Bool = false) {
if hideStatusBar {
UIApplication.sharedApplication().statusBarHidden = hide
}
}
/**
A method that determines whether the passed point is
contained within the bounds of the horizontalThreshold
and height of the SideNavigationViewController view frame
property.
- Parameter point: A CGPoint to test against.
- Returns: A Boolean of the result, true if yes, false
otherwise.
*/
private func isPointContainedWithinRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(CGRectMake(0, 0, horizontalThreshold, view.frame.height), point)
}
/**
A method that determines whether the passed in point is
contained within the bounds of the passed in container view.
- Parameter container: A UIView that sets the bounds to test
against.
- Parameter point: A CGPoint to test whether or not it is
within the bounds of the container parameter.
- Returns: A Boolean of the result, true if yes, false
otherwise.
*/
private func isPointContainedWithinViewController(container: UIView, point: CGPoint) -> Bool {
return CGRectContainsPoint(container.frame, point)
}
/**
A method that adds the depth to the sideView depth property.
*/
private func showSideViewDepth() {
MaterialAnimation.animationDisabled { [unowned self] in
self.sideView.depth = self.depth
}
}
/**
A method that removes the depth from the sideView depth
property.
*/
private func hideSideViewDepth() {
MaterialAnimation.animationDisabled { [unowned self] in
self.sideView.depth = .None
}
}
}
|
e04dc1896ba8677ec2152c35c2a2e6ba
| 32.899514 | 200 | 0.768252 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/MGalleryItem.swift
|
gpl-2.0
|
1
|
//
// MGalleryItem.swift
// TelegramMac
//
// Created by keepcoder on 15/12/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import TelegramCore
import SwiftSignalKit
import TGUIKit
final class GPreviewValueClass {
let value: GPreviewValue
init(_ value: GPreviewValue) {
self.value = value
}
}
enum GPreviewValue {
case image(NSImage?, ImageOrientation?)
case view(NSView?)
var hasValue: Bool {
switch self {
case let .image(img, _):
return img != nil
case let .view(view):
return view != nil
}
}
var size: NSSize? {
switch self {
case let .image(img, _):
return img?.size
case let .view(view):
return view?.frame.size
}
}
var rotation: ImageOrientation? {
switch self {
case let .image(_, rotation):
return rotation
case .view:
return nil
}
}
var image: NSImage? {
switch self {
case let .image(img, _):
return img
case .view:
return nil
}
}
}
func <(lhs: GalleryEntry, rhs: GalleryEntry) -> Bool {
switch lhs {
case .message(let lhsEntry):
if case let .message(rhsEntry) = rhs {
return lhsEntry < rhsEntry
} else {
return false
}
case let .secureIdDocument(_, lhsIndex):
if case let .secureIdDocument(_, rhsIndex) = rhs {
return lhsIndex < rhsIndex
} else {
return false
}
case let .photo(lhsIndex, _, _, _, _, _, _):
if case let .photo(rhsIndex, _, _, _, _, _, _) = rhs {
return lhsIndex < rhsIndex
} else {
return false
}
case let .instantMedia(lhsMedia, _):
if case let .instantMedia(rhsMedia, _) = rhs {
return lhsMedia.index < rhsMedia.index
} else {
return false
}
}
}
func ==(lhs: GalleryEntry, rhs: GalleryEntry) -> Bool {
switch lhs {
case .message(let lhsEntry):
if case let .message(rhsEntry) = rhs {
return lhsEntry.stableId == rhsEntry.stableId
} else {
return false
}
case let .secureIdDocument(lhsEntry, lhsIndex):
if case let .secureIdDocument(rhsEntry, rhsIndex) = rhs {
return lhsEntry.document.isEqual(to: rhsEntry.document) && lhsIndex == rhsIndex
} else {
return false
}
case let .photo(lhsIndex, lhsStableId, lhsPhoto, lhsReference, lhsPeer, _, lhsDate):
if case let .photo(rhsIndex, rhsStableId, rhsPhoto, rhsReference, rhsPeer, _, rhsDate) = rhs {
return lhsIndex == rhsIndex && lhsStableId == rhsStableId && lhsPhoto.isEqual(to: rhsPhoto) && lhsReference == rhsReference && lhsPeer.isEqual(rhsPeer) && lhsDate == rhsDate
} else {
return false
}
case let .instantMedia(lhsMedia, _):
if case let .instantMedia(rhsMedia, _) = rhs {
return lhsMedia == rhsMedia
} else {
return false
}
}
}
enum GalleryEntry : Comparable, Identifiable {
case message(ChatHistoryEntry)
case photo(index:Int, stableId:AnyHashable, photo:TelegramMediaImage, reference: TelegramMediaImageReference?, peer: Peer, message: Message?, date: TimeInterval)
case instantMedia(InstantPageMedia, Message?)
case secureIdDocument(SecureIdDocumentValue, Int)
var stableId: AnyHashable {
switch self {
case let .message(entry):
return entry.stableId
case let .photo(_, stableId, _, _, _, _, _):
return stableId
case let .instantMedia(media, _):
return media.index
case let .secureIdDocument(document, _):
return document.stableId
}
}
var canShare: Bool {
return message != nil && !message!.isScheduledMessage && !message!.containsSecretMedia && !message!.isCopyProtected()
}
var interfaceState:(PeerId, TimeInterval)? {
switch self {
case let .message(entry):
if let peerId = entry.message!.effectiveAuthor?.id {
return (peerId, TimeInterval(entry.message!.timestamp))
}
case let .instantMedia(_, message):
if let message = message, let peerId = message.effectiveAuthor?.id {
return (peerId, TimeInterval(message.timestamp))
}
case let .photo(_, _, _, _, peer, _, date):
return (peer.id, date)
default:
return nil
}
return nil
}
var file:TelegramMediaFile? {
switch self {
case .message(let entry):
if let media = entry.message!.effectiveMedia as? TelegramMediaFile {
return media
} else if let media = entry.message!.media[0] as? TelegramMediaWebpage {
switch media.content {
case let .Loaded(content):
return content.file
default:
return nil
}
}
case .instantMedia(let media, _):
return media.media as? TelegramMediaFile
default:
return nil
}
return nil
}
var webpage: TelegramMediaWebpage? {
switch self {
case let .message(entry):
return entry.message!.media[0] as? TelegramMediaWebpage
case let .instantMedia(media, _):
return media.media as? TelegramMediaWebpage
default:
return nil
}
}
func imageReference( _ image: TelegramMediaImage) -> ImageMediaReference {
switch self {
case let .message(entry):
return ImageMediaReference.message(message: MessageReference(entry.message!), media: image)
case let .instantMedia(media, _):
return ImageMediaReference.webPage(webPage: WebpageReference(media.webpage), media: image)
case .secureIdDocument:
return ImageMediaReference.standalone(media: image)
case .photo:
return ImageMediaReference.standalone(media: image)
}
}
var peer: Peer? {
switch self {
case let .photo(_, _, _, _, peer, _, _):
return peer
default:
return nil
}
}
func peerPhotoResource() -> MediaResourceReference {
switch self {
case let .photo(_, _, image, _, peer, message, _):
if let representation = image.representationForDisplayAtSize(PixelDimensions(1280, 1280)) {
if let message = message {
return .media(media: .message(message: MessageReference(message), media: image), resource: representation.resource)
}
if let peerReference = PeerReference(peer) {
return .avatar(peer: peerReference, resource: representation.resource)
} else {
return .standalone(resource: representation.resource)
}
} else {
preconditionFailure()
}
default:
preconditionFailure()
}
}
func fileReference( _ file: TelegramMediaFile) -> FileMediaReference {
switch self {
case let .message(entry):
return FileMediaReference.message(message: MessageReference(entry.message!), media: file)
case let .instantMedia(media, _):
return FileMediaReference.webPage(webPage: WebpageReference(media.webpage), media: file)
case .secureIdDocument:
return FileMediaReference.standalone(media: file)
case .photo:
return FileMediaReference.standalone(media: file)
}
}
var identifier: String {
switch self {
case let .message(entry):
return "\(entry.message?.stableId ?? 0)"
case .photo(_, let stableId, _, _, _, _, _):
return "\(stableId)"
case .instantMedia:
return "\(stableId)"
case let .secureIdDocument(document, _):
return "secureId: \(document.document.id.hashValue)"
}
}
var chatEntry: ChatHistoryEntry? {
switch self {
case let .message(entry):
return entry
default:
return nil
}
}
var message:Message? {
switch self {
case let .message(entry):
return entry.message
case let .instantMedia(_, message):
return message
default:
return nil
}
}
var photo:TelegramMediaImage? {
switch self {
case .message:
return nil
case let .photo(_, _, photo, _, _, _, _):
return photo
default:
return nil
}
}
var photoReference:TelegramMediaImageReference? {
switch self {
case .message:
return nil
case let .photo(_, _, _, reference, _, _, _):
return reference
default:
return nil
}
}
}
func ==(lhs: MGalleryItem, rhs: MGalleryItem) -> Bool {
return lhs.entry == rhs.entry
}
func <(lhs: MGalleryItem, rhs: MGalleryItem) -> Bool {
return lhs.entry < rhs.entry
}
private final class MGalleryItemView : NSView {
init() {
super.init(frame: NSZeroRect)
self.wantsLayer = true
self.layerContentsRedrawPolicy = .never
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isOpaque: Bool {
return true
}
deinit {
var bp:Int = 0
bp += 1
}
}
class MGalleryItem: NSObject, Comparable, Identifiable {
let image:Promise<GPreviewValueClass> = Promise()
let view:Promise<NSView> = Promise()
let size:Promise<NSSize> = Promise()
let magnify:Promise<CGFloat> = Promise(1)
let rotate: ValuePromise<ImageOrientation?> = ValuePromise(nil, ignoreRepeated: true)
private let appearSignal = ValuePromise(false, ignoreRepeated: true)
var appearValue:Signal<Bool, NoError> {
return appearSignal.get()
}
let disposable:MetaDisposable = MetaDisposable()
let fetching:MetaDisposable = MetaDisposable()
private let magnifyDisposable = MetaDisposable()
private let viewDisposable:MetaDisposable = MetaDisposable()
let path:Promise<String> = Promise()
let entry:GalleryEntry
let context: AccountContext
private var _pagerSize: NSSize
private var captionSeized: Bool = false
var pagerSize:NSSize {
var pagerSize = _pagerSize
if let caption = caption, !captionSeized {
caption.measure(width: pagerSize.width - 300)
captionSeized = true
}
if let caption = caption {
pagerSize.height -= min(200, (caption.layoutSize.height + 120))
}
return pagerSize
}
let caption: TextViewLayout?
var disableAnimations: Bool = false
var modifiedSize: NSSize? = nil
private(set) var magnifyValue:CGFloat = 1.0
var stableId: AnyHashable {
return entry.stableId
}
var identifier:NSPageController.ObjectIdentifier {
return entry.identifier + self.className
}
var sizeValue:NSSize {
return pagerSize
}
var minMagnify:CGFloat {
return 0.25
}
var maxMagnify:CGFloat {
return 8.0
}
func smallestValue(for size: NSSize) -> NSSize {
return pagerSize
}
var status:Signal<MediaResourceStatus, NoError> {
return .single(.Local)
}
var realStatus:Signal<MediaResourceStatus, NoError> {
return self.status
}
func toggleFullScreen() {
}
func togglePlayerOrPause() {
}
func rewindBack() {
}
func rewindForward() {
}
init(_ context: AccountContext, _ entry:GalleryEntry, _ pagerSize:NSSize) {
self.entry = entry
self.context = context
self._pagerSize = pagerSize
if let message = entry.message, !message.text.isEmpty, !(message.effectiveMedia is TelegramMediaWebpage) {
let caption = message.text
let attr = NSMutableAttributedString()
_ = attr.append(string: caption.trimmed.fullTrimmed, color: .white, font: .normal(.text))
let controller = context.bindings.rootNavigation().controller as? ChatController
if let peer = message.peers[message.id.peerId] {
var type: ParsingType = [.Links, .Mentions, .Hashtags]
if peer.isGroup || peer.isSupergroup, peer.canSendMessage() {
if let _ = controller {
type.insert(.Commands)
}
}
attr.detectLinks(type: type, context: context, color: .linkColor, openInfo: { peerId, toChat, postId, action in
let navigation = context.bindings.rootNavigation()
let controller = navigation.controller
if toChat {
if peerId == (controller as? ChatController)?.chatInteraction.peerId {
if let postId = postId {
(controller as? ChatController)?.chatInteraction.focusMessageId(nil, postId, TableScrollState.CenterEmpty)
}
} else {
navigation.push(ChatAdditionController(context: context, chatLocation: .peer(peerId), messageId: postId, initialAction: action))
}
} else {
navigation.push(PeerInfoController(context: context, peerId: peerId))
}
viewer?.close()
}, hashtag: { hashtag in
context.bindings.globalSearch(hashtag)
viewer?.close()
}, command: { commandText in
_ = Sender.enqueue(input: ChatTextInputState(inputText: commandText), context: context, peerId: peer.id, replyId: nil, atDate: nil).start()
viewer?.close()
}, applyProxy: { server in
applyExternalProxy(server, accountManager: context.sharedContext.accountManager)
viewer?.close()
})
}
var spoilers:[TextViewLayout.Spoiler] = []
for attr in message.attributes {
if let attr = attr as? TextEntitiesMessageAttribute {
for entity in attr.entities {
switch entity.type {
case .Spoiler:
let color: NSColor = NSColor.white
spoilers.append(.init(range: NSMakeRange(entity.range.lowerBound, entity.range.upperBound - entity.range.lowerBound), color: color, isRevealed: false))
default:
break
}
}
}
}
self.caption = TextViewLayout(attr, alignment: .left, spoilers: spoilers)
self.caption?.interactions = TextViewInteractions(processURL: { link in
if let link = link as? inAppLink {
execute(inapp: link, afterComplete: { value in
if value {
viewer?.close()
}
})
}
})
} else {
self.caption = nil
}
super.init()
var first:Bool = true
let image = combineLatest(self.image.get() |> map { $0.value }, view.get()) |> map { [weak self] value, view in
guard let `self` = self else {return}
view.layer?.contents = value.image
if !first && !self.disableAnimations {
view.layer?.animateContents()
}
self.disableAnimations = false
view.layer?.backgroundColor = self.backgroundColor.cgColor
if let magnify = view.superview?.superview as? MagnifyView {
var size = magnify.contentSize
if self is MGalleryPhotoItem || self is MGalleryPeerPhotoItem {
if value.rotation == nil {
size = value.size?.aspectFitted(size) ?? size
} else {
size = value.size ?? size
}
}
magnify.contentSize = size
}
first = false
}
viewDisposable.set(image.start())
magnifyDisposable.set(magnify.get().start(next: { [weak self] (magnify) in
self?.magnifyValue = magnify
}))
}
var backgroundColor: NSColor {
return .black
}
var isGraphicFile: Bool {
if self.entry.message?.effectiveMedia is TelegramMediaFile {
return true
} else {
return false
}
}
func singleView() -> NSView {
return MGalleryItemView()
}
func request(immediately:Bool = true) {
// self.caption?.measure(width: sizeValue.width)
}
func fetch() {
}
var notFittedSize: NSSize {
return sizeValue
}
func cancel() {
fetching.set(nil)
}
func appear(for view:NSView?) {
appearSignal.set(true)
}
func disappear(for view:NSView?) {
appearSignal.set(false)
}
deinit {
disposable.dispose()
viewDisposable.dispose()
fetching.dispose()
magnifyDisposable.dispose()
}
}
|
fd4f8832aa12bc5bd7bb3187f08f4367
| 30.370242 | 185 | 0.542908 | false | false | false | false |
malaonline/iOS
|
refs/heads/master
|
mala-ios/Resource/Application/Fonts.swift
|
mit
|
1
|
//
// Fonts.swift
// mala-ios
//
// Created by 王新宇 on 2017/3/6.
// Copyright © 2017年 Mala Online. All rights reserved.
//
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIFont
typealias Font = UIFont
#elseif os(OSX)
import AppKit.NSFont
typealias Font = NSFont
#endif
protocol FontConvertible {
func font(_ size: CGFloat) -> Font!
}
extension FontConvertible where Self: RawRepresentable, Self.RawValue == String {
func font(_ size: CGFloat) -> Font! {
return Font(font: self, size: size)
}
}
extension Font {
convenience init!<FontType: FontConvertible>
(font: FontType, size: CGFloat)
where FontType: RawRepresentable, FontType.RawValue == String {
self.init(name: font.rawValue, size: size)
}
}
struct FontFamily {
enum HeitiSC: String, FontConvertible {
case Light = "STHeitiSC-Light"
case Medium = "STHeitiSC-Medium"
}
enum Helvetica: String, FontConvertible {
case Regular = "Helvetica"
case Bold = "Helvetica-Bold"
case Light = "Helvetica-Light"
}
enum HelveticaNeue: String, FontConvertible {
case Regular = "HelveticaNeue"
case Bold = "HelveticaNeue-Bold"
case Light = "HelveticaNeue-Light"
case Medium = "HelveticaNeue-Medium"
case Thin = "HelveticaNeue-Thin"
}
enum PingFangSC: String, FontConvertible {
case Light = "PingFangSC-Light"
case Medium = "PingFangSC-Medium"
case Regular = "PingFangSC-Regular"
case Semibold = "PingFangSC-Semibold"
case Thin = "PingFangSC-Thin"
case Ultralight = "PingFangSC-Ultralight"
}
}
|
8d423c497c6845006eaa47c434a2f47f
| 27.836066 | 85 | 0.645253 | false | false | false | false |
duliodenis/fabyo
|
refs/heads/master
|
Fabyo/Fabyo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Fabyo
//
// Created by Dulio Denis on 8/31/15.
// Copyright (c) 2015 Dulio Denis. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var library: JSON = JSON.null
let textCellIdentifier = "Cell"
let bookSegueIdentifier = "BookView"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
booksLookup()
}
func booksLookup() {
let urlPath = NSURL(string: "https://librivox.org/api/feed/audiobooks/?format=json")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urlPath) {
data, response, error -> Void in
if ((error) != nil) {
print(error!.localizedDescription, terminator: "")
}
var jsonError : NSError?
var jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
if ((jsonError) != nil) {
print(jsonError!.localizedDescription, terminator: "")
}
// update the UITableView on the main thread
dispatch_async(dispatch_get_main_queue()) {
self.library = JSON(data: data!)
let numberOfBooks = self.library["books"].count
print("Results are \(numberOfBooks) books\n", terminator: "")
self.tableView.reloadData()
}
}
task.resume()
}
// MARK: - TableView Delegte Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let books = library["books"]
return books.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let row = indexPath.row
if let bookName = library["books"][row]["title"].string as String! {
cell.textLabel?.text = bookName
}
if let authorFirstName = library["books"][row]["authors"][0]["first_name"].string as String! {
if let authorLastName = library["books"][row]["authors"][0]["last_name"].string as String! {
cell.detailTextLabel?.text = "\(authorFirstName) \(authorLastName)"
}
}
return cell
}
// MARK: - Navigation Control
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == bookSegueIdentifier {
if let bookVC: BookViewController = segue.destinationViewController as? BookViewController {
if let bookIndex = tableView.indexPathForSelectedRow?.row {
bookVC.book.title = library["books"][bookIndex]["title"].string
let description = library["books"][bookIndex]["description"].string
let cleanDescription = description!.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
bookVC.book.description = cleanDescription
}
}
}
}
}
|
5aef0a08a49cd5295749b3fcb912aa89
| 34.145631 | 166 | 0.594475 | false | false | false | false |
kdw9/TIY-Assignments
|
refs/heads/master
|
High Voltage Home Assignment/High Voltage Home Assignment/HighVoltageTableViewController.swift
|
cc0-1.0
|
1
|
//
// HighVoltageTableViewController.swift
// High Voltage Home Assignment
//
// Created by Keron Williams on 10/25/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
// This protocol is for the class that is sending the data to the view that will make data appear in the table view
protocol FormulaListTableViewControllerDelegate
{
func formulaWasChosen(chosenFormula: String)
}
class HighVoltageTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, FormulaListTableViewControllerDelegate
{
var formulas = Array<OperatorBrain>()
@IBOutlet weak var refresh: UIBarButtonItem!
var remainingOperatorNames = ["Watts", "Volts", "Amps", "Ohms"]
override func viewDidLoad()
{
super.viewDidLoad()
title = "High Voltage"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return formulas.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("HighVoltageCell", forIndexPath: indexPath)
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
// This code is to initialize the pop over segue
if segue.identifier == "ShowFormulaListPopOverSegue"
{
let destVC = segue.destinationViewController as! FormulaListTableViewController
// This Code is tell the destination View controller to asssign the array of strings in the remaingOperatorName to the propert in the formula list class
destVC.electricFormulas = remainingOperatorNames
// Now I am setting the size of the pop over controller
destVC.popoverPresentationController?.delegate = self
destVC.delegate = self
let contentHeight = 44.0 * CGFloat(remainingOperatorNames.count)
destVC.preferredContentSize = CGSize(width: 200.0, height: contentHeight)
}
}
// MARK: - UIPopoverPresentationController Delegate
// This is tell the delegate to give me the style I want, I selected None
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return .None
}
//MARL: - CharacterListTableViewController Delegate
// This makes the pop over view controller dissappear
func formulaWasChosen(chosenFormula: String)
{
navigationController?.dismissViewControllerAnimated(true, completion: nil)
formulas.append(chosenFormula)
let rowToRemove = (remainingOperatorNames as NSArray). indexOfObject(chosenFormula)
remainingOperatorNames.removeAtIndex(rowToRemove)
if remainingOperatorNames.count == 0
{
refresh.enabled = false
}
tableView?.reloadData()
}
}
|
794d48cd11420f463b14aaf46ad126a7
| 32.825 | 160 | 0.686622 | false | false | false | false |
ddimitrov90/EverliveSDK
|
refs/heads/master
|
EverliveSDK/MasterKeyLoginMethod.swift
|
mit
|
2
|
//
// MasterKeyLoginMethod.swift
// EverliveSwift
//
// Created by Dimitar Dimitrov on 3/12/16.
// Copyright © 2016 ddimitrov. All rights reserved.
//
import Foundation
import SwiftyJSON
public class MasterKeyLoginMethod : LoginMethod {
public var masterKey: String
required public init(masterKey: String){
self.masterKey = masterKey
}
public func prepareLogin(request: EverliveRequest) {
var payload:[String:String] = [:]
payload["masterkey"] = self.masterKey
payload["grant_type"] = "masterkey"
let jsonPayload:JSON = JSON(payload)
let body: String = jsonPayload.rawString(NSUTF8StringEncoding, options: NSJSONWritingOptions(rawValue: 0))!
request.body = body.dataUsingEncoding(NSUTF8StringEncoding)
}
}
|
addc3e7ff2c86636164314c97c48daf4
| 27.535714 | 115 | 0.690476 | false | false | false | false |
xiankuncheng/ContactList
|
refs/heads/master
|
ContactList/Classes/Modules/List/Application Logic/Model/Contact.swift
|
mit
|
1
|
//
// ContactModel.swift
// ContactList
//
// Created by XiankunCheng on 26/07/17.
// Copyright © 2017 Xiankun Cheng. All rights reserved.
//
import UIKit
import ObjectMapper
class Contact: Mappable {
var id: String?
var name: String?
var username: String?
var email: String?
var address: Address?
var phone: String?
var website: String?
var company: Company?
required init?(map: Map){
}
init() {
}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
username <- map["username"]
email <- map["email"]
address <- map["address"]
phone <- map["phone"]
website <- map["website"]
company <- map["company"]
}
}
class Address: Mappable {
var street: String?
var suite: String?
var city: String?
var zipcode: String?
var geo: Geo?
required init?(map: Map){
}
func mapping(map: Map) {
street <- map["street"]
suite <- map["suite"]
city <- map["city"]
zipcode <- map["zipcode"]
geo <- map["geo"]
}
func fullAddress() -> String {
var fullAddress: String = street!
fullAddress += ", " + suite!
fullAddress += ", " + city!
fullAddress += ", " + zipcode!
return fullAddress
}
}
class Geo: Mappable {
var lat: String?
var lng: String?
required init?(map: Map){
}
func mapping(map: Map) {
lat <- map["lat"]
lng <- map["lng"]
}
}
class Company: Mappable {
var name: String?
var catchPhrase: String?
var bs: String?
required init?(map: Map){
}
func mapping(map: Map) {
name <- map["name"]
catchPhrase <- map["catchPhrase"]
bs <- map["bs"]
}
func companyDisplayName() -> String {
var companyDisplayName: String = name!
companyDisplayName += "\n" + catchPhrase!
companyDisplayName += "\n" + bs!
return companyDisplayName
}
}
|
e69bc7f310ed1bbe1e800ed807d25686
| 18.587156 | 56 | 0.51007 | false | false | false | false |
Antondomashnev/Sourcery
|
refs/heads/master
|
Pods/Yams/Sources/Yams/Parser.swift
|
mit
|
1
|
//
// Parser.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
import CYaml
#endif
import Foundation
/// Parse all YAML documents in a String
/// and produce corresponding Swift objects.
///
/// - Parameters:
/// - yaml: String
/// - resolver: Resolver
/// - constructor: Constructor
/// - Returns: YamlSequence<Any>
/// - Throws: YamlError
public func load_all(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) throws -> YamlSequence<Any> {
let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor)
return YamlSequence { try parser.nextRoot()?.any }
}
/// Parse the first YAML document in a String
/// and produce the corresponding Swift object.
///
/// - Parameters:
/// - yaml: String
/// - resolver: Resolver
/// - constructor: Constructor
/// - Returns: Any?
/// - Throws: YamlError
public func load(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) throws -> Any? {
return try Parser(yaml: yaml, resolver: resolver, constructor: constructor).singleRoot()?.any
}
/// Parse all YAML documents in a String
/// and produce corresponding representation trees.
///
/// - Parameters:
/// - yaml: String
/// - resolver: Resolver
/// - constructor: Constructor
/// - Returns: YamlSequence<Node>
/// - Throws: YamlError
public func compose_all(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) throws -> YamlSequence<Node> {
let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor)
return YamlSequence(parser.nextRoot)
}
/// Parse the first YAML document in a String
/// and produce the corresponding representation tree.
///
/// - Parameters:
/// - yaml: String
/// - resolver: Resolver
/// - constructor: Constructor
/// - Returns: Node?
/// - Throws: YamlError
public func compose(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) throws -> Node? {
return try Parser(yaml: yaml, resolver: resolver, constructor: constructor).singleRoot()
}
/// Sequence that holds error
public struct YamlSequence<T>: Sequence, IteratorProtocol {
public private(set) var error: Swift.Error?
public mutating func next() -> T? {
do {
return try closure()
} catch {
self.error = error
return nil
}
}
fileprivate init(_ closure: @escaping () throws -> T?) {
self.closure = closure
}
private let closure: () throws -> T?
}
public final class Parser {
// MARK: public
public let yaml: String
public let resolver: Resolver
public let constructor: Constructor
/// Set up Parser.
///
/// - Parameter string: YAML
/// - Parameter resolver: Resolver
/// - Parameter constructor: Constructor
/// - Throws: YamlError
public init(yaml string: String,
resolver: Resolver = .default,
constructor: Constructor = .default) throws {
yaml = string
self.resolver = resolver
self.constructor = constructor
yaml_parser_initialize(&parser)
#if USE_UTF8
yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING)
utf8CString = string.utf8CString
utf8CString.withUnsafeBytes { bytes in
let input = bytes.baseAddress?.assumingMemoryBound(to: UInt8.self)
yaml_parser_set_input_string(&parser, input, bytes.count - 1)
}
#else
// use native endian
let isLittleEndian = 1 == 1.littleEndian
yaml_parser_set_encoding(&parser, isLittleEndian ? YAML_UTF16LE_ENCODING : YAML_UTF16BE_ENCODING)
let encoding: String.Encoding
#if swift(>=3.1)
encoding = isLittleEndian ? .utf16LittleEndian : .utf16BigEndian
#else
/*
```
"".data(using: .utf16LittleEndian).withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
bytes == nil // true on Swift 3.0.2, false on Swift 3.1
}
```
for avoiding above, use `.utf16` if yaml is empty.
*/
encoding = yaml.isEmpty ? .utf16 : isLittleEndian ? .utf16LittleEndian : .utf16BigEndian
#endif
data = yaml.data(using: encoding)!
data.withUnsafeBytes { bytes in
yaml_parser_set_input_string(&parser, bytes, data.count)
}
#endif
try parse() // Drop YAML_STREAM_START_EVENT
}
deinit {
yaml_parser_delete(&parser)
}
/// Parse next document and return root Node.
///
/// - Returns: next Node
/// - Throws: YamlError
public func nextRoot() throws -> Node? {
guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil }
return try loadDocument()
}
public func singleRoot() throws -> Node? {
guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil }
let node = try loadDocument()
let event = try parse()
if event.type != YAML_STREAM_END_EVENT {
throw YamlError.composer(
context: YamlError.Context(text: "expected a single document in the stream",
mark: Mark(line: 1, column: 1)),
problem: "but found another document", event.startMark,
yaml: yaml
)
}
return node
}
// MARK: private
fileprivate var anchors = [String: Node]()
fileprivate var parser = yaml_parser_t()
#if USE_UTF8
private let utf8CString: ContiguousArray<CChar>
#else
private let data: Data
#endif
}
// MARK: implementation details
extension Parser {
fileprivate var streamEndProduced: Bool {
return parser.stream_end_produced != 0
}
fileprivate func loadDocument() throws -> Node {
let node = try loadNode(from: parse())
try parse() // Drop YAML_DOCUMENT_END_EVENT
return node
}
private func loadNode(from event: Event) throws -> Node {
switch event.type {
case YAML_ALIAS_EVENT:
return try loadAlias(from: event)
case YAML_SCALAR_EVENT:
return try loadScalar(from: event)
case YAML_SEQUENCE_START_EVENT:
return try loadSequence(from: event)
case YAML_MAPPING_START_EVENT:
return try loadMapping(from: event)
default:
fatalError("unreachable")
}
}
@discardableResult
fileprivate func parse() throws -> Event {
let event = Event()
guard yaml_parser_parse(&parser, &event.event) == 1 else {
throw YamlError(from: parser, with: yaml)
}
return event
}
private func loadAlias(from event: Event) throws -> Node {
guard let alias = event.aliasAnchor else {
fatalError("unreachable")
}
guard let node = anchors[alias] else {
throw YamlError.composer(context: nil,
problem: "found undefined alias", event.startMark,
yaml: yaml)
}
return node
}
private func loadScalar(from event: Event) throws -> Node {
let node = Node.scalar(.init(event.scalarValue, tag(event.scalarTag), event.scalarStyle, event.startMark))
if let anchor = event.scalarAnchor {
anchors[anchor] = node
}
return node
}
private func loadSequence(from firstEvent: Event) throws -> Node {
var array = [Node]()
var event = try parse()
while event.type != YAML_SEQUENCE_END_EVENT {
array.append(try loadNode(from: event))
event = try parse()
}
let node = Node.sequence(.init(array, tag(firstEvent.sequenceTag), event.sequenceStyle, event.startMark))
if let anchor = firstEvent.sequenceAnchor {
anchors[anchor] = node
}
return node
}
private func loadMapping(from firstEvent: Event) throws -> Node {
var pairs = [(Node, Node)]()
var event = try parse()
while event.type != YAML_MAPPING_END_EVENT {
let key = try loadNode(from: event)
event = try parse()
let value = try loadNode(from: event)
pairs.append((key, value))
event = try parse()
}
let node = Node.mapping(.init(pairs, tag(firstEvent.mappingTag), event.mappingStyle, event.startMark))
if let anchor = firstEvent.mappingAnchor {
anchors[anchor] = node
}
return node
}
private func tag(_ string: String?) -> Tag {
let tagName = string.map(Tag.Name.init(rawValue:)) ?? .implicit
return Tag(tagName, resolver, constructor)
}
}
/// Representation of `yaml_event_t`
fileprivate class Event {
var event = yaml_event_t()
deinit { yaml_event_delete(&event) }
var type: yaml_event_type_t {
return event.type
}
// alias
var aliasAnchor: String? {
return string(from: event.data.alias.anchor)
}
// scalar
var scalarAnchor: String? {
return string(from: event.data.scalar.anchor)
}
var scalarStyle: Node.Scalar.Style {
// swiftlint:disable:next force_unwrapping
return Node.Scalar.Style(rawValue: event.data.scalar.style.rawValue)!
}
var scalarTag: String? {
guard event.data.scalar.plain_implicit == 0,
event.data.scalar.quoted_implicit == 0 else {
return nil
}
return string(from: event.data.scalar.tag)
}
var scalarValue: String {
// scalar may contain NULL characters
let buffer = UnsafeBufferPointer(start: event.data.scalar.value,
count: event.data.scalar.length)
// libYAML converts scalar characters into UTF8 if input is other than YAML_UTF8_ENCODING
return String(bytes: buffer, encoding: .utf8)!
}
// sequence
var sequenceAnchor: String? {
return string(from: event.data.sequence_start.anchor)
}
var sequenceStyle: Node.Sequence.Style {
// swiftlint:disable:next force_unwrapping
return Node.Sequence.Style(rawValue: event.data.sequence_start.style.rawValue)!
}
var sequenceTag: String? {
return event.data.sequence_start.implicit != 0
? nil : string(from: event.data.sequence_start.tag)
}
// mapping
var mappingAnchor: String? {
return string(from: event.data.scalar.anchor)
}
var mappingStyle: Node.Mapping.Style {
// swiftlint:disable:next force_unwrapping
return Node.Mapping.Style(rawValue: event.data.mapping_start.style.rawValue)!
}
var mappingTag: String? {
return event.data.mapping_start.implicit != 0
? nil : string(from: event.data.sequence_start.tag)
}
// start_mark
var startMark: Mark {
return Mark(line: event.start_mark.line + 1, column: event.start_mark.column + 1)
}
}
fileprivate func string(from pointer: UnsafePointer<UInt8>!) -> String? {
return String.decodeCString(pointer, as: UTF8.self, repairingInvalidCodeUnits: true)?.result
}
|
2ff0ca287c1da1d7de44cbac60227495
| 32.153846 | 114 | 0.596546 | false | false | false | false |
coderMONSTER/iosstar
|
refs/heads/master
|
iOSStar/Scenes/Market/Controller/MarketSearchViewController.swift
|
gpl-3.0
|
1
|
//
// MarketSearchViewController.swift
// iOSStar
//
// Created by J-bb on 17/5/10.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class MarketSearchViewController: UIViewController , UITextFieldDelegate{
@IBOutlet weak var searchTextField: UITextField!
lazy var requestModel: MarketSearhModel = {
let model = MarketSearhModel()
return model
}()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var backView: UIView!
var dataArry = [SearchResultModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
backView.layer.cornerRadius = 1
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
label.text = "搜索"
//
label.font = UIFont.systemFont(ofSize: 17)
label.textColor = UIColor(hexString: AppConst.Color.main)
navigationItem.titleView = label
searchTextField.addTarget(self , action:#selector(textfiledchange(_:)), for: .editingChanged)
searchTextField.delegate = self
}
func textfiledchange(_ textField: UITextField){
if textField.text == "" {
dataArry.removeAll()
tableView.reloadData()
return
}
searchText(text: textField.text!)
}
func searchText(text:String) {
requestModel.message = text
AppAPIHelper.marketAPI().searchstar(requestModel: requestModel, complete: { [weak self](result) in
if let models = result as? [SearchResultModel]{
self?.dataArry = models
self?.tableView.reloadData()
}
}) { (error) in
self.dataArry.removeAll()
self.tableView.reloadData()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.text == "" {
dataArry.removeAll()
tableView.reloadData()
return false
}
searchText(text: textField.text!)
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension MarketSearchViewController:UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchResultCell", for: indexPath) as! SearchResultCell
cell.update(dataArry[indexPath.row])
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArry.count
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard = UIStoryboard(name: AppConst.StoryBoardName.Markt.rawValue, bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "MarketDetail") as? MarketDetailViewController
let starListModel = MarketListModel()
let model = dataArry[indexPath.row]
starListModel.wid = model.wid
starListModel.pic = model.pic
starListModel.symbol = model.symbol
starListModel.name = model.name
vc?.starModel = starListModel
navigationController?.pushViewController(vc!, animated: true)
}
}
|
830ba48a95c3f0a9c061902118cbb51f
| 33.504673 | 121 | 0.647616 | false | false | false | false |
barbosa/clappr-ios
|
refs/heads/master
|
Pod/Classes/Formatter/DateFormatter.swift
|
bsd-3-clause
|
1
|
public class DateFormatter {
private static let hourInSeconds:Double = 1 * 60 * 60
public class func formatSeconds(totalSeconds: NSTimeInterval) -> String {
let date = NSDate(timeIntervalSince1970: totalSeconds)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = totalSeconds < hourInSeconds ? "mm:ss" : "HH:mm:ss"
return formatter.stringFromDate(date)
}
}
|
733594b8295234b5dd364157efc46e4d
| 42.090909 | 82 | 0.69556 | false | false | false | false |
banxi1988/BXAppKit
|
refs/heads/master
|
BXLoadMoreControl/UITableViewController+BXLoadMoreControl.swift
|
mit
|
1
|
//
// BXLoadMoreControl.swift
//
// Created by Haizhen Lee on 15/6/19.
//
import UIKit
extension UIScrollView{
var minPulledDistance: CGFloat{
return BXLoadMoreSettings.triggerPullDistance
}
var overflowY:CGFloat{
// 在 初始时会有 ,所以需要加以判断后再处理
// (lldb) e scrollView.contentSize
// (CGSize) $R0 = (width = 600, height = 0)
// (lldb) e scrollView.frame
// (CGRect) $R1 = (origin = (x = 0, y = 0), size = (width = 320, height = 568))
// (lldb) e scrollView.contentOffset
// (CGPoint) $R2 = (x = 0, y = 0)
if contentSize.height > 0 && contentOffset.y > 0 {
return contentOffset.y + frame.height - contentSize.height
}else{
return 0
}
}
var isPullingUp: Bool{
return overflowY > 1
}
var isPulledUp: Bool{
return overflowY > minPulledDistance
}
}
class BXLoadMoreControlHelper:NSObject{
weak var control:BXLoadMoreControl?
var scrollView:UIScrollView?
init(control:BXLoadMoreControl,scrollView:UIScrollView){
self.control = control
self.scrollView = scrollView
super.init()
control.controlHelper = self
scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .initial, context: &KVOContext)
}
// MARK: KVO
fileprivate var KVOContext = "bx_kvo_context"
fileprivate let contentOffsetKeyPath = "contentOffset"
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == contentOffsetKeyPath && (object as? UIScrollView == scrollView)){
guard let scrollView = scrollView else{
return
}
if scrollView.isDragging{
scrollViewDidScroll(scrollView)
}else{
if scrollView.isPullingUp{
#if DEBUG
//NSLog("overflowY = \(scrollView.overflowY)")
#endif
scrollViewDidEndDragging(scrollView, willDecelerate: scrollView.isDecelerating)
}
}
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
deinit{
scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath)
scrollView = nil
}
//MARK: Hook UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffset = scrollView.contentOffset
let overflowY = scrollView.frame.height + contentOffset.y - scrollView.contentSize.height
#if DEBUG
//NSLog("\(#function) contentoffset=\(contentOffset) overflowY=\(overflowY)")
#endif
guard let bx_control = control else{
return
}
if bx_control.isNomore{
return
}
if bx_control.isLoading{
#if DEBUG
NSLog("isLoading return")
return
#endif
}
if scrollView.isPulledUp && !bx_control.isPreparing {
if !bx_control.isPulled{
bx_control.pulled()
NSLog("startPull")
}
// overflowY 有两次达到此状态,一些上上拉,一次是加弹,所以需要判断一下
}else if scrollView.isPullingUp{
if !bx_control.isPulling{
NSLog("startPull")
bx_control.startPull()
}
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
#if DEBUG
NSLog("\(#function) willDecelerate?=\(decelerate)")
#endif
guard let bx_control = control else{
return
}
if bx_control.isNomore{
return
}
if !bx_control.isLoading{
if scrollView.isPulledUp{
NSLog("\(#function) beginLoading")
bx_control.beginLoading()
}else{
bx_control.canceled()
}
}
}
}
public extension UITableViewController{
fileprivate struct AssociatedKeys{
static let LoadMoreControlKey = "bx_LoadMoreControlKey"
}
public var bx_loadMoreControl:BXLoadMoreControl?{
get{
if let bx_control = objc_getAssociatedObject(self, AssociatedKeys.LoadMoreControlKey) as? BXLoadMoreControl{
return bx_control
}else{
return nil
}
}set{
if let bx_control = newValue{
objc_setAssociatedObject(self, AssociatedKeys.LoadMoreControlKey, bx_control, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// helper is retained by bx_control
let _ = BXLoadMoreControlHelper(control: bx_control, scrollView: tableView)
}else{
objc_setAssociatedObject(self, AssociatedKeys.LoadMoreControlKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
tableView.tableFooterView = newValue
}
}
}
|
d009d4fdf1f57f2498a84bbe51757d57
| 29.452941 | 151 | 0.576782 | false | false | false | false |
kaltura/playkit-ios
|
refs/heads/develop
|
Classes/Player/Media/SourceSelector.swift
|
agpl-3.0
|
1
|
// ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
/// Media Source Type
enum SourceType {
case mp3
case mp4
case m3u8
case wvm
var asString: String {
switch self {
case .mp3:
return "mp3"
case .mp4:
return "mp4"
case .m3u8:
return "m3u8"
case .wvm:
return "wvm"
}
}
}
/// Selects the preffered media source
class SourceSelector {
static func selectSource(from mediaEntry: PKMediaEntry) -> (PKMediaSource, AssetHandler)? {
guard let sources = mediaEntry.sources else {
PKLog.error("no media sources in mediaEntry!")
return nil
}
let defaultHandler = DefaultAssetHandler.self
// Preference: Local, HLS, FPS*, MP4, WVM*, MP3
if let source = sources.first(where: {$0 is LocalMediaSource}) {
if source.mediaFormat == .wvm {
return (source, DRMSupport.widevineClassicHandler!.init())
} else {
return (source, defaultHandler.init())
}
}
if DRMSupport.fairplay {
if let source = sources.first(where: {$0.mediaFormat == .hls}) {
return (source, defaultHandler.init())
}
} else {
if let source = sources.first(where: {$0.mediaFormat == .hls && ($0.drmData == nil || $0.drmData!.isEmpty) }) {
return (source, defaultHandler.init())
}
}
if let source = sources.first(where: {$0.mediaFormat == .mp4}) {
return (source, defaultHandler.init())
}
if DRMSupport.widevineClassic, let source = sources.first(where: {$0.mediaFormat == .wvm}) {
return (source, DRMSupport.widevineClassicHandler!.init())
}
if let source = sources.first(where: {$0.mediaFormat == .mp3}) {
return (source, defaultHandler.init())
}
PKLog.error("No playable media sources!")
if !DRMSupport.fairplay {
PKLog.warning("Note: FairPlay is not supported on simulators")
}
return nil
}
}
|
713430365a56ec2bad68318bb7b7a391
| 31.47561 | 123 | 0.509576 | false | false | false | false |
CharlesVu/Smart-iPad
|
refs/heads/master
|
MKHome/UK/UK - TFL/TFLInteractor.swift
|
mit
|
1
|
//
// TFLInteractor.swift
// MKHome
//
// Created by Charles Vu on 06/06/2019.
// Copyright © 2019 charles. All rights reserved.
//
import Foundation
import TFLApiModels
import Alamofire
import os.log
extension TFL {
struct TFLIntetactor {
private var jsonDecoder: JSONDecoder {
let result = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
result.dateDecodingStrategy = .formatted(dateFormatter)
return result
}
func getLines(mode: Mode, completion: @escaping ([Line]) -> Void) {
let urlString = LinesURLBuilder()
.setMode(mode: mode)
.build()
Alamofire.request(urlString, method: .get)
.response { response in
if let data = response.data {
do {
let lines = try self.jsonDecoder.decode([Line].self, from: data)
completion(lines)
} catch let error {
os_log("❤️ %@", error.localizedDescription)
}
}
}
}
func getLineStatus(mode: Mode, completion: @escaping ([Line]) -> Void) {
let urlString = ModeStatusURLBuilder()
.setMode(mode: mode)
.build()
Alamofire.request(urlString, method: .get)
.response { response in
if let data = response.data {
do {
let lines = try self.jsonDecoder.decode([Line].self, from: data)
completion(lines)
} catch let error {
os_log("❤️ %@", error.localizedDescription)
}
}
}
}
func getStatusDescription(completion: @escaping ([StatusSeverity]) -> Void) {
let urlString = StatusDescriptionURLBuilder()
.build()
Alamofire.request(urlString, method: .get)
.response { response in
if let data = response.data {
do {
let statuses = try self.jsonDecoder.decode([StatusSeverity].self, from: data)
completion(statuses)
} catch let error {
os_log("❤️ %@", error.localizedDescription)
}
}
}
}
}
}
|
0e558829ba7e4136954e833c9865fe86
| 32.8875 | 105 | 0.468462 | false | false | false | false |
naoyashiga/LegendTV
|
refs/heads/master
|
LegendTV/BaseUserDefaultManager.swift
|
mit
|
1
|
//
// BaseUserDefaultManager.swift
// LegendTV
//
// Created by naoyashiga on 2015/08/24.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
class BaseUserDefaultManager: NSObject {
static let ud = NSUserDefaults.standardUserDefaults()
static var counter = 0
static func mySetCounter(keyName: String){
if ud.objectForKey(keyName) == nil {
ud.setObject(0, forKey: keyName)
} else {
counter = ud.integerForKey(keyName)
}
}
static func countUp(keyName: String){
counter = counter + 1
print(counter)
ud.setInteger(counter, forKey: keyName)
}
}
|
d63c6cf26dcc760ef42194e2f7c5f41e
| 22.2 | 57 | 0.614388 | false | false | false | false |
helloglance/betterbeeb
|
refs/heads/master
|
BetterBeeb/SlimPageControl.swift
|
mit
|
1
|
//
// SlimPageControl.swift
// BetterBeeb
//
// Created by Hudzilla on 15/10/2014.
// Copyright (c) 2014 Paul Hudson. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class SlimPageControl: UIPageControl {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.backgroundColor = UIColor.clearColor()
}
override func layoutSubviews() {
super.layoutSubviews()
for vw in subviews as [UIView] {
// hide the pretty circular views, but keep their spacing for AutoLayout
vw.alpha = 0
}
}
override func drawRect(rect: CGRect) {
// We have custom drawing code to draw Beeb-style squares. They aren't very attractive, but oh well…
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextSetAllowsAntialiasing(context, true)
let dotSize = 7
let dotSpacing = 6
let dotY = (self.frame.size.height - CGFloat(dotSize)) / 2
let dotsWidth = (dotSize * self.numberOfPages) + (self.numberOfPages - 1) * dotSpacing
let offset = (self.frame.size.width - CGFloat(dotsWidth)) / 2
for (var i = 0; i < self.numberOfPages; i++) {
let dotRect = CGRectMake(offset + (CGFloat(dotSize) + CGFloat(dotSpacing)) * CGFloat(i), dotY, CGFloat(dotSize), CGFloat(dotSize))
if (i == self.currentPage) {
CGContextSetFillColorWithColor(context, currentPageIndicatorTintColor?.CGColor)
CGContextFillRect(context, dotRect)
} else {
CGContextSetFillColorWithColor(context, pageIndicatorTintColor?.CGColor)
CGContextFillRect(context, dotRect)
}
}
CGContextRestoreGState(context)
}
override var currentPage: Int {
didSet {
setNeedsDisplay()
}
}
}
|
57b8381032d6e05bd4eac138228d41d2
| 32.964706 | 133 | 0.72532 | false | false | false | false |
vlribeiro/loja-desafio-ios
|
refs/heads/master
|
LojaDesafio/LojaDesafio/CartTableViewController.swift
|
mit
|
1
|
//
// CartTableView.swift
// LojaDesafio
//
// Created by Vinicius Ribeiro on 01/12/15.
// Copyright © 2015 Vinicius Ribeiro. All rights reserved.
//
import UIKit
class CartTableViewController: UITableViewController, CartTableViewCellProtocol {
var transaction : Transaction
@IBOutlet var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
required init?(coder aDecoder: NSCoder) {
self.transaction = Transaction()
super.init(coder: aDecoder)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.transaction = TransactionBusiness.fetch()
self.cartTableView.reloadData()
}
func updateTableView() {
self.cartTableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.transaction.transactionProducts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CartTableViewCell", forIndexPath: indexPath) as! CartTableViewCell
let transactionProduct = self.transaction.transactionProducts[indexPath.row]
cell.setTransactionProduct(transactionProduct, index: indexPath.row, delegate: self)
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("ProductDetailSegue", sender: indexPath.row)
}
}
|
d9a84dd5d858ffa6b26b71b1a9c3f7d9
| 30.245902 | 130 | 0.687303 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
Pods/QRCode/QRCode/CIImageExtension.swift
|
mit
|
1
|
//
// CIImageExtension.swift
// QRCode
//
// Created by Jaiouch Yaman - Société ID-APPS on 18/12/2015.
// Copyright © 2015 Alexander Schuch. All rights reserved.
//
import Foundation
internal typealias Scale = (dx: CGFloat, dy: CGFloat)
internal extension CIImage {
/// Creates an `UIImage` with interpolation disabled and scaled given a scale property
///
/// - parameter withScale: a given scale using to resize the result image
///
/// - returns: an non-interpolated UIImage
func nonInterpolatedImage(withScale scale: Scale = Scale(dx: 1, dy: 1)) -> UIImage? {
guard let cgImage = CIContext(options: nil).createCGImage(self, from: self.extent) else { return nil }
let size = CGSize(width: self.extent.size.width * scale.dx, height: self.extent.size.height * scale.dy)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.interpolationQuality = .none
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.draw(cgImage, in: context.boundingBoxOfClipPath)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
|
0feb63946dd7de4ead9592c062339ff1
| 36.542857 | 111 | 0.675038 | false | false | false | false |
kevindelord/DKDBManager
|
refs/heads/master
|
Example/DBSwiftTest/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// DBSwiftTest
//
// Created by kevin delord on 22/01/16.
// Copyright © 2016 Smart Mobile Factory. All rights reserved.
//
import Foundation
struct Segue {
static let OpenPassengers = "OpenPassengerForPlane"
static let OpenBaggages = "OpenBaggageForPassenger"
}
struct JSON {
static let Destination = "destination"
static let Origin = "origin"
static let Passengers = "passengers"
static let Baggages = "baggages"
static let Plane = "plane"
static let Name = "name"
static let Age = "age"
static let Weight = "weight"
}
struct Verbose {
static let DatabaseManager = true
struct Model {
static let Plane = true
static let Passenger = true
static let Baggage = true
}
}
|
ce59b4a4a59ac63bec96f29c6d27da3a
| 19.638889 | 63 | 0.695418 | false | false | false | false |
zning1994/practice
|
refs/heads/master
|
Swift学习/code4xcode6/ch14/14.2.3引用类型构造器代理.playground/section-1.swift
|
gpl-2.0
|
1
|
// 本书网站:http://www.51work6.com/swift.php
// 智捷iOS课堂在线课堂:http://v.51work6.com
// 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973
// 智捷iOS课堂微信公共账号:智捷iOS课堂
// 作者微博:http://weibo.com/516inc
// 官方csdn博客:http://blog.csdn.net/tonny_guan
// Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected]
class Rectangle {
var width : Double
var height : Double
init(width : Double, height : Double) {
self.width = width
self.height = height
}
init(W width : Double,H height : Double) {
self.width = width
self.height = height
}
convenience init(length : Double) {
self.init(W : length, H : length)
}
convenience init() {
self.init(width: 640.0, height: 940.0)
}
}
var rectc1 = Rectangle(width : 320.0, height : 480.0)
println("长方形1:\(rectc1.width) x \(rectc1.height)")
var rectc2 = Rectangle(W : 320.0, H : 480.0)
println("长方形2:\(rectc2.width) x \(rectc2.height)")
var rectc3 = Rectangle(length: 500.0)
println("长方形3:\(rectc3.width) x \(rectc3.height)")
var rectc4 = Rectangle()
println("长方形4:\(rectc4.width) x \(rectc4.height)")
|
700aee0ba8269872383a1c30adc92c5c
| 24.511111 | 62 | 0.622822 | false | false | false | false |
zhanggaoqiang/SwiftLearn
|
refs/heads/master
|
Swift语法/Swift扩展/Swift扩展/main.swift
|
mit
|
1
|
//
// main.swift
// Swift扩展
//
// Created by zgq on 16/4/25.
// Copyright © 2016年 zgq. All rights reserved.
//
import Foundation
/*
扩展就是向一个已有的类,结构体或枚举类型添加新功能
扩展可以对一个类添加新的功能,但是不能重写已有的功能
Swift中的扩展可以:
1.添加计算型属性和计算行静态属性
2.定义实例方法和类型方法
3.提供新的构造器
4.定义下标
5.定义使用新的嵌套类型
6.使一个已有类型符合某个协议
*/
//语法: 扩展声明使用关键字extension:
//一个扩展可以扩展一个已有类型,使其能够失陪一个或多个协议,语法格式如下
/*
计算型属性:扩展可以向已有类型添加计算型属性和计算型类型属性
实例:下面的例子向Int类型添加5个计算型属性并扩展其功能
*/
extension Int {
var add:Int {
return self + 100
}
var sub:Int {
return self - 10
}
var mul:Int {
return self * 10
}
var div :Int {
return self / 5
}
}
let addtion = 3.add
print("加法运算后的值:\(addtion)")
let subtraction = 120.sub
print("减法运算后的值:\(subtraction)")
let multiplicaton = 39.mul
print("乘法运算后的值:\(multiplicaton)")
let division=55.div
print("除法运算后的值:\(division)")
let mix = 30.add + 34.sub
print("混合运算结果:\(mix)")
/*
构造器:
扩展可以向已有类型添加新的构造器。
这可以让你扩展其它类型,将你自己的定制类型作为构造器参数,或者提供该类型的原始数据中没有包含的额外初始化选项
扩展可以向类中添加新的便利构造器init(),但是它们不能向类中添加新的指定构造器或析构函数deinit。
*/
struct sum {
var num1 = 100,num2=200
}
struct diff {
var no1 = 200,no2 = 100
}
struct mult {
var a = sum()
var b = diff()
}
let calc = mult()
print("mult 模块内\(calc.a.num1,calc.a.num2)")
print("mult 模块内\(calc.b.no1,calc.b.no2)")
let memcalc = mult(a:sum(num1:300,num2:500),b:diff(no1:300,no2: 100))
print("mult 模块内\(memcalc.a.num1,memcalc.a.num2)")
print("mult 模块内\(memcalc.b.no1,memcalc.b.no2)")
extension mult {
init(x:sum,y:diff) {
_ = x.num1 + x.num2
_ = y.no1 + y.no2
}
}
let a = sum(num1:100,num2: 200)
print("Sum 模块内:\(a.num1,a.num2)")
let b = diff(no1:200,no2: 200)
print("Diff 模块内:\(b.no1,b.no2)")
/*
方法:
扩展可以向已有类型添加新的方法和类型方法
下面的例子可以向Int类型添加一个名为topics的新实例方法
这个topics方法使用了一个() -> ()类型的单参数,表明函数没有参数而且没有返回值。
定义该扩展之后,你就可以对任意整数调用topic方法,实现的功能则是多次执行某任务
*/
extension Int {
func topics(summation:() -> ()) {
for _ in 0..<self {
summation()
}
}
}
4.topics({
print("扩展模块内")
})
3.topics({
print("内型转换模块内")
})
/*
可变实例方法:
通过扩展添加的实例方法也可以修改该实例本身。
结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样
实例:
下面的例子向Swift的Double类型添加了一个新的名为square的修改方法,来实现一个原始值的平方计算
*/
extension Double {
mutating func square() {
let pi = 3.1415
self = pi * self * self
}
}
var Triall = 3.3
Triall.square()
print("圆的面积为: \(Triall)")
var Trial2=5.8
Trial2.square()
print("圆的面积为:\(Trial2)")
/*
实例:
扩展可以向一个已有类型添加新下标
以下例子向Swift内建类型Int添加了一个整形下标,该下标[n]返回十进制数字
*/
extension Int {
subscript(var multtable: Int) -> Int {
var no1 = 1
while multtable > 0 {
no1 *= 10
multtable -= 1
}
return (self / no1) % 10
}
}
print(12[0])
print(7869[1])
print(786534[2])
/*
嵌套类型:
扩展可以向已有的类,结构体和枚举添加新的嵌套类型
*/
extension Int {
enum calc {
case add
case sub
case mult
case div
case anything
}
var print: calc {
switch self
{
case 0:
return .add
case 1:
return .sub
case 2:
return .mult
case 3:
return .div
default:
return .anything
}
}
}
func result(numb: [Int]) {
for i in numb {
switch i.print {
case .add:
print(" 10 ")
case .sub:
print(" 20 ")
case .mult:
print(" 30 ")
case .div:
print(" 40 ")
default:
print(" 50 ")
}
}
}
result([0, 1, 2, 3, 4, 7])
|
741380763ebe85fd6158bd678b0ab008
| 12.572993 | 69 | 0.561592 | false | false | false | false |
JaDogg/__py_playground
|
refs/heads/master
|
antlr/grammars-v4/swift/examples/GameScene.swift
|
gpl-2.0
|
2
|
//
// GameScene.swift
// FlappyBird
//
// Created by Nate Murray on 6/2/14.
// Copyright (c) 2014 Fullstack.io. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var bird = SKSpriteNode()
var skyColor = SKColor()
var verticalPipeGap = 150.0
var pipeTextureUp = SKTexture()
var pipeTextureDown = SKTexture()
var movePipesAndRemove = SKAction()
override func didMoveToView(view: SKView) {
// setup physics
self.physicsWorld.gravity = CGVectorMake( 0.0, -5.0 )
// setup background color
skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0)
self.backgroundColor = skyColor
// ground
var groundTexture = SKTexture(imageNamed: "land")
groundTexture.filteringMode = SKTextureFilteringMode.Nearest
var moveGroundSprite = SKAction.moveByX(-groundTexture.size().width * 2.0, y: 0, duration: NSTimeInterval(0.02 * groundTexture.size().width * 2.0))
var resetGroundSprite = SKAction.moveByX(groundTexture.size().width * 2.0, y: 0, duration: 0.0)
var moveGroundSpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveGroundSprite,resetGroundSprite]))
for var i:CGFloat = 0; i < 2.0 + self.frame.size.width / ( groundTexture.size().width * 2.0 ); ++i {
var sprite = SKSpriteNode(texture: groundTexture)
sprite.setScale(2.0)
sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height / 2.0)
sprite.runAction(moveGroundSpritesForever)
self.addChild(sprite)
}
// skyline
var skyTexture = SKTexture(imageNamed: "sky")
skyTexture.filteringMode = SKTextureFilteringMode.Nearest
var moveSkySprite = SKAction.moveByX(-skyTexture.size().width * 2.0, y: 0, duration: NSTimeInterval(0.1 * skyTexture.size().width * 2.0))
var resetSkySprite = SKAction.moveByX(skyTexture.size().width * 2.0, y: 0, duration: 0.0)
var moveSkySpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveSkySprite,resetSkySprite]))
for var i:CGFloat = 0; i < 2.0 + self.frame.size.width / ( skyTexture.size().width * 2.0 ); ++i {
var sprite = SKSpriteNode(texture: skyTexture)
sprite.setScale(2.0)
sprite.zPosition = -20;
sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height / 2.0 + groundTexture.size().height * 2.0)
sprite.runAction(moveSkySpritesForever)
self.addChild(sprite)
}
// create the pipes textures
pipeTextureUp = SKTexture(imageNamed: "PipeUp")
pipeTextureUp.filteringMode = SKTextureFilteringMode.Nearest
pipeTextureDown = SKTexture(imageNamed: "PipeDown")
pipeTextureDown.filteringMode = SKTextureFilteringMode.Nearest
// create the pipes movement actions
var distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeTextureUp.size().width);
var movePipes = SKAction.moveByX(-distanceToMove, y:0.0, duration:NSTimeInterval(0.01 * distanceToMove));
var removePipes = SKAction.removeFromParent();
movePipesAndRemove = SKAction.sequence([movePipes, removePipes]);
// spawn the pipes
var spawn = SKAction.runBlock({() in self.spawnPipes()})
var delay = SKAction.waitForDuration(NSTimeInterval(2.0))
var spawnThenDelay = SKAction.sequence([spawn, delay])
var spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay)
self.runAction(spawnThenDelayForever)
// setup our bird
var birdTexture1 = SKTexture(imageNamed: "bird-01")
birdTexture1.filteringMode = SKTextureFilteringMode.Nearest
var birdTexture2 = SKTexture(imageNamed: "bird-02")
birdTexture2.filteringMode = SKTextureFilteringMode.Nearest
var anim = SKAction.animateWithTextures([birdTexture1, birdTexture2], timePerFrame: 0.2)
var flap = SKAction.repeatActionForever(anim)
bird = SKSpriteNode(texture: birdTexture1)
bird.setScale(2.0)
bird.position = CGPoint(x: self.frame.size.width * 0.35, y:self.frame.size.height * 0.6)
bird.runAction(flap)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0)
bird.physicsBody.dynamic = true
bird.physicsBody.allowsRotation = false
self.addChild(bird)
// create the ground
var ground = SKNode()
ground.position = CGPointMake(0, groundTexture.size().height)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, groundTexture.size().height * 2.0))
ground.physicsBody.dynamic = false
self.addChild(ground)
}
func spawnPipes() {
var pipePair = SKNode()
pipePair.position = CGPointMake( self.frame.size.width + pipeTextureUp.size().width * 2, 0 );
pipePair.zPosition = -10;
var height = UInt32( self.frame.size.height / 4 )
var y = arc4random() % height + height;
var pipeDown = SKSpriteNode(texture: pipeTextureDown)
pipeDown.setScale(2.0)
pipeDown.position = CGPointMake(0.0, CGFloat(y) + pipeDown.size.height + CGFloat(verticalPipeGap))
pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize: pipeDown.size)
pipeDown.physicsBody.dynamic = false
pipePair.addChild(pipeDown)
var pipeUp = SKSpriteNode(texture: pipeTextureUp)
pipeUp.setScale(2.0)
pipeUp.position = CGPointMake(0.0, CGFloat(y))
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
pipeUp.physicsBody.dynamic = false
pipePair.addChild(pipeUp)
pipePair.runAction(movePipesAndRemove);
self.addChild(pipePair)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
bird.physicsBody.velocity = CGVectorMake(0, 0)
bird.physicsBody.applyImpulse(CGVectorMake(0, 30))
}
}
func clamp(min: CGFloat, max: CGFloat, value: CGFloat) -> CGFloat {
if( value > max ) {
return max;
} else if( value < min ) {
return min;
} else {
return value;
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
bird.zRotation = self.clamp( -1, max: 0.5, value: bird.physicsBody.velocity.dy * ( bird.physicsBody.velocity.dy < 0 ? 0.003 : 0.001 ) );
}
}
|
1389597f72e49bbbc6627c872d23494f
| 40.909639 | 155 | 0.631307 | false | false | false | false |
aksalj/Helium
|
refs/heads/master
|
Helium/Helium/WebViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Helium
//
// Created by Jaden Geller on 4/9/15.
// Copyright (c) 2015 Jaden Geller. All rights reserved.
//
import Cocoa
import WebKit
class WebViewController: NSViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.addTrackingRect(view.bounds, owner: self, userData: nil, assumeInside: false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadURLObject:", name: "HeliumLoadURL", object: nil)
// Layout webview
view.addSubview(webView)
webView.frame = view.bounds
webView.autoresizingMask = [NSAutoresizingMaskOptions.ViewHeightSizable, NSAutoresizingMaskOptions.ViewWidthSizable]
// Allow plug-ins such as silverlight
webView.configuration.preferences.plugInsEnabled = true
// Custom user agent string for Netflix HTML5 support
webView._customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/8.0.7 Safari/600.7.12"
// Setup magic URLs
webView.navigationDelegate = self
// Allow zooming
webView.allowsMagnification = true
// Alow back and forth
webView.allowsBackForwardNavigationGestures = true
// Listen for load progress
webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil)
clear()
}
override func validateMenuItem(menuItem: NSMenuItem) -> Bool{
switch menuItem.title {
case "Back":
return webView.canGoBack
case "Forward":
return webView.canGoForward
default:
return true
}
}
@IBAction func backPress(sender: AnyObject) {
webView.goBack()
}
@IBAction func forwardPress(sender: AnyObject) {
webView.goForward()
}
func zoomIn() {
webView.magnification += 0.1
}
func zoomOut() {
webView.magnification -= 0.1
}
func resetZoom() {
webView.magnification = 1
}
@IBAction func reloadPress(sender: AnyObject) {
requestedReload()
}
@IBAction func clearPress(sender: AnyObject) {
clear()
}
@IBAction func resetZoomLevel(sender: AnyObject) {
resetZoom()
}
@IBAction func zoomIn(sender: AnyObject) {
zoomIn()
}
@IBAction func zoomOut(sender: AnyObject) {
zoomOut()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
var uneditedURL:String!
func loadAlmostURL(var text: String) {
if !(text.lowercaseString.hasPrefix("http://") || text.lowercaseString.hasPrefix("https://")) {
text = "http://" + text
}
if let url = NSURL(string: text) {
loadURL(url)
}
self.uneditedURL = text
}
func loadURL(url:NSURL) {
webView.loadRequest(NSURLRequest(URL: url))
}
//MARK: - loadURLObject
func loadURLObject(urlObject : NSNotification) {
if let url = urlObject.object as? NSURL {
loadAlmostURL(url.absoluteString);
}
}
func requestedReload() {
webView.reload()
}
func clear() {
loadURL(NSURL(string: "https://cdn.rawgit.com/JadenGeller/Helium/master/helium_start.html")!)
}
var webView = WKWebView()
var shouldRedirect: Bool {
get {
return !NSUserDefaults.standardUserDefaults().boolForKey(UserSetting.DisabledMagicURLs.userDefaultsKey)
}
}
// Redirect Hulu and YouTube to pop-out videos
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if shouldRedirect, let url = navigationAction.request.URL {
let urlString = url.absoluteString
var modified = urlString
modified = modified.replacePrefix("https://www.youtube.com/watch?", replacement: "https://www.youtube.com/watch_popup?")
modified = modified.replacePrefix("https://vimeo.com/", replacement: "http://player.vimeo.com/video/")
modified = modified.replacePrefix("http://v.youku.com/v_show/id_", replacement: "http://player.youku.com/embed/")
if self.uneditedURL.containsString("https://youtu.be") {
if urlString.containsString("?t=") {
modified = "https://youtube.com/embed/" + getVideoHash(urlString) + makeCustomStartTimeURL(urlString)
}
}
if urlString != modified {
decisionHandler(WKNavigationActionPolicy.Cancel)
loadURL(NSURL(string: modified)!)
return
}
}
decisionHandler(WKNavigationActionPolicy.Allow)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation) {
if let pageTitle = webView.title {
var title = pageTitle;
if title.isEmpty { title = "Helium" }
let notif = NSNotification(name: "HeliumUpdateTitle", object: title);
NSNotificationCenter.defaultCenter().postNotification(notif)
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object as! NSObject == webView && keyPath == "estimatedProgress" {
if let progress = change?["new"] as? Float {
let percent = progress * 100
var title = NSString(format: "Loading... %.2f%%", percent)
if percent == 100 {
title = "Helium"
}
let notif = NSNotification(name: "HeliumUpdateTitle", object: title);
NSNotificationCenter.defaultCenter().postNotification(notif)
}
}
}
//Convert a YouTube video url that starts at a certian point to popup/embedded design
// (i.e. ...?t=1m2s --> ?start=62)
func makeCustomStartTimeURL(url: String) -> String {
let startTime = "?t="
let idx = url.indexOf(startTime)
if idx == -1 {
return url
} else {
var returnURL = url
let timing = url.substringFromIndex(url.startIndex.advancedBy(idx+3))
let hoursDigits = timing.indexOf("h")
var minutesDigits = timing.indexOf("m")
let secondsDigits = timing.indexOf("s")
returnURL.removeRange(Range<String.Index>(start: returnURL.startIndex.advancedBy(idx+1), end: returnURL.endIndex))
returnURL = "?start="
//If there are no h/m/s params and only seconds (i.e. ...?t=89)
if (hoursDigits == -1 && minutesDigits == -1 && secondsDigits == -1) {
let onlySeconds = url.substringFromIndex(url.startIndex.advancedBy(idx+3))
returnURL = returnURL + onlySeconds
return returnURL
}
//Do check to see if there is an hours parameter.
var hours = 0
if (hoursDigits != -1) {
hours = Int(timing.substringToIndex(timing.startIndex.advancedBy(hoursDigits)))!
}
//Do check to see if there is a minutes parameter.
var minutes = 0
if (minutesDigits != -1) {
minutes = Int(timing.substringWithRange(Range<String.Index>(start: timing.startIndex.advancedBy(hoursDigits+1), end: timing.startIndex.advancedBy(minutesDigits))))!
}
if minutesDigits == -1 {
minutesDigits = hoursDigits
}
//Do check to see if there is a seconds parameter.
var seconds = 0
if (secondsDigits != -1) {
seconds = Int(timing.substringWithRange(Range<String.Index>(start: timing.startIndex.advancedBy(minutesDigits+1), end: timing.startIndex.advancedBy(secondsDigits))))!
}
//Combine all to make seconds.
let secondsFinal = 3600*hours + 60*minutes + seconds
returnURL = returnURL + String(secondsFinal)
return returnURL
}
}
//Helper function to return the hash of the video for encoding a popout video that has a start time code.
func getVideoHash(url: String) -> String {
let startOfHash = url.indexOf(".be/")
let endOfHash = url.indexOf("?t")
let hash = url.substringWithRange(Range<String.Index>(start: url.startIndex.advancedBy(startOfHash+4), end: url.startIndex.advancedBy(endOfHash)))
return hash
}
}
extension String {
func replacePrefix(prefix: String, replacement: String) -> String {
if hasPrefix(prefix) {
return replacement + substringFromIndex(prefix.endIndex)
}
else {
return self
}
}
func indexOf(target: String) -> Int {
let range = self.rangeOfString(target)
if let range = range {
return self.startIndex.distanceTo(range.startIndex)
} else {
return -1
}
}
}
|
e1180d3ca7103ccf3dc93bb2983ce7be
| 34.043956 | 182 | 0.587018 | false | false | false | false |
windaddict/ARFun
|
refs/heads/master
|
ARFun.playground/Pages/ARKit Search.xcplaygroundpage/Contents.swift
|
mit
|
1
|
/*
* Copyright 2017 John M. P. Knox
* Licensed under the MIT License - see license file
*/
import UIKit
import ARKit
import Vision
import PlaygroundSupport
/**
* A Simple starting point for AR experimentation in Swift Playgrounds 2
*/
class ARFun: NSObject, ARSCNViewDelegate, ARSessionDelegate {
var nodeDict = [UUID:SCNNode]()
//mark: ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
if let node = nodeDict[anchor.identifier] {
return node
}
return nil
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
DispatchQueue.main.async { [weak self] in
self?.debugView.log("updated node")
}
}
//=======================
//mark: ARSessionDelegate
///holds the image we're trying to match
var matchImage: CVPixelBuffer?
var captureNext = false
func session(_ session: ARSession, didUpdate frame: ARFrame){
if captureNext {
matchImage = frame.capturedImage
captureNext = false
} else if let referenceImage = matchImage {
let imageRequest = VNTranslationalImageRegistrationRequest(targetedCVPixelBuffer: referenceImage)
let requestHandler = VNImageRequestHandler(cvPixelBuffer: frame.capturedImage)
try? requestHandler.perform([imageRequest])
if let results = imageRequest.results?.first as? VNImageTranslationAlignmentObservation {
let originalRect = CGRect(x: 0, y:0, width: 1, height: 1)
guard let viewSize = view?.bounds.size else {
return
}
let displayTransform = frame.displayTransform(for: UIInterfaceOrientation.landscapeLeft, viewportSize: viewSize) //TODO: programatically get orientation
let ndRect = originalRect.applying(displayTransform)
let displayRect = CGRect(x:ndRect.origin.x * viewSize.width, y: ndRect.origin.y * viewSize.height, width: ndRect.size.width * viewSize.width, height: ndRect.size.height * viewSize.height) //perhaps another transform instead of this mess
DispatchQueue.main.async{
if results.confidence < 1 {
self.debugView.clearWithLog("LOW")
} else if fabs(results.alignmentTransform.ty) >= CGFloat(CVPixelBufferGetWidth(frame.capturedImage)){
self.debugView.clearWithLog("NO MATCH: too much Y")
} else if results.alignmentTransform.ty <= 0 {
self.debugView.clearWithLog("NO MATCH: too little Y")
} else if results.alignmentTransform.tx >= CGFloat(CVPixelBufferGetHeight(frame.capturedImage)) {
self.debugView.clearWithLog("NO MATCH: too much X")
} else if results.alignmentTransform.tx <= 0 {
self.debugView.clearWithLog("NO MATCH: too little X")
} else {
self.debugView.clearWithLog("match: \(results.alignmentTransform)")
self.rectView.frame = displayRect
self.debugView.log("rect is: \(String(describing: self.view?.bounds.size))")
self.debugView.log("transform is: \(displayTransform)")
}
}
}
}
}
let arSessionConfig = ARWorldTrackingConfiguration()
let debugView = ARDebugView()
let captureButton = UIButton(type: UIButtonType.system)
let rectView = UIView()
var view:ARSCNView? = nil
let scene = SCNScene()
let useScenekit = true
override init(){
super.init()
let frame = CGRect(x: 0.0, y: 0, width: 100, height: 100)
let arView = ARSCNView(frame: frame)
//configure the ARSCNView
arView.debugOptions = [
ARSCNDebugOptions.showWorldOrigin,
ARSCNDebugOptions.showFeaturePoints,
// SCNDebugOptions.showLightInfluences,
// SCNDebugOptions.showWireframe
]
arView.showsStatistics = true
arView.automaticallyUpdatesLighting = true
//views
debugView.translatesAutoresizingMaskIntoConstraints = false
//add the debug view
arView.addSubview(debugView)
arView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor).isActive = true
arView.topAnchor.constraint(equalTo: debugView.topAnchor)
//configure the capture button
captureButton.setTitle("Capture", for: .normal)
captureButton.backgroundColor = UIColor.gray
captureButton.translatesAutoresizingMaskIntoConstraints = false
arView.addSubview(captureButton)
arView.topAnchor.constraint(equalTo: captureButton.topAnchor).isActive = true
arView.trailingAnchor.constraint(equalTo: captureButton.trailingAnchor).isActive = true
captureButton.addTarget(self, action: #selector(captureButtonTapped), for: .touchUpInside )
//configure the rectView
arView.addSubview(rectView)
rectView.layer.borderWidth = 2
rectView.layer.borderColor = UIColor.red.cgColor
rectView.frame = CGRect(x: 0, y:100, width:30, height: 30)
view = arView
arView.scene = scene
//setup session config
if !ARWorldTrackingConfiguration.isSupported { return }
arSessionConfig.planeDetection = .horizontal
arSessionConfig.worldAlignment = .gravityAndHeading //y-axis points UP, x points E (longitude), z points S (latitude)
arSessionConfig.isLightEstimationEnabled = true
arView.session.delegate = self
arView.session.run(arSessionConfig, options: [.resetTracking, .removeExistingAnchors])
arView.delegate = self
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:)))
view?.addGestureRecognizer(gestureRecognizer)
}
@objc func captureButtonTapped() {
captureNext = true
}
let shouldAddAnchorsForNodes = true
func addNode(node: SCNNode, worldTransform: matrix_float4x4) {
let anchor = ARAnchor(transform: worldTransform)
let position = vectorFrom(transform: worldTransform)
node.position = position
node.rotation = SCNVector4(x: 1, y: 1, z: 0, w: 0)
nodeDict[anchor.identifier] = node
if shouldAddAnchorsForNodes {
view?.session.add(anchor: anchor)
} else {
scene.rootNode.addChildNode(node)
}
}
func debug(sceneNode : SCNNode, prefix: String = "" ){
debugView.log(prefix + (sceneNode.name ?? ""))
for child in sceneNode.childNodes{
debug(sceneNode: child, prefix: prefix + "-")
}
}
func debug(scene: SCNScene, prefix: String = ""){
debug(sceneNode: scene.rootNode)
}
///returns a new node with a scene, if one can be found for the scene file specified
func nodeFromScene(named fileName: String, inDirectory directoryName: String)-> SCNNode? {
let scene = SCNScene(named: fileName, inDirectory: directoryName)
guard let theScene = scene else {
debugView.log("no scene \(fileName) in \(directoryName)")
return nil
}
//debug(scene: theScene)
let node = SCNNode()
for child in theScene.rootNode.childNodes {
debugView.log("examining \(String(describing: child.name))")
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
child.movabilityHint = .movable
node.addChildNode(child)
}
return node
}
///adds a new torus to the scene's root node
func addTorus(worldTransform: matrix_float4x4 = matrix_identity_float4x4) {
let torus = SCNTorus(ringRadius: 0.1, pipeRadius: 0.02)
torus.firstMaterial?.diffuse.contents = UIColor(red: 0.4, green: 0, blue: 0, alpha: 1)
torus.firstMaterial?.specular.contents = UIColor.white
let torusNode = SCNNode(geometry:torus)
let spin = CABasicAnimation(keyPath: "rotation.w")
spin.toValue = 2 * Double.pi
spin.duration = 3
spin.repeatCount = HUGE
torusNode.addAnimation(spin, forKey: "spin around")
addNode(node: torusNode, worldTransform: worldTransform)
}
func makeLight()->SCNLight{
let light = SCNLight()
light.intensity = 1
light.type = .omni
light.color = UIColor.yellow
light.attenuationStartDistance = 0.01
light.attenuationEndDistance = 1
return light
}
func makeLightNode()->SCNNode{
let light = makeLight()
let node = SCNNode()
var transform = matrix_identity_float4x4
transform.columns.3.y = 0.2
node.simdTransform = transform
node.light = light
// node.position = SCNVector3(0.0, 0.2, 0.0)
node.simdTransform = transform
return node
}
func addCandle(worldTransform: matrix_float4x4 = matrix_identity_float4x4) {
guard let candleNode = nodeFromScene(named: "candle.scn", inDirectory: "Models.scnassets/candle") else {
return
}
candleNode.addChildNode(makeLightNode())
addNode(node: candleNode, worldTransform: worldTransform)
}
///add a node where the scene was tapped
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
switch gestureRecognizer.state {
default:
print("got tap: \(gestureRecognizer.location(in: view))")
let hitTypes:ARHitTestResult.ResultType = [
ARHitTestResult.ResultType.existingPlaneUsingExtent,
// ARHitTestResult.ResultType.estimatedHorizontalPlane,
// ARHitTestResult.ResultType.featurePoint
]
if let hitTransform = view?.hitTest(gestureRecognizer.location(in: view), types: hitTypes).first?.worldTransform {
addCandle(worldTransform: hitTransform) //TODO: use the anchor provided, if any?
} else {
//add an item at 0,0,0 --
//addCandle()
debugView.log("no hit for tap")
}
}
}
///convert a transform matrix_float4x4 to a SCNVector3
func vectorFrom(transform: matrix_float4x4) -> SCNVector3 {
return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
}
}
///vector addition and subtraction
extension SCNVector3 {
static func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
}
static func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z)
}
}
let arFun = ARFun()
PlaygroundPage.current.liveView = arFun.view
PlaygroundPage.current.needsIndefiniteExecution = true
|
66a1f39ca06acd6bc25748b5f1088dd6
| 40.466912 | 252 | 0.627006 | false | false | false | false |
darina/omim
|
refs/heads/master
|
iphone/Maps/UI/Search/SearchBar.swift
|
apache-2.0
|
4
|
@objc enum SearchBarState: Int {
case ready
case searching
case back
}
final class SearchBar: SolidTouchView {
@IBOutlet private var searchIcon: UIImageView!
@IBOutlet private var activityIndicator: UIActivityIndicatorView!
@IBOutlet private var backButton: UIButton!
@IBOutlet private var searchTextField: SearchTextField!
@IBOutlet private var stackView: UIStackView!
@IBOutlet private var bookingSearchView: UIView!
@IBOutlet private var bookingGuestCountLabel: UILabel!
@IBOutlet private var bookingDatesLabel: UILabel!
override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .top, iPad: .left) }
override var placePageAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
override var trafficButtonAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .top, iPad: .left) }
override var tabBarAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
@objc var state: SearchBarState = .ready {
didSet {
if state != oldValue {
updateLeftView()
}
}
}
@objc var isBookingSearchViewHidden: Bool = true {
didSet {
if oldValue != isBookingSearchViewHidden {
if isBookingSearchViewHidden {
Statistics.logEvent(kStatSearchQuickFilterOpen, withParameters: [kStatCategory: kStatHotel,
kStatNetwork: Statistics.connectionTypeString()])
}
UIView.animate(withDuration: kDefaultAnimationDuration / 2,
delay: 0,
options: [.beginFromCurrentState],
animations: {
if self.isBookingSearchViewHidden {
self.bookingSearchView.alpha = 0
} else {
self.bookingSearchView.isHidden = false
}
}, completion: { complete in
if complete {
UIView.animate(withDuration: kDefaultAnimationDuration / 2,
delay: 0, options: [.beginFromCurrentState],
animations: {
if self.isBookingSearchViewHidden {
self.bookingSearchView.isHidden = true
} else {
self.bookingSearchView.alpha = 1
}
}, completion: nil)
} else {
self.bookingSearchView.isHidden = self.isBookingSearchViewHidden
self.bookingSearchView.alpha = self.isBookingSearchViewHidden ? 0 : 1
}
})
}
}
}
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("EEE, MMMd")
return formatter
}()
override func awakeFromNib() {
super.awakeFromNib()
updateLeftView()
searchTextField.leftViewMode = UITextField.ViewMode.always
searchTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
bookingSearchView.isHidden = true
bookingSearchView.alpha = 0
}
private func updateLeftView() {
searchIcon.isHidden = true
activityIndicator.isHidden = true
backButton.isHidden = true
switch state {
case .ready:
searchIcon.isHidden = false
case .searching:
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .back:
backButton.isHidden = false
}
}
@objc func resetGuestCount() {
bookingGuestCountLabel.text = "?"
}
@objc func setGuestCount(_ count: Int) {
bookingGuestCountLabel.text = "\(count)"
}
@objc func resetDates() {
bookingDatesLabel.text = L("date_picker_сhoose_dates_cta")
}
@objc func setDates(checkin: Date, checkout: Date) {
bookingDatesLabel.text = "\(dateFormatter.string(from: checkin)) – \(dateFormatter.string(from: checkout))".capitalized
}
}
|
b85ba9f5c65c7693ed4746526ec00dbb
| 35.017094 | 132 | 0.639298 | false | false | false | false |
KaushalElsewhere/ImageLocker
|
refs/heads/develop
|
ImageLocker/Controllers/FolderDetailController.swift
|
mit
|
1
|
//
// FolderDetailController.swift
// ImageLocker
//
// Created by Kaushal Elsewhere on 01/06/16.
// Copyright © 2016 Elsewhere. All rights reserved.
//
import UIKit
import JTSImageViewController
import ImageViewer
//MARK: Methods
extension FolderDetailController{
func didClickOnEditBbi(sender: AnyObject){
isEditMode = !isEditMode
let indexPaths:[NSIndexPath] = self.collectionView.indexPathsForSelectedItems()!
for indexPath in indexPaths{
self.collectionView.deselectItemAtIndexPath(indexPath, animated: false)
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FolderDetailCollectionCell
cell.coverView.hidden = true
}
if isEditMode == true {
editButton.setTitle("Cancel", forState: .Normal)
titleLabel.text = "Select"
navigationItem.hidesBackButton = true
deleteButton.hidden = false
} else {
editButton.setTitle("Edit", forState: .Normal)
titleLabel.text = folder.name
navigationItem.hidesBackButton = false
deleteButton.hidden = true
}
}
func readAllFolderImagesFromDefault(){
if let folder = FileManager.sharedInstance.readFolderFromDefaultForKey(self.folderIdentifier) as? Folder {
self.folder = folder
collectionView.collectionViewLayout = createLayoutwithCellCount(self.folder.images.count ?? 0)
}
}
func didSelectDeleteBtn(sender: AnyObject){
// let defaultStyle = UIAlertController
//
// MZAlertControllerStyle *defaultStyle = [UIAlertController mz_sharedStyle];
// defaultStyle.blurEffectStyle = UIBlurEffectStyleDark;
// defaultStyle.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
let alert = UIAlertController(title: "Lorem Ipsum", message: "Haqoona matata, yaaro, ghum ko maaro goli.", preferredStyle: .Alert)
let done = UIAlertAction(title: "Done", style: .Default) { (action) in
}
let cancel = UIAlertAction(title: "Cancel", style: .Destructive, handler: nil)
alert.addAction(cancel)
alert.addAction(done)
self.presentViewController(alert, animated: true, completion: nil)
}
}
extension FolderDetailController{
override func setupViews(){
readAllFolderImagesFromDefault()
self.view.addSubview(collectionView)
self.view.addSubview(deleteButton)
deleteButton.frame = CGRect(x: self.view.frame.size.width-80, y: self.view.frame.size.height-100, width: 50, height: 50)
deleteButton.addTarget(self, action: #selector(didSelectDeleteBtn(_:)), forControlEvents: .TouchUpInside)
self.view.backgroundColor = K.Color.lightGray
setupNav()
setupConstraints()
}
override func setupConstraints() {
let superView = view
collectionView.snp_makeConstraints { (make) in
make.left.top.right.bottom.equalTo(superView)
}
}
func setupNav(){
titleLabel.text = folder.name
navigationItem.titleView = titleLabel
editButton.addTarget(self, action: #selector(didClickOnEditBbi(_:)), forControlEvents: .TouchUpInside)
let editBbi = UIBarButtonItem(customView: editButton)
navigationItem.rightBarButtonItem = editBbi
}
}
extension FolderDetailController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (self.folder.images.count)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! FolderDetailCollectionCell
cell.imgView.image = self.folder.images[indexPath.row]
return cell
}
// func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
//
//
// let screenRect:CGRect = UIScreen.mainScreen().bounds
// let screenWidth:CGFloat = screenRect.size.width
// let cellWidth:CGFloat = CGFloat(screenWidth / 4.0) //Replace the divisor with the column count requirement. Make sure to have it in float.
// let size:CGSize = CGSize(width: cellWidth, height: cellWidth)
//
// return size
// }
}
extension FolderDetailController:UICollectionViewDelegate{
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FolderDetailCollectionCell
if isEditMode == true {
cell.coverView.hidden = false
} else{
cell.selected = true
//showImageOnViewer(cell.imgView)
showGalleryImageViewer(cell.contentView,selectedIndex: indexPath.row)
}
//showImageOnViewer(cell.imgView)
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FolderDetailCollectionCell
if isEditMode == true {
cell.coverView.hidden = true
} else{
//showImageOnViewer(cell.imgView)
showGalleryImageViewer(cell.contentView,selectedIndex: indexPath.row)
}
}
func showImageOnViewer(imageView:UIImageView) -> Void{
let imageInfo:JTSImageInfo = JTSImageInfo()
imageInfo.image = imageView.image
imageInfo.referenceRect = imageView.frame
imageInfo.referenceView = imageView.superview
let imageViewer = JTSImageViewController(imageInfo: imageInfo, mode: .Image, backgroundStyle: .Blurred)
imageViewer.showFromViewController(self, transition: .FromOriginalPosition)
}
}
extension FolderDetailController{
func showGalleryImageViewer(displacedView: UIView, selectedIndex index:Int) {
let imageProvider = SomeImageProvider()
imageProvider.images = self.folder.images
// let frame = CGRect(x: 0, y: 0, width: 200, height: 24)
// let headerView = CounterView(frame: frame, currentIndex: displacedView.tag, count: self.folder.images.count)
// let footerView = CounterView(frame: frame, currentIndex: displacedView.tag, count: images.count)
let galleryViewController = GalleryViewController(imageProvider: imageProvider,
displacedView: displacedView,
imageCount: folder.images.count,
startIndex: index)
// galleryViewController.headerView = headerView
// galleryViewController.footerView = footerView
// galleryViewController.launchedCompletion = { print("LAUNCHED") }
// galleryViewController.closedCompletion = { print("CLOSED") }
// galleryViewController.swipedToDismissCompletion = { print("SWIPE-DISMISSED") }
// galleryViewController.landedPageAtIndexCompletion = { index in
//
// print("LANDED AT INDEX: \(index)")
//
//// headerView.currentIndex = index
//// footerView.currentIndex = index
// }
self.presentImageGallery(galleryViewController)
}
}
class SomeImageProvider: ImageProvider {
var images: [UIImage]!
func provideImage(completion: UIImage? -> Void) {
completion(images.first)
}
func provideImage(atIndex index: Int, completion: UIImage? -> Void) {
completion(images[index])
}
}
class FolderDetailController: Controller{
lazy var titleLabel:UILabel = {
let label = UILabel(frame:CGRect(x: 0, y: 0, width: 100, height: 20))
label.font = K.Font.americanTypewriter.size(19)
label.textAlignment = .Center
label.textColor = .blackColor()
return label
}()
lazy var editButton:UIButton = {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 20))
button.setTitle("Edit", forState: .Normal)
button.setTitleColor(.darkGrayColor(), forState: .Normal)
return button
}()
lazy var deleteButton:UIButton = {
let button = UIButton(frame:CGRect(x: 0, y: 0, width: 50, height: 50))
button.setImage(UIImage(named: "deleteW"), forState: .Normal)
button.backgroundColor = UIColor.cornflowerColor()
button.layer.cornerRadius = 50/2
button.layer.shadowColor = UIColor.blackColor().CGColor
button.layer.shadowOffset = CGSize(width: 0, height: 1)
button.layer.masksToBounds = false
button.layer.shadowRadius = 2
button.layer.shadowOpacity = 1.0
button.hidden = true
return button
}()
var isEditMode:Bool = false
var folder:Folder!
var folderIdentifier:String!
var layout:UICollectionViewFlowLayout{
return self.createLayoutwithCellCount(3)
}
lazy var collectionView: UICollectionView = {
//let width = CGFloat(self.view.frame.size.width)/4-15
//let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//layout.sectionInset = UIEdgeInsets(top: 20, left: 8, bottom: 10, right: 8)
//layout.itemSize = CGSize(width: width, height: width)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(FolderDetailCollectionCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView.backgroundColor = .clearColor()
collectionView.allowsMultipleSelection = true
return collectionView
}()
func createLayoutwithCellCount(count:Int) -> UICollectionViewFlowLayout {
var number:Int
switch count {
case 1...5:
number = 2
case 6...11:
number = 3
case 12...100000000000:
number = 4
default:
fatalError("image count is beyond limit, please check and correct")
}
let screenSize = UIScreen.mainScreen().bounds
let width = (screenSize.width/CGFloat(number)) - CGFloat(number+2)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 3, bottom: 10, right: 3)
layout.itemSize = CGSize(width: width, height: width)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 3
return layout
}
}
//
|
4b012f18dd1a08074f24467ea5364ed7
| 36.8 | 171 | 0.641799 | false | false | false | false |
omaralbeik/SwifterSwift
|
refs/heads/master
|
Tests/UIKitTests/UIGestureRecognizerExtensionsTests.swift
|
mit
|
1
|
//
// UIGestureRecognizerExtensionsTests.swift
// SwifterSwift
//
// Created by Morgan Dock on 4/21/18.
// Copyright © 2018 SwifterSwift
//
import XCTest
@testable import SwifterSwift
#if os(iOS) && !os(watchOS)
import UIKit
final class UIGestureRecognizerExtensionsTests: XCTestCase {
func testRemoveFromView() {
let view = UIImageView()
let tap = UITapGestureRecognizer()
//First Baseline Assertion
XCTAssert(view.gestureRecognizers == nil)
XCTAssert(tap.view == nil)
view.addGestureRecognizer(tap)
//Verify change
XCTAssertFalse(view.gestureRecognizers == nil)
XCTAssertFalse(tap.view == nil)
//Second Baseline Assertion
XCTAssertFalse((view.gestureRecognizers?.count ?? 0) == 0)
XCTAssertFalse(view.gestureRecognizers?.isEmpty ?? true)
tap.removeFromView()
//Verify change
XCTAssert((view.gestureRecognizers?.count ?? 1) == 0)
XCTAssert(view.gestureRecognizers?.isEmpty ?? false)
XCTAssert(tap.view == nil)
}
}
#endif
|
2bf431a08e2d75126cf624bcf81a52f9
| 23.568182 | 66 | 0.659574 | false | true | false | false |
Mubaloo/Lock.iOS-OSX
|
refs/heads/master
|
Examples/Firebase/Firebase.Swift/FirebaseExample/ViewController.swift
|
mit
|
3
|
// ViewController.swift
//
// Copyright (c) 2014 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
let FirebaseURLString = "https://sizzling-heat-5516.firebaseio.com/"
class ViewController: UIViewController {
@IBOutlet weak var firstStepLabel: UILabel!
@IBOutlet weak var seconStepLabel: UILabel!
@IBOutlet weak var thirdStepLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let idToken = A0SimpleKeychain().stringForKey("id_token")
self.firstStepLabel.text = idToken == nil ? nil : "Auth0 JWT \(idToken)"
if idToken == nil {
self.showLogin()
}
}
@IBAction func logout(sender: AnyObject) {
A0SimpleKeychain().clearAll()
self.showLogin()
self.seconStepLabel.text = nil
self.thirdStepLabel.text = nil
}
@IBAction func fetchFromFirebase(sender: AnyObject) {
let button = sender as! UIButton
self.setInProgress(true, button: button)
let client = A0APIClient.sharedClient()
let jwt = A0SimpleKeychain().stringForKey("id_token")
let parameters = A0AuthParameters.newWithDictionary([
A0ParameterAPIType: "firebase",
"id_token": jwt
])
client.fetchDelegationTokenWithParameters(parameters,
success: { (response) -> Void in
let credentials = response as! Dictionary<String, AnyObject>
let firebaseToken = credentials["id_token"] as? String
self.seconStepLabel.text = "Firebase JWT \(firebaseToken!)"
println("Obtained Firebase credentials \(credentials)")
let ref = Firebase(url: FirebaseURLString)
ref.authWithCustomToken(firebaseToken, withCompletionBlock: { (error, data) -> () in
if error == nil {
self.thirdStepLabel.text = "\(data)"
println("Obtained data \(data)")
} else {
self.thirdStepLabel.text = error.localizedDescription
println("Failed to auth with Firebase. Error \(error)")
}
self.setInProgress(false, button: button)
})
},
failure: { (error) -> Void in
self.seconStepLabel.text = error.localizedDescription
println("An error ocurred \(error)")
self.setInProgress(false, button: button)
})
}
func setInProgress(inProgress: Bool, button: UIButton) {
if inProgress {
button.enabled = false
self.activityIndicator.startAnimating()
self.activityIndicator.hidden = false
self.seconStepLabel.text = nil
self.thirdStepLabel.text = nil
} else {
button.enabled = true
self.activityIndicator.stopAnimating()
}
}
func showLogin() {
let lock = A0LockViewController()
lock.closable = false
lock.onAuthenticationBlock = {(profile: A0UserProfile!, token: A0Token!) -> () in
A0SimpleKeychain().setString(token.idToken, forKey: "id_token")
self.dismissViewControllerAnimated(true, completion: nil)
self.firstStepLabel.text = "Auth0 JWT \(token.idToken)"
return;
}
self.presentViewController(lock, animated: true, completion: nil)
}
}
|
0cb502a7b043f9bd3c2b65ea30bea1de
| 39.344828 | 100 | 0.633547 | false | false | false | false |
attaswift/BigInt
|
refs/heads/master
|
Sources/Codable.swift
|
mit
|
2
|
//
// Codable.swift
// BigInt
//
// Created by Károly Lőrentey on 2017-8-11.
// Copyright © 2016-2017 Károly Lőrentey.
//
// Little-endian to big-endian
struct Units<Unit: FixedWidthInteger, Words: RandomAccessCollection>: RandomAccessCollection
where Words.Element: FixedWidthInteger, Words.Index == Int {
typealias Word = Words.Element
let words: Words
init(of type: Unit.Type, _ words: Words) {
precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
self.words = words
}
var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth }
var startIndex: Int { return 0 }
var endIndex: Int { return count }
subscript(_ index: Int) -> Unit {
let index = count - 1 - index
if Unit.bitWidth == Word.bitWidth {
return Unit(words[index])
}
else if Unit.bitWidth > Word.bitWidth {
let c = Unit.bitWidth / Word.bitWidth
var unit: Unit = 0
var j = 0
for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) {
unit |= Unit(words[i]) << j
j += Word.bitWidth
}
return unit
}
// Unit.bitWidth < Word.bitWidth
let c = Word.bitWidth / Unit.bitWidth
let i = index / c
let j = index % c
return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth))
}
}
extension Array where Element: FixedWidthInteger {
// Big-endian to little-endian
init<Unit: FixedWidthInteger>(count: Int?, generator: () throws -> Unit?) rethrows {
typealias Word = Element
precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
self = []
if Unit.bitWidth == Word.bitWidth {
if let count = count {
self.reserveCapacity(count)
}
while let unit = try generator() {
self.append(Word(unit))
}
}
else if Unit.bitWidth > Word.bitWidth {
let wordsPerUnit = Unit.bitWidth / Word.bitWidth
if let count = count {
self.reserveCapacity(count * wordsPerUnit)
}
while let unit = try generator() {
var shift = Unit.bitWidth - Word.bitWidth
while shift >= 0 {
self.append(Word(truncatingIfNeeded: unit >> shift))
shift -= Word.bitWidth
}
}
}
else {
let unitsPerWord = Word.bitWidth / Unit.bitWidth
if let count = count {
self.reserveCapacity((count + unitsPerWord - 1) / unitsPerWord)
}
var word: Word = 0
var c = 0
while let unit = try generator() {
word <<= Unit.bitWidth
word |= Word(unit)
c += Unit.bitWidth
if c == Word.bitWidth {
self.append(word)
word = 0
c = 0
}
}
if c > 0 {
self.append(word << c)
var shifted: Word = 0
for i in self.indices {
let word = self[i]
self[i] = shifted | (word >> c)
shifted = word << (Word.bitWidth - c)
}
}
}
self.reverse()
}
}
extension BigInt: Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// Decode sign
let sign: BigInt.Sign
switch try container.decode(String.self) {
case "+":
sign = .plus
case "-":
sign = .minus
default:
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Invalid big integer sign"))
}
// Decode magnitude
let words = try [UInt](count: container.count?.advanced(by: -1)) { () -> UInt64? in
guard !container.isAtEnd else { return nil }
return try container.decode(UInt64.self)
}
let magnitude = BigUInt(words: words)
self.init(sign: sign, magnitude: magnitude)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(sign == .plus ? "+" : "-")
let units = Units(of: UInt64.self, self.magnitude.words)
if units.isEmpty {
try container.encode(0 as UInt64)
}
else {
try container.encode(contentsOf: units)
}
}
}
extension BigUInt: Codable {
public init(from decoder: Decoder) throws {
let value = try BigInt(from: decoder)
guard value.sign == .plus else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath,
debugDescription: "BigUInt cannot hold a negative value"))
}
self = value.magnitude
}
public func encode(to encoder: Encoder) throws {
try BigInt(sign: .plus, magnitude: self).encode(to: encoder)
}
}
|
3ceeb9be23ddbca0d45af9f590d8d508
| 33.219355 | 110 | 0.522624 | false | false | false | false |
Chuck8080/ios-swift-sugar-record
|
refs/heads/master
|
example/SugarRecordExample/Shared/Controllers/RealmTableViewController.swift
|
mit
|
1
|
//
// RealmTableViewController.swift
// SugarRecordExample
//
// Created by Pedro Piñera Buendía on 25/12/14.
// Copyright (c) 2014 Robert Dougan. All rights reserved.
//
import Foundation
import Realm
class RealmTableViewController: StackTableViewController
{
//MARK: - Attributes
var data: SugarRecordResults<RLMObject>?
//MARK: - Viewcontroller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Realm"
self.stack = DefaultREALMStack(stackName: "Realm", stackDescription: "")
SugarRecord.addStack(self.stack!)
}
//MARK: - Actions
@IBAction override func add(sender: AnyObject?) {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM d yyyy - HH:mm:ss"
let model = RealmModel.create() as RealmModel
model.name = formatter.stringFromDate(NSDate())
model.save()
self.fetchData()
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
}
//MARK: - Data Source
override func fetchData() {
self.data = RealmModel.all().sorted(by: "date", ascending: false).find()
}
override func dataCount() -> Int {
if (data == nil) { return 0 }
else { return data!.count }
}
//MARK: - Cell
override func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM d yyyy - HH:mm:ss"
let model = self.data![indexPath.row] as RealmModel
cell.textLabel?.text = model.name
cell.detailTextLabel?.text = formatter.stringFromDate(model.date)
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
let model = self.data![indexPath.row] as RealmModel
model.beginWriting().delete().endWriting()
self.fetchData()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func cellIdentifier() -> String {
return "ModelCell"
}
}
|
d18327ab153f36019db372da56d9ef92
| 29.090909 | 157 | 0.634283 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/01224-swift-parser-skipsingle.swift
|
apache-2.0
|
11
|
// 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
func e<l {
enum e {
func p() { p
class A {
class func a() -> Self {
}
}
func b<T>(t: AnyObject.Type) -> T! {
}
func b<d-> d { class d:b class b
protocol A {
}
func f() {
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f k }
}
protocol n {
}
class o: n{ cla) u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) {
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
o) {
return { -> T
class func a() -> String {
struct c {
static let d: String = {
b {A {
u) {
func g<T where T.E == F>(f: B<T>) {
func e(
class A {
class func a() -> String {
struct c {
static let d
|
eb23cb05475966bc77e7a3c642902ca4
| 19.354167 | 78 | 0.601842 | false | false | false | false |
mownier/photostream
|
refs/heads/master
|
Photostream/Services/Models/Photo.swift
|
mit
|
1
|
//
// Photo.swift
// Photostream
//
// Created by Mounir Ybanez on 17/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import Foundation
import Firebase
struct Photo {
var url: String
var width: Int
var height: Int
init() {
url = ""
width = 0
height = 0
}
}
extension Photo: SnapshotParser {
init(with snapshot: DataSnapshot, exception: String...) {
self.init()
if snapshot.hasChild("url") && !exception.contains("url") {
url = snapshot.childSnapshot(forPath: "url").value as! String
}
if snapshot.hasChild("width") && !exception.contains("width") {
width = snapshot.childSnapshot(forPath: "width").value as! Int
}
if snapshot.hasChild("height") && !exception.contains("height") {
height = snapshot.childSnapshot(forPath: "height").value as! Int
}
}
}
|
b1886a8f712e2ba404fb2fab06be8eeb
| 21.761905 | 76 | 0.572176 | false | false | false | false |
ChrisChares/SwiftToolbelt
|
refs/heads/develop
|
Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
|
apache-2.0
|
43
|
import Foundation
#if _runtime(_ObjC)
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
internal struct AsyncMatcherWrapper<T, U>: Matcher
where U: Matcher, U.ValueType == T
{
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function")
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
#endif
|
a65ef39d2050c1eb4dc87338cd707cf5
| 42.5 | 268 | 0.646474 | false | false | false | false |
kylecrawshaw/ImagrAdmin
|
refs/heads/master
|
ImagrAdmin/WorkflowSupport/WorkflowComponents/EraseVolumeComponent/EraseVolumeViewController.swift
|
apache-2.0
|
1
|
//
// ImageComponentViewController.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/14/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Cocoa
class EraseVolumeViewController: NSViewController {
@IBOutlet weak var volumeNameField: NSTextField!
@IBOutlet weak var volumeFormatField: NSTextField!
var component: EraseVolumeComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? EraseVolumeComponent
volumeNameField.stringValue = component!.volumeName
volumeFormatField.stringValue = component!.volumeFormat
}
override func viewDidDisappear() {
component!.volumeName = volumeNameField.stringValue
component!.volumeFormat = volumeFormatField.stringValue
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
|
db882c6f944abc9c0e77ec894a20f70d
| 26.837838 | 108 | 0.71068 | false | false | false | false |
ngageoint/mage-ios
|
refs/heads/master
|
Mage/NumberFieldView.swift
|
apache-2.0
|
1
|
//
// NumberFieldView.swift
// MAGE
//
// Created by Daniel Barela on 5/26/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MDCTextField;
class NumberFieldView : BaseFieldView {
private var shouldResign: Bool = false;
private var number: NSNumber?;
private var min: NSNumber?;
private var max: NSNumber?;
lazy var helperText: String? = {
var helper: String? = nil;
if (self.min != nil && self.max != nil) {
helper = "Must be between \(self.min!) and \(self.max!)";
} else if (self.min != nil) {
helper = "Must be greater than \(self.min!) ";
} else if (self.max != nil) {
helper = "Must be less than \(self.max!)";
}
return helper;
}()
lazy var titleLabel: UILabel = {
let label = UILabel(forAutoLayout: ());
label.text = helperText;
label.sizeToFit();
return label;
}()
private lazy var formatter: NumberFormatter = {
let formatter = NumberFormatter();
formatter.numberStyle = .decimal;
return formatter;
}()
private lazy var accessoryView: UIToolbar = {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44));
toolbar.autoSetDimension(.height, toSize: 44);
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed));
let cancelBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed));
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil);
toolbar.items = [cancelBarButton, flexSpace, UIBarButtonItem(customView: titleLabel), flexSpace, doneBarButton];
return toolbar;
}()
lazy var textField: MDCFilledTextField = {
let textField = MDCFilledTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 100));
textField.delegate = self;
textField.trailingView = UIImageView(image: UIImage(systemName: "number"));
textField.trailingViewMode = .always;
textField.accessibilityLabel = field[FieldKey.name.key] as? String ?? "";
textField.leadingAssistiveLabel.text = helperText ?? " ";
textField.inputAccessoryView = accessoryView;
textField.keyboardType = .decimalPad;
setPlaceholder(textField: textField);
textField.sizeToFit();
return textField;
}()
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
convenience init(field: [String: Any], editMode: Bool = true, delegate: (ObservationFormFieldListener & FieldSelectionDelegate)? = nil) {
self.init(field: field, delegate: delegate, value: nil);
}
init(field: [String: Any], editMode: Bool = true, delegate: (ObservationFormFieldListener & FieldSelectionDelegate)? = nil, value: String?) {
super.init(field: field, delegate: delegate, value: value, editMode: editMode);
self.min = self.field[FieldKey.min.key] as? NSNumber;
self.max = self.field[FieldKey.max.key] as? NSNumber;
setupInputView();
setValue(value);
}
override func applyTheme(withScheme scheme: MDCContainerScheming?) {
guard let scheme = scheme else {
return
}
super.applyTheme(withScheme: scheme);
textField.applyTheme(withScheme: scheme);
textField.trailingView?.tintColor = scheme.colorScheme.onSurfaceColor.withAlphaComponent(0.6);
}
func setupInputView() {
if (editMode) {
viewStack.addArrangedSubview(textField);
} else {
viewStack.addArrangedSubview(fieldNameLabel);
viewStack.addArrangedSubview(fieldValue);
fieldValue.text = getValue()?.stringValue;
}
}
override func getValue() -> Any? {
return number;
}
func getValue() -> NSNumber? {
return number;
}
override func setValue(_ value: Any?) {
setValue(value as? String);
}
func setValue(_ value: String?) {
number = nil;
if (value != nil) {
number = formatter.number(from: value!);
}
if (editMode) {
setTextFieldValue();
} else {
fieldValue.text = number?.stringValue;
}
}
func setTextFieldValue() {
textField.text = number?.stringValue
}
@objc func doneButtonPressed() {
shouldResign = true;
textField.resignFirstResponder();
}
@objc func cancelButtonPressed() {
shouldResign = true;
setTextFieldValue();
textField.resignFirstResponder();
}
override func isEmpty() -> Bool{
if let checkText = textField.text {
return checkText.count == 0;
}
return true;
}
override func getErrorMessage() -> String {
if let helperText = helperText {
return helperText
}
return "Must be a number";
}
override func isValid(enforceRequired: Bool = false) -> Bool {
return self.isValid(enforceRequired: enforceRequired, number: self.number);
}
func isValid(enforceRequired: Bool = false, number: NSNumber?) -> Bool {
return super.isValid(enforceRequired: enforceRequired) && isValidNumber(number);
}
func isValidNumber(_ number: NSNumber?) -> Bool {
if (!isEmpty() && number == nil) {
return false;
}
if let check = number {
if ((self.min != nil && self.max != nil &&
((check.doubleValue < self.min!.doubleValue) || (check.doubleValue > self.max!.doubleValue)
)
)
|| (self.min != nil && check.doubleValue < min!.doubleValue)
|| (self.max != nil && check.doubleValue > max!.doubleValue)) {
return false;
}
}
return true;
}
override func setValid(_ valid: Bool) {
super.setValid(valid);
if (valid) {
textField.leadingAssistiveLabel.text = helperText;
if let scheme = scheme {
textField.applyTheme(withScheme: scheme);
}
} else {
textField.applyErrorTheme(withScheme: globalErrorContainerScheme());
textField.leadingAssistiveLabel.text = getErrorMessage();
}
}
}
extension NumberFieldView: UITextFieldDelegate {
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return shouldResign;
}
func textFieldDidEndEditing(_ textField: UITextField) {
if let text: String = textField.text {
let number = formatter.number(from: text);
let valid = isValid(enforceRequired: true, number: number);
setValid(valid);
if (valid && (number == nil || (self.number?.stringValue != textField.text))) {
delegate?.fieldValueChanged(field, value: number);
}
self.number = number;
}
shouldResign = false;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// allow backspace
if (string.count == 0) {
return true;
}
if let text = textField.text as NSString? {
let txtAfterUpdate = text.replacingCharacters(in: range, with: string);
let number = formatter.number(from: txtAfterUpdate);
if (number == nil) {
return false;
}
setValid(isValidNumber(number));
return true;
}
return false;
}
}
|
9933eacfdb7231a0e5a8fe96dcce570a
| 32.940678 | 145 | 0.589139 | false | false | false | false |
codefellows/sea-d34-iOS
|
refs/heads/master
|
Sample Code/Week 2/ImageFilters/ImageFilters/FilterService.swift
|
mit
|
1
|
//
// FilterService.swift
// ImageFilters
//
// Created by Bradley Johnson on 4/6/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import UIKit
import CoreImage
class FilterService {
class func sepia(originalImage : UIImage, context : CIContext) -> UIImage {
let sepia = CIFilter(name: "CISepiaTone")
return self.filteredImageFromOriginalImage(originalImage, filter: sepia, context: context)
}
class func colorInvert(originalImage : UIImage, context : CIContext) -> UIImage {
let invert = CIFilter(name: "CIColorInvert")
invert.setDefaults()
return self.filteredImageFromOriginalImage(originalImage, filter: invert, context: context)
}
class func instant(originalImage : UIImage, context : CIContext) -> UIImage {
let instant = CIFilter(name: "CIPhotoEffectInstant")
instant.setDefaults()
return self.filteredImageFromOriginalImage(originalImage, filter: instant, context: context)
}
class func chrome(originalImage : UIImage, context : CIContext) -> UIImage {
let chrome = CIFilter(name: "CIPhotoEffectChrome")
chrome.setDefaults()
return self.filteredImageFromOriginalImage(originalImage, filter: chrome, context: context)
}
class func noir(originalImage : UIImage, context : CIContext) -> UIImage {
let noir = CIFilter(name: "CIPhotoEffectNoir")
noir.setDefaults()
return self.filteredImageFromOriginalImage(originalImage, filter: noir, context: context)
}
private class func filteredImageFromOriginalImage(originalImage : UIImage, filter : CIFilter, context : CIContext) -> UIImage {
let image = CIImage(image: originalImage)
filter.setValue(image, forKey: kCIInputImageKey)
let result = filter.valueForKey(kCIOutputImageKey) as CIImage
let resultRef = context.createCGImage(result, fromRect: result.extent())
return UIImage(CGImage: resultRef)!
}
}
|
b8f63ed6255513c83b8f8c2b4907f29c
| 29.809524 | 129 | 0.715611 | false | false | false | false |
pksprojects/ElasticSwift
|
refs/heads/master
|
Sources/ElasticSwift/Requests/StoredScriptRequests.swift
|
mit
|
1
|
//
// StoredScriptRequests.swift
//
//
// Created by Prafull Kumar Soni on 9/27/20.
//
import ElasticSwiftCore
import Foundation
import NIOHTTP1
// MARK: - Put StoredScript Request Builder
public class PutStoredScriptRequestBuilder: RequestBuilder {
public typealias RequestType = PutStoredScriptRequest
private var _id: String?
private var _script: StoredScriptSource?
private var _context: String?
public init() {}
@discardableResult
public func set(id: String) -> Self {
_id = id
return self
}
@discardableResult
public func set(script: StoredScriptSource) -> Self {
_script = script
return self
}
@discardableResult
public func set(context: String) -> Self {
_context = context
return self
}
public var id: String? {
return _id
}
public var script: StoredScriptSource? {
return _script
}
public var context: String? {
return _context
}
public func build() throws -> PutStoredScriptRequest {
return try PutStoredScriptRequest(withBuilder: self)
}
}
// MARK: - Put StoredScript Request
public struct PutStoredScriptRequest: Request {
public var headers = HTTPHeaders()
public let id: String
public let script: StoredScriptSource
public let context: String?
public var timeout: String?
public var masterTimeout: String?
public init(id: String, script: StoredScriptSource, context: String? = nil, timeout: String? = nil, masterTimeout: String? = nil) {
self.id = id
self.script = script
self.context = context
self.timeout = timeout
self.masterTimeout = masterTimeout
}
internal init(withBuilder builder: PutStoredScriptRequestBuilder) throws {
guard let id = builder.id else {
throw RequestBuilderError.missingRequiredField("id")
}
guard let script = builder.script else {
throw RequestBuilderError.missingRequiredField("script")
}
self.init(id: id, script: script, context: builder.context)
}
public var queryParams: [URLQueryItem] {
var queryItems = [URLQueryItem]()
if let timeout = self.timeout {
queryItems.append(.init(name: QueryParams.timeout, value: timeout))
}
if let masterTimeout = self.masterTimeout {
queryItems.append(.init(name: QueryParams.masterTimeout, value: masterTimeout))
}
return queryItems
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
var _endPoint = "_scripts/\(id)"
if let context = self.context {
_endPoint = "\(_endPoint)/\(context)"
}
return _endPoint
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
let body = Body(script: script)
return serializer.encode(body).mapError { error -> MakeBodyError in
.wrapped(error)
}
}
private struct Body: Encodable {
public let script: StoredScriptSource
}
}
extension PutStoredScriptRequest: Equatable {}
public struct StoredScriptSource {
public let lang: String
public let source: String
public let options: [String: String]?
public init(lang: String, source: String, options: [String: String]? = nil) {
self.lang = lang
self.source = source
self.options = options
}
}
extension StoredScriptSource: Codable {}
extension StoredScriptSource: Equatable {}
// MARK: - Get StoredScript Request Builder
public class GetStoredScriptRequestBuilder: RequestBuilder {
public typealias RequestType = GetStoredScriptRequest
private var _id: String?
private var _masterTimeout: String?
public init() {}
@discardableResult
public func set(id: String) -> Self {
_id = id
return self
}
@discardableResult
public func set(masterTimeout: String) -> Self {
_masterTimeout = masterTimeout
return self
}
public var id: String? {
return _id
}
public var masterTimeout: String? {
return _masterTimeout
}
public func build() throws -> GetStoredScriptRequest {
return try GetStoredScriptRequest(withBuilder: self)
}
}
// MARK: - Get StoredScript Request
public struct GetStoredScriptRequest: Request {
public var headers = HTTPHeaders()
public let id: String
public var masterTimeout: String?
public init(_ id: String, masterTimeout: String? = nil) {
self.id = id
self.masterTimeout = masterTimeout
}
internal init(withBuilder builder: GetStoredScriptRequestBuilder) throws {
guard let id = builder.id else {
throw RequestBuilderError.missingRequiredField("id")
}
self.init(id, masterTimeout: builder.masterTimeout)
}
public var queryParams: [URLQueryItem] {
var queryItems = [URLQueryItem]()
if let masterTimeout = self.masterTimeout {
queryItems.append(.init(name: QueryParams.masterTimeout, value: masterTimeout))
}
return queryItems
}
public var method: HTTPMethod {
return .GET
}
public var endPoint: String {
return "_scripts/\(id)"
}
public func makeBody(_: Serializer) -> Result<Data, MakeBodyError> {
return .failure(.noBodyForRequest)
}
}
extension GetStoredScriptRequest: Equatable {}
// MARK: - Delete StoredScript Request Builder
public class DeleteStoredScriptRequestBuilder: RequestBuilder {
public typealias RequestType = DeleteStoredScriptRequest
private var _id: String?
private var _masterTimeout: String?
public init() {}
@discardableResult
public func set(id: String) -> Self {
_id = id
return self
}
@discardableResult
public func set(masterTimeout: String) -> Self {
_masterTimeout = masterTimeout
return self
}
public var id: String? {
return _id
}
public var masterTimeout: String? {
return _masterTimeout
}
public func build() throws -> DeleteStoredScriptRequest {
return try DeleteStoredScriptRequest(withBuilder: self)
}
}
// MARK: - Delete StoredScript Request
public struct DeleteStoredScriptRequest: Request {
public var headers = HTTPHeaders()
public let id: String
public var masterTimeout: String?
public init(_ id: String, masterTimeout: String? = nil) {
self.id = id
self.masterTimeout = masterTimeout
}
internal init(withBuilder builder: DeleteStoredScriptRequestBuilder) throws {
guard let id = builder.id else {
throw RequestBuilderError.missingRequiredField("id")
}
self.init(id, masterTimeout: builder.masterTimeout)
}
public var queryParams: [URLQueryItem] {
var queryItems = [URLQueryItem]()
if let masterTimeout = self.masterTimeout {
queryItems.append(.init(name: QueryParams.masterTimeout, value: masterTimeout))
}
return queryItems
}
public var method: HTTPMethod {
return .DELETE
}
public var endPoint: String {
return "_scripts/\(id)"
}
public func makeBody(_: Serializer) -> Result<Data, MakeBodyError> {
return .failure(.noBodyForRequest)
}
}
extension DeleteStoredScriptRequest: Equatable {}
|
2f945f0d6622ae2607d0deef3f39d642
| 23.900332 | 135 | 0.646298 | false | false | false | false |
hossamghareeb/Facebook-POP-Tutorial
|
refs/heads/master
|
Swift Version/POPDemo/Controllers/ExamplesListViewController/ExampleCell.swift
|
mit
|
1
|
//
// ExampleCell.swift
// POPSwiftDemo
//
// Created by Hossam Ghareeb on 1/29/15.
// Copyright (c) 2015 AppCoda. All rights reserved.
//
import UIKit
class ExampleCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
self.selectionStyle = UITableViewCellSelectionStyle.None
self.textLabel.font = UIFont(name: "Avenir-Light", size: 24)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if self.highlighted
{
let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
scaleAnimation.duration = 0.1
scaleAnimation.toValue = NSValue(CGPoint: CGPointMake(1, 1))
self.textLabel.pop_addAnimation(scaleAnimation, forKey: "scalingUp")
}
else
{
let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
springAnimation.toValue = NSValue(CGPoint: CGPointMake(0.9, 0.9))
springAnimation.velocity = NSValue(CGPoint: CGPointMake(2, 2))
springAnimation.springBounciness = 20.0
self.textLabel.pop_addAnimation(springAnimation, forKey: "springAnimation")
}
}
}
|
49fe22aeedcbab80bc84bbf40714dae5
| 32.1875 | 87 | 0.659761 | false | false | false | false |
betaY/columba
|
refs/heads/master
|
col/col/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// Columba
//
// Created by Beta on 15/7/23.
// Copyright © 2015年 Beta. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
// var userData: UserData?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField!.text as String!
let userPassword = userPasswordTextField!.text as String!
if (userEmail=="" || userPassword=="") {
let alert = UIAlertController(title: "Warning", message: "cannot let username or password empty", preferredStyle: UIAlertControllerStyle.Alert)
let okaction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil)
alert.addAction(okaction)
self.presentViewController(alert, animated: true, completion: nil)
}
let myUrl: NSURL! = NSURL(string: "http://beta.moe/userLogin.php")
let request: NSMutableURLRequest! = NSMutableURLRequest(URL: myUrl)
request.HTTPMethod = "POST"
let postString = "email=\(userEmail)&password=\(userPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
print("url \(myUrl)")
print("post string \(postString)")
print("request \(request.HTTPBody!)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// println("hello ")
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
let _: NSError?
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
let jsonArray = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
// print("json = \(json) err = \(err)")
print("array = \(jsonArray)")
if let parseJSON = json {
let resultValue = parseJSON["status"] as! String
print("result: \(resultValue)")
if (resultValue == "Success"){
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().setValue("\(userEmail)", forKey: "userEmail")
NSUserDefaults.standardUserDefaults().setValue("\(userPassword)", forKey: "userPassword")
// var userData = UserData(userEmail: "\(userEmail)", userPassword: "\(userPassword)")
// self.userData?.setUserEmail("\(userEmail)")
// self.userData?.setUserPassword("\(userPassword)")
// userData.setUserEmail("\(userEmail)")
// userData.setUserPassword("\(userPassword)")
// NSUserDefaults.standardUserDefaults().setValue(userData, forKey: "userdata")
NSUserDefaults.standardUserDefaults().synchronize()
// println("==================\(userData.getUserEmail()!) \(userData.getUserPassword()!)")
self.dismissViewControllerAnimated(true, completion: nil)
} else {
let messageToDisplay:String = parseJSON["message"] as! String
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion: nil)
self.userPasswordTextField.text = nil
})
}
}
}
task.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
c7c5a7888fc58fa934d3cc6e442e34ea
| 41.785124 | 155 | 0.578907 | false | false | false | false |
benlangmuir/swift
|
refs/heads/master
|
SwiftCompilerSources/Sources/SIL/Instruction.swift
|
apache-2.0
|
1
|
//===--- Instruction.swift - Defines the Instruction classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 Basic
import SILBridging
//===----------------------------------------------------------------------===//
// Instruction base classes
//===----------------------------------------------------------------------===//
public class Instruction : ListNode, CustomStringConvertible, Hashable {
final public var next: Instruction? {
SILInstruction_next(bridged).instruction
}
final public var previous: Instruction? {
SILInstruction_previous(bridged).instruction
}
// Needed for ReverseList<Instruction>.reversed(). Never use directly.
public var _firstInList: Instruction { SILBasicBlock_firstInst(block.bridged).instruction! }
// Needed for List<Instruction>.reversed(). Never use directly.
public var _lastInList: Instruction { SILBasicBlock_lastInst(block.bridged).instruction! }
final public var block: BasicBlock {
SILInstruction_getParent(bridged).block
}
final public var function: Function { block.function }
final public var description: String {
let stdString = SILNode_debugDescription(bridgedNode)
return String(_cxxString: stdString)
}
final public var operands: OperandArray {
return OperandArray(opArray: SILInstruction_getOperands(bridged))
}
fileprivate var resultCount: Int { 0 }
fileprivate func getResult(index: Int) -> Value { fatalError() }
public struct Results : RandomAccessCollection {
fileprivate let inst: Instruction
fileprivate let numResults: Int
public var startIndex: Int { 0 }
public var endIndex: Int { numResults }
public subscript(_ index: Int) -> Value { inst.getResult(index: index) }
}
final public var results: Results {
Results(inst: self, numResults: resultCount)
}
final public var location: Location {
return Location(bridged: SILInstruction_getLocation(bridged))
}
public var mayTrap: Bool { false }
final public var mayHaveSideEffects: Bool {
return mayTrap || mayWriteToMemory
}
final public var mayReadFromMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayWriteToMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayReadOrWriteMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior,
MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
public final var mayRelease: Bool {
return SILInstruction_mayRelease(bridged)
}
public func visitReferencedFunctions(_ cl: (Function) -> ()) {
}
public static func ==(lhs: Instruction, rhs: Instruction) -> Bool {
lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public var bridged: BridgedInstruction {
BridgedInstruction(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedInstruction {
public var instruction: Instruction { obj.getAs(Instruction.self) }
public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) }
public var optional: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: self.obj)
}
}
extension OptionalBridgedInstruction {
var instruction: Instruction? { obj.getAs(Instruction.self) }
public static var none: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: nil)
}
}
public class SingleValueInstruction : Instruction, Value {
final public var definingInstruction: Instruction? { self }
final public var definingBlock: BasicBlock { block }
fileprivate final override var resultCount: Int { 1 }
fileprivate final override func getResult(index: Int) -> Value { self }
public static func ==(lhs: SingleValueInstruction, rhs: SingleValueInstruction) -> Bool {
lhs === rhs
}
}
public final class MultipleValueInstructionResult : Value {
final public var description: String {
let stdString = SILNode_debugDescription(bridgedNode)
return String(_cxxString: stdString)
}
public var instruction: Instruction {
MultiValueInstResult_getParent(bridged).instruction
}
public var definingInstruction: Instruction? { instruction }
public var definingBlock: BasicBlock { instruction.block }
public var index: Int { MultiValueInstResult_getIndex(bridged) }
var bridged: BridgedMultiValueResult {
BridgedMultiValueResult(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedMultiValueResult {
var result: MultipleValueInstructionResult {
obj.getAs(MultipleValueInstructionResult.self)
}
}
public class MultipleValueInstruction : Instruction {
fileprivate final override var resultCount: Int {
return MultipleValueInstruction_getNumResults(bridged)
}
fileprivate final override func getResult(index: Int) -> Value {
MultipleValueInstruction_getResult(bridged, index).result
}
}
/// Instructions, which have a single operand.
public protocol UnaryInstruction : AnyObject {
var operands: OperandArray { get }
var operand: Value { get }
}
extension UnaryInstruction {
public var operand: Value { operands[0].value }
}
//===----------------------------------------------------------------------===//
// no-value instructions
//===----------------------------------------------------------------------===//
/// Used for all non-value instructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedInstruction : Instruction {
}
public protocol StoringInstruction : AnyObject {
var operands: OperandArray { get }
}
extension StoringInstruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
}
final public class StoreInst : Instruction, StoringInstruction {
// must match with enum class StoreOwnershipQualifier
public enum StoreOwnership: Int {
case unqualified = 0, initialize = 1, assign = 2, trivial = 3
}
public var destinationOwnership: StoreOwnership {
StoreOwnership(rawValue: StoreInst_getStoreOwnership(bridged))!
}
}
final public class StoreWeakInst : Instruction, StoringInstruction { }
final public class StoreUnownedInst : Instruction, StoringInstruction { }
final public class CopyAddrInst : Instruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
public var isTakeOfSrc: Bool {
CopyAddrInst_isTakeOfSrc(bridged) != 0
}
public var isInitializationOfDest: Bool {
CopyAddrInst_isInitializationOfDest(bridged) != 0
}
}
final public class EndAccessInst : Instruction, UnaryInstruction {
public var beginAccess: BeginAccessInst {
return operand as! BeginAccessInst
}
}
final public class EndBorrowInst : Instruction, UnaryInstruction {}
final public class DeallocStackInst : Instruction, UnaryInstruction {
public var allocstack: AllocStackInst {
return operand as! AllocStackInst
}
}
final public class DeallocStackRefInst : Instruction, UnaryInstruction {
public var allocRef: AllocRefInstBase { operand as! AllocRefInstBase }
}
final public class CondFailInst : Instruction, UnaryInstruction {
public override var mayTrap: Bool { true }
public var message: String { CondFailInst_getMessage(bridged).string }
}
final public class FixLifetimeInst : Instruction, UnaryInstruction {}
final public class DebugValueInst : Instruction, UnaryInstruction {}
final public class UnconditionalCheckedCastAddrInst : Instruction {
public override var mayTrap: Bool { true }
}
final public class SetDeallocatingInst : Instruction, UnaryInstruction {}
final public class DeallocRefInst : Instruction, UnaryInstruction {}
public class RefCountingInst : Instruction, UnaryInstruction {
public var isAtomic: Bool { RefCountingInst_getIsAtomic(bridged) }
}
final public class StrongRetainInst : RefCountingInst {
}
final public class RetainValueInst : RefCountingInst {
}
final public class StrongReleaseInst : RefCountingInst {
}
final public class ReleaseValueInst : RefCountingInst {
}
final public class DestroyValueInst : Instruction, UnaryInstruction {}
final public class DestroyAddrInst : Instruction, UnaryInstruction {}
final public class InjectEnumAddrInst : Instruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InjectEnumAddrInst_caseIndex(bridged) }
}
final public class UnimplementedRefCountingInst : RefCountingInst {}
//===----------------------------------------------------------------------===//
// single-value instructions
//===----------------------------------------------------------------------===//
/// Used for all SingleValueInstructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedSingleValueInst : SingleValueInstruction {
}
final public class LoadInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadWeakInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class BuiltinInst : SingleValueInstruction {
// TODO: find a way to directly reuse the BuiltinValueKind enum
public enum ID {
case none
case destroyArray
case stackAlloc
}
public var id: ID {
switch BuiltinInst_getID(bridged) {
case DestroyArrayBuiltin: return .destroyArray
case StackAllocBuiltin: return .stackAlloc
default: return .none
}
}
}
final public class UpcastInst : SingleValueInstruction, UnaryInstruction {}
final public
class UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {}
final public
class RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class AddressToPointerInst : SingleValueInstruction, UnaryInstruction {
public var needsStackProtection: Bool {
AddressToPointerInst_needsStackProtection(bridged) != 0
}
}
final public
class PointerToAddressInst : SingleValueInstruction, UnaryInstruction {}
final public
class IndexAddrInst : SingleValueInstruction {
public var base: Value { operands[0].value }
public var index: Value { operands[1].value }
public var needsStackProtection: Bool {
IndexAddrInst_needsStackProtection(bridged) != 0
}
}
final public
class InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
public class GlobalAccessInst : SingleValueInstruction {
final public var global: GlobalVariable {
GlobalAccessInst_getGlobal(bridged).globalVar
}
}
public class FunctionRefBaseInst : SingleValueInstruction {
public var referencedFunction: Function {
FunctionRefBaseInst_getReferencedFunction(bridged).function
}
public override func visitReferencedFunctions(_ cl: (Function) -> ()) {
cl(referencedFunction)
}
}
final public class FunctionRefInst : FunctionRefBaseInst {
}
final public class DynamicFunctionRefInst : FunctionRefBaseInst {
}
final public class PreviousDynamicFunctionRefInst : FunctionRefBaseInst {
}
final public class GlobalAddrInst : GlobalAccessInst {}
final public class GlobalValueInst : GlobalAccessInst {}
final public class IntegerLiteralInst : SingleValueInstruction {}
final public class StringLiteralInst : SingleValueInstruction {
public var string: String { StringLiteralInst_getValue(bridged).string }
}
final public class TupleInst : SingleValueInstruction {
}
final public class TupleExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleExtractInst_fieldIndex(bridged) }
}
final public
class TupleElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleElementAddrInst_fieldIndex(bridged) }
}
final public class StructInst : SingleValueInstruction {
}
final public class StructExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructExtractInst_fieldIndex(bridged) }
}
final public
class StructElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructElementAddrInst_fieldIndex(bridged) }
}
public protocol EnumInstruction : AnyObject {
var caseIndex: Int { get }
}
final public class EnumInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { EnumInst_caseIndex(bridged) }
public var operand: Value? { operands.first?.value }
}
final public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedEnumDataInst_caseIndex(bridged) }
}
final public class InitEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InitEnumDataAddrInst_caseIndex(bridged) }
}
final public class UncheckedTakeEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedTakeEnumDataAddrInst_caseIndex(bridged) }
}
final public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { RefElementAddrInst_fieldIndex(bridged) }
public var fieldIsLet: Bool { RefElementAddrInst_fieldIsLet(bridged) != 0 }
}
final public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {}
final public class KeyPathInst : SingleValueInstruction {
public override func visitReferencedFunctions(_ cl: (Function) -> ()) {
var results = KeyPathFunctionResults()
for componentIdx in 0..<KeyPathInst_getNumComponents(bridged) {
KeyPathInst_getReferencedFunctions(bridged, componentIdx, &results)
let numFuncs = results.numFunctions
withUnsafePointer(to: &results) {
$0.withMemoryRebound(to: BridgedFunction.self, capacity: numFuncs) {
let functions = UnsafeBufferPointer(start: $0, count: numFuncs)
for idx in 0..<numFuncs {
cl(functions[idx].function)
}
}
}
}
}
}
final public
class UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction {
public override var mayTrap: Bool { true }
}
final public
class ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ObjCExistentialMetatypeToObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public
class ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class MarkDependenceInst : SingleValueInstruction {
public var value: Value { return operands[0].value }
public var base: Value { return operands[1].value }
}
final public class RefToBridgeObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToRefInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToWordInst : SingleValueInstruction,
UnaryInstruction {}
public enum AccessKind {
case initialize
case read
case modify
case deinitialize
}
extension BridgedAccessKind {
var kind: AccessKind {
switch self {
case AccessKind_Init:
return .initialize
case AccessKind_Read:
return .read
case AccessKind_Modify:
return .modify
case AccessKind_Deinit:
return .deinitialize
default:
fatalError("unsupported access kind")
}
}
}
// TODO: add support for begin_unpaired_access
final public class BeginAccessInst : SingleValueInstruction, UnaryInstruction {
public var accessKind: AccessKind { BeginAccessInst_getAccessKind(bridged).kind }
}
public protocol ScopedInstruction {
associatedtype EndInstructions
var endInstructions: EndInstructions { get }
}
extension BeginAccessInst : ScopedInstruction {
public typealias EndInstructions = LazyMapSequence<LazyFilterSequence<LazyMapSequence<UseList, EndAccessInst?>>, EndAccessInst>
public var endInstructions: EndInstructions {
uses.lazy.compactMap({ $0.instruction as? EndAccessInst })
}
}
final public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class ProjectBoxInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { ProjectBoxInst_fieldIndex(bridged) }
}
final public class CopyValueInst : SingleValueInstruction, UnaryInstruction {}
final public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {}
final public
class ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public class PartialApplyInst : SingleValueInstruction, ApplySite {
public var numArguments: Int { PartialApplyInst_numArguments(bridged) }
public var isOnStack: Bool { PartialApplyInst_isOnStack(bridged) != 0 }
public func calleeArgIndex(callerArgIndex: Int) -> Int {
PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged) + callerArgIndex
}
public func callerArgIndex(calleeArgIndex: Int) -> Int? {
let firstIdx = PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged)
if calleeArgIndex >= firstIdx {
let callerIdx = calleeArgIndex - firstIdx
if callerIdx < numArguments {
return callerIdx
}
}
return nil
}
}
final public class ApplyInst : SingleValueInstruction, FullApplySite {
public var numArguments: Int { ApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { self }
}
final public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class WitnessMethodInst : SingleValueInstruction {}
final public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {}
final public class IsEscapingClosureInst : SingleValueInstruction, UnaryInstruction {}
//===----------------------------------------------------------------------===//
// single-value allocation instructions
//===----------------------------------------------------------------------===//
public protocol Allocation : AnyObject { }
final public class AllocStackInst : SingleValueInstruction, Allocation {
}
public class AllocRefInstBase : SingleValueInstruction, Allocation {
final public var isObjC: Bool { AllocRefInstBase_isObjc(bridged) != 0 }
final public var canAllocOnStack: Bool {
AllocRefInstBase_canAllocOnStack(bridged) != 0
}
}
final public class AllocRefInst : AllocRefInstBase {
}
final public class AllocRefDynamicInst : AllocRefInstBase {
}
final public class AllocBoxInst : SingleValueInstruction, Allocation {
}
final public class AllocExistentialBoxInst : SingleValueInstruction, Allocation {
}
//===----------------------------------------------------------------------===//
// multi-value instructions
//===----------------------------------------------------------------------===//
final public class BeginCOWMutationInst : MultipleValueInstruction,
UnaryInstruction {
public var uniquenessResult: Value { return getResult(index: 0) }
public var bufferResult: Value { return getResult(index: 1) }
}
final public class DestructureStructInst : MultipleValueInstruction, UnaryInstruction {
}
final public class DestructureTupleInst : MultipleValueInstruction, UnaryInstruction {
}
final public class BeginApplyInst : MultipleValueInstruction, FullApplySite {
public var numArguments: Int { BeginApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { nil }
}
//===----------------------------------------------------------------------===//
// terminator instructions
//===----------------------------------------------------------------------===//
public class TermInst : Instruction {
final public var successors: SuccessorArray {
SuccessorArray(succArray: TermInst_getSuccessors(bridged))
}
public var isFunctionExiting: Bool { false }
}
final public class UnreachableInst : TermInst {
}
final public class ReturnInst : TermInst, UnaryInstruction {
public override var isFunctionExiting: Bool { true }
}
final public class ThrowInst : TermInst, UnaryInstruction {
public override var isFunctionExiting: Bool { true }
}
final public class YieldInst : TermInst {
}
final public class UnwindInst : TermInst {
public override var isFunctionExiting: Bool { true }
}
final public class TryApplyInst : TermInst, FullApplySite {
public var numArguments: Int { TryApplyInst_numArguments(bridged) }
public var normalBlock: BasicBlock { successors[0] }
public var errorBlock: BasicBlock { successors[1] }
public var singleDirectResult: Value? { normalBlock.arguments[0] }
}
final public class BranchInst : TermInst {
public var targetBlock: BasicBlock { BranchInst_getTargetBlock(bridged).block }
public func getArgument(for operand: Operand) -> Argument {
return targetBlock.arguments[operand.index]
}
}
final public class CondBranchInst : TermInst {
var trueBlock: BasicBlock { successors[0] }
var falseBlock: BasicBlock { successors[1] }
var condition: Value { operands[0].value }
var trueOperands: OperandArray { operands[1...CondBranchInst_getNumTrueArgs(bridged)] }
var falseOperands: OperandArray {
let ops = operands
return ops[(CondBranchInst_getNumTrueArgs(bridged) &+ 1)..<ops.count]
}
public func getArgument(for operand: Operand) -> Argument {
let argIdx = operand.index - 1
let numTrueArgs = CondBranchInst_getNumTrueArgs(bridged)
if (0..<numTrueArgs).contains(argIdx) {
return trueBlock.arguments[argIdx]
} else {
return falseBlock.arguments[argIdx - numTrueArgs]
}
}
}
final public class SwitchValueInst : TermInst {
}
final public class SwitchEnumInst : TermInst {
public var enumOp: Value { operands[0].value }
public struct CaseIndexArray : RandomAccessCollection {
fileprivate let switchEnum: SwitchEnumInst
public var startIndex: Int { return 0 }
public var endIndex: Int { SwitchEnumInst_getNumCases(switchEnum.bridged) }
public subscript(_ index: Int) -> Int {
SwitchEnumInst_getCaseIndex(switchEnum.bridged, index)
}
}
var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) }
var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> {
zip(caseIndices, successors)
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? {
cases.first(where: { $0.0 == forCaseIndex })?.1
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueCase(forSuccessor: BasicBlock) -> Int? {
cases.first(where: { $0.1 == forSuccessor })?.0
}
}
final public class SwitchEnumAddrInst : TermInst {
}
final public class DynamicMethodBranchInst : TermInst {
}
final public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction {
}
final public class CheckedCastBranchInst : TermInst, UnaryInstruction {
}
final public class CheckedCastAddrBranchInst : TermInst, UnaryInstruction {
}
|
c3b2547134b8fff5f5af47e789102af3
| 30.72113 | 129 | 0.727083 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Extensions/String+SwiftLint.swift
|
mit
|
1
|
import Foundation
import SourceKittenFramework
extension String {
internal func hasTrailingWhitespace() -> Bool {
if isEmpty {
return false
}
if let unicodescalar = unicodeScalars.last {
return CharacterSet.whitespaces.contains(unicodescalar)
}
return false
}
internal func isUppercase() -> Bool {
return self == uppercased()
}
internal func isLowercase() -> Bool {
return self == lowercased()
}
internal func nameStrippingLeadingUnderscoreIfPrivate(_ dict: SourceKittenDictionary) -> String {
if let acl = dict.accessibility,
acl.isPrivate && first == "_" {
return String(self[index(after: startIndex)...])
}
return self
}
private subscript (range: Range<Int>) -> String {
let nsrange = NSRange(location: range.lowerBound,
length: range.upperBound - range.lowerBound)
if let indexRange = nsrangeToIndexRange(nsrange) {
return String(self[indexRange])
}
queuedFatalError("invalid range")
}
internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length {
return self[from..<from + length]
}
return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...])
}
internal func lastIndex(of search: String) -> Int? {
if let range = range(of: search, options: [.literal, .backwards]) {
return distance(from: startIndex, to: range.lowerBound)
}
return nil
}
internal func nsrangeToIndexRange(_ nsrange: NSRange) -> Range<Index>? {
guard nsrange.location != NSNotFound else {
return nil
}
let from16 = utf16.index(utf16.startIndex, offsetBy: nsrange.location,
limitedBy: utf16.endIndex) ?? utf16.endIndex
let to16 = utf16.index(from16, offsetBy: nsrange.length,
limitedBy: utf16.endIndex) ?? utf16.endIndex
guard let fromIndex = Index(from16, within: self),
let toIndex = Index(to16, within: self) else {
return nil
}
return fromIndex..<toIndex
}
internal var fullNSRange: NSRange {
return NSRange(location: 0, length: utf16.count)
}
/// Returns a new string, converting the path to a canonical absolute path.
///
/// - returns: A new `String`.
public func absolutePathStandardized() -> String {
return bridge().absolutePathRepresentation().bridge().standardizingPath
}
internal var isFile: Bool {
if self.isEmpty {
return false
}
var isDirectoryObjC: ObjCBool = false
if FileManager.default.fileExists(atPath: self, isDirectory: &isDirectoryObjC) {
return !isDirectoryObjC.boolValue
}
return false
}
/// Count the number of occurrences of the given character in `self`
/// - Parameter character: Character to count
/// - Returns: Number of times `character` occurs in `self`
public func countOccurrences(of character: Character) -> Int {
return self.reduce(0, {
$1 == character ? $0 + 1 : $0
})
}
/// If self is a path, this method can be used to get a path expression relative to a root directory
public func path(relativeTo rootDirectory: String) -> String {
let normalizedRootDir = rootDirectory.bridge().standardizingPath
let normalizedSelf = bridge().standardizingPath
if normalizedRootDir.isEmpty {
return normalizedSelf
}
var rootDirComps = normalizedRootDir.components(separatedBy: "/")
let rootDirCompsCount = rootDirComps.count
while true {
let sharedRootDir = rootDirComps.joined(separator: "/")
if normalizedSelf == sharedRootDir || normalizedSelf.hasPrefix(sharedRootDir + "/") {
let path = (0 ..< rootDirCompsCount - rootDirComps.count).map { _ in "/.." }.flatMap { $0 }
+ String(normalizedSelf.dropFirst(sharedRootDir.count))
return String(path.dropFirst()) // Remove leading '/'
} else {
rootDirComps = rootDirComps.dropLast()
}
}
}
internal func deletingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else { return self }
return String(dropFirst(prefix.count))
}
}
|
6f0cb5431c84f8a25e75c791f671561b
| 33.976923 | 107 | 0.600616 | false | false | false | false |
esttorhe/SwiftSSH2
|
refs/heads/swift-2.0
|
SwiftSSH2/SSHChannel.swift
|
mit
|
1
|
/**
*/
public enum PTYTerminal: String {
case Vanilla = "vanilla"
case VT100 = "vt100"
case VT102 = "vt102"
case VT220 = "vt220"
case Ansi = "ansi"
case Xterm = "xterm"
case None = ""
}
/**
*/
public enum ChannelType {
case Closed
case Exec
case Shell
case SCP
case Subsystem
}
public enum ChannelError: ErrorType {
case UnableToOpenChannelSession
}
/**
*/
public class SSHChannel {
private let session: SSH2Session
private var channel: SSH2Channel?=nil
private let LIBSSH2_CHANNEL_WINDOW_DEFAULT: UInt32 = 256*1024
private (set) public var ptyTerminal = PTYTerminal.None
// MARK: - Initializers
/**
*/
public init(session: SSH2Session) {
self.session = session
}
/**
*/
public func openChannel(channel: SSH2Channel?=nil) throws -> SSH2Channel {
libssh2_session_set_blocking(session.cSession, 10)
let windowSize: UInt32 = 256*1024
let cChannel = libssh2_channel_open_ex(session.cSession, "session", UInt32("session".characters.count - 1), windowSize, UInt32(LIBSSH2_CHANNEL_PACKET_DEFAULT), nil, UInt32(0))
self.channel = SSH2Channel(channel: cChannel)
guard cChannel.hashValue == 0 else {
throw ChannelError.UnableToOpenChannelSession
}
return self.channel!
}
}
|
0299017910b466817fa9210c34686b2f
| 20.711864 | 179 | 0.682031 | false | false | false | false |
externl/ice
|
refs/heads/3.7
|
swift/src/Ice/ConnectionInfoFactory.swift
|
gpl-2.0
|
4
|
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Foundation
import IceImpl
private class ConnectionInfoI: ConnectionInfo {
var underlying: ConnectionInfo?
var incoming: Bool
var adapterName: String
var connectionId: String
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String) {
self.underlying = underlying
self.incoming = incoming
self.adapterName = adapterName
self.connectionId = connectionId
}
}
private class IPConnectionInfoI: ConnectionInfoI, IPConnectionInfo {
var localAddress: String
var localPort: Int32
var remoteAddress: String
var remotePort: Int32
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
localAddress: String, localPort: Int32, remoteAddress: String, remotePort: Int32) {
self.localAddress = localAddress
self.localPort = localPort
self.remoteAddress = remoteAddress
self.remotePort = remotePort
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId)
}
}
private class TCPConnectionInfoI: IPConnectionInfoI, TCPConnectionInfo {
var rcvSize: Int32
var sndSize: Int32
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
localAddress: String, localPort: Int32, remoteAddress: String, remotePort: Int32,
rcvSize: Int32, sndSize: Int32) {
self.rcvSize = rcvSize
self.sndSize = sndSize
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId,
localAddress: localAddress, localPort: localPort,
remoteAddress: remoteAddress, remotePort: remotePort)
}
}
private class UDPConnectionInfoI: IPConnectionInfoI, UDPConnectionInfo {
var mcastAddress: String
var mcastPort: Int32
var rcvSize: Int32
var sndSize: Int32
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
localAddress: String, localPort: Int32, remoteAddress: String, remotePort: Int32,
mcastAddress: String, mcastPort: Int32, rcvSize: Int32, sndSize: Int32) {
self.mcastAddress = mcastAddress
self.mcastPort = mcastPort
self.rcvSize = rcvSize
self.sndSize = sndSize
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId,
localAddress: localAddress, localPort: localPort,
remoteAddress: remoteAddress, remotePort: remotePort)
}
}
private class WSConnectionInfoI: ConnectionInfoI, WSConnectionInfo {
var headers: HeaderDict
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
headers: HeaderDict) {
self.headers = headers
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId)
}
}
private class SSLConnectionInfoI: ConnectionInfoI, SSLConnectionInfo {
var cipher: String
var certs: [SecCertificate]
var verified: Bool
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
cipher: String, certs: StringSeq, verified: Bool) {
self.cipher = cipher
self.certs = []
let beginPrefix = "-----BEGIN CERTIFICATE-----\n"
let endPrefix = "\n-----END CERTIFICATE-----\n"
for cert in certs {
var raw = cert
if raw.hasPrefix(beginPrefix) {
raw = String(raw.dropFirst(beginPrefix.count))
raw = String(raw.dropLast(endPrefix.count))
}
if let data = NSData(base64Encoded: raw, options: .ignoreUnknownCharacters) {
if let c = SecCertificateCreateWithData(kCFAllocatorDefault, data) {
self.certs.append(c)
}
}
}
self.verified = verified
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId)
}
}
#if os(iOS) || os(watchOS) || os(tvOS)
private class IAPConnectionInfoI: ConnectionInfoI, IAPConnectionInfo {
var name: String
var manufacturer: String
var modelNumber: String
var firmwareRevision: String
var hardwareRevision: String
var `protocol`: String
init(underlying: ConnectionInfo?, incoming: Bool, adapterName: String, connectionId: String,
name: String, manufacturer: String, modelNumber: String, firmwareRevision: String,
hardwareRevision: String,
protocol: String) {
self.name = name
self.manufacturer = manufacturer
self.modelNumber = modelNumber
self.firmwareRevision = firmwareRevision
self.hardwareRevision = hardwareRevision
self.protocol = `protocol`
super.init(underlying: underlying, incoming: incoming, adapterName: adapterName, connectionId: connectionId)
}
}
#endif
class ConnectionInfoFactory: ICEConnectionInfoFactory {
static func createIPConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
localAddress: String,
localPort: Int32,
remoteAddress: String,
remotePort: Int32) -> Any {
return IPConnectionInfoI(underlying: getUnderlying(underlying),
incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
localAddress: localAddress,
localPort: localPort,
remoteAddress: remoteAddress,
remotePort: remotePort)
}
static func createTCPConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
localAddress: String,
localPort: Int32,
remoteAddress: String,
remotePort: Int32,
rcvSize: Int32,
sndSize: Int32) -> Any {
return TCPConnectionInfoI(underlying: getUnderlying(underlying), incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
localAddress: localAddress,
localPort: localPort,
remoteAddress: remoteAddress,
remotePort: remotePort,
rcvSize: rcvSize,
sndSize: sndSize)
}
static func createUDPConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
localAddress: String,
localPort: Int32,
remoteAddress: String,
remotePort: Int32, mcastAddress: String, mcastPort: Int32,
rcvSize: Int32,
sndSize: Int32) -> Any {
return UDPConnectionInfoI(underlying: getUnderlying(underlying), incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
localAddress: localAddress,
localPort: localPort,
remoteAddress: remoteAddress,
remotePort: remotePort,
mcastAddress: mcastAddress,
mcastPort: mcastPort,
rcvSize: rcvSize,
sndSize: sndSize)
}
static func createWSConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
headers: [String: String]) -> Any {
return WSConnectionInfoI(underlying: getUnderlying(underlying),
incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
headers: headers)
}
static func createSSLConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
cipher: String,
certs: [String], verified: Bool) -> Any {
return SSLConnectionInfoI(underlying: getUnderlying(underlying),
incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
cipher: cipher,
certs: certs,
verified: verified)
}
#if os(iOS) || os(watchOS) || os(tvOS)
static func createIAPConnectionInfo(_ underlying: Any,
incoming: Bool,
adapterName: String,
connectionId: String,
name: String,
manufacturer: String,
modelNumber: String,
firmwareRevision: String,
hardwareRevision: String,
protocol: String) -> Any {
return IAPConnectionInfoI(underlying: getUnderlying(underlying),
incoming: incoming,
adapterName: adapterName,
connectionId: connectionId,
name: name,
manufacturer: manufacturer,
modelNumber: modelNumber,
firmwareRevision: firmwareRevision,
hardwareRevision: hardwareRevision,
protocol: `protocol`)
}
#endif
static func getUnderlying(_ info: Any) -> ConnectionInfo? {
return info as? ConnectionInfo
}
}
|
15570aae03d397499224e00a6b682562
| 44.47451 | 120 | 0.509917 | false | false | false | false |
onevcat/Kingfisher
|
refs/heads/master
|
Sources/Image/ImageProcessor.swift
|
mit
|
2
|
//
// ImageProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/26.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
#endif
/// Represents an item which could be processed by an `ImageProcessor`.
///
/// - image: Input image. The processor should provide a way to apply
/// processing on this `image` and return the result image.
/// - data: Input data. The processor should provide a way to apply
/// processing on this `data` and return the result image.
public enum ImageProcessItem {
/// Input image. The processor should provide a way to apply
/// processing on this `image` and return the result image.
case image(KFCrossPlatformImage)
/// Input data. The processor should provide a way to apply
/// processing on this `data` and return the result image.
case data(Data)
}
/// An `ImageProcessor` would be used to convert some downloaded data to an image.
public protocol ImageProcessor {
/// Identifier of the processor. It will be used to identify the processor when
/// caching and retrieving an image. You might want to make sure that processors with
/// same properties/functionality have the same identifiers, so correct processed images
/// could be retrieved with proper key.
///
/// - Note: Do not supply an empty string for a customized processor, which is already reserved by
/// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of
/// your own for the identifier.
var identifier: String { get }
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: The parsed options when processing the item.
/// - Returns: The processed image.
///
/// - Note: The return value should be `nil` if processing failed while converting an input item to image.
/// If `nil` received by the processing caller, an error will be reported and the process flow stops.
/// If the processing flow is not critical for your flow, then when the input item is already an image
/// (`.image` case) and there is any errors in the processing, you could return the input image itself
/// to keep the processing pipeline continuing.
/// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
/// a filter, the input image will be returned directly on watchOS.
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
}
extension ImageProcessor {
/// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
/// will be "\(self.identifier)|>\(another.identifier)".
///
/// - Parameter another: An `ImageProcessor` you want to append to `self`.
/// - Returns: The new `ImageProcessor` will process the image in the order
/// of the two processors concatenated.
public func append(another: ImageProcessor) -> ImageProcessor {
let newIdentifier = identifier.appending("|>\(another.identifier)")
return GeneralProcessor(identifier: newIdentifier) {
item, options in
if let image = self.process(item: item, options: options) {
return another.process(item: .image(image), options: options)
} else {
return nil
}
}
}
}
func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
return left.identifier == right.identifier
}
func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
return !(left == right)
}
typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?)
struct GeneralProcessor: ImageProcessor {
let identifier: String
let p: ProcessorImp
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return p(item, options)
}
}
/// The default processor. It converts the input data to a valid image.
/// Images of .PNG, .JPEG and .GIF format are supported.
/// If an image item is given as `.image` case, `DefaultImageProcessor` will
/// do nothing on it and return the associated image.
public struct DefaultImageProcessor: ImageProcessor {
/// A default `DefaultImageProcessor` could be used across.
public static let `default` = DefaultImageProcessor()
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier = ""
/// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance,
/// if you do not have a good reason to create your own `DefaultImageProcessor`.
public init() {}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
case .data(let data):
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
}
}
/// Represents the rect corner setting when processing a round corner image.
public struct RectCorner: OptionSet {
/// Raw value of the rect corner.
public let rawValue: Int
/// Represents the top left corner.
public static let topLeft = RectCorner(rawValue: 1 << 0)
/// Represents the top right corner.
public static let topRight = RectCorner(rawValue: 1 << 1)
/// Represents the bottom left corner.
public static let bottomLeft = RectCorner(rawValue: 1 << 2)
/// Represents the bottom right corner.
public static let bottomRight = RectCorner(rawValue: 1 << 3)
/// Represents all corners.
public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
/// Creates a `RectCorner` option set with a given value.
///
/// - Parameter rawValue: The value represents a certain corner option.
public init(rawValue: Int) {
self.rawValue = rawValue
}
var cornerIdentifier: String {
if self == .all {
return ""
}
return "_corner(\(rawValue))"
}
}
#if !os(macOS)
/// Processor for adding an blend mode to images. Only CG-based images are supported.
public struct BlendImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Blend Mode will be used to blend the input image.
public let blendMode: CGBlendMode
/// Alpha will be used when blend image.
public let alpha: CGFloat
/// Background color of the output image. If `nil`, it will stay transparent.
public let backgroundColor: KFCrossPlatformColor?
/// Creates a `BlendImageProcessor`.
///
/// - Parameters:
/// - blendMode: Blend Mode will be used to blend the input image.
/// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image,
/// 0.0 means transparent image (not visible at all). Default is 1.0.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) {
self.blendMode = blendMode
self.alpha = alpha
self.backgroundColor = backgroundColor
var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
if let color = backgroundColor {
identifier.append("_\(color.rgbaDescription)")
}
self.identifier = identifier
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
#endif
#if os(macOS)
/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
public struct CompositingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Compositing operation will be used to the input image.
public let compositingOperation: NSCompositingOperation
/// Alpha will be used when compositing image.
public let alpha: CGFloat
/// Background color of the output image. If `nil`, it will stay transparent.
public let backgroundColor: KFCrossPlatformColor?
/// Creates a `CompositingImageProcessor`
///
/// - Parameters:
/// - compositingOperation: Compositing operation will be used to the input image.
/// - alpha: Alpha will be used when compositing image.
/// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
/// Default is 1.0.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(compositingOperation: NSCompositingOperation,
alpha: CGFloat = 1.0,
backgroundColor: KFCrossPlatformColor? = nil)
{
self.compositingOperation = compositingOperation
self.alpha = alpha
self.backgroundColor = backgroundColor
var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
if let color = backgroundColor {
identifier.append("_\(color.rgbaDescription)")
}
self.identifier = identifier
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.image(
withCompositingOperation: compositingOperation,
alpha: alpha,
backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
#endif
/// Represents a radius specified in a `RoundCornerImageProcessor`.
public enum Radius {
/// The radius should be calculated as a fraction of the image width. Typically the associated value should be
/// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width.
case widthFraction(CGFloat)
/// The radius should be calculated as a fraction of the image height. Typically the associated value should be
/// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height.
case heightFraction(CGFloat)
/// Use a fixed point value as the round corner radius.
case point(CGFloat)
var radiusIdentifier: String {
switch self {
case .widthFraction(let f):
return "w_frac_\(f)"
case .heightFraction(let f):
return "h_frac_\(f)"
case .point(let p):
return p.description
}
}
public func compute(with size: CGSize) -> CGFloat {
let cornerRadius: CGFloat
switch self {
case .point(let point):
cornerRadius = point
case .widthFraction(let widthFraction):
cornerRadius = size.width * widthFraction
case .heightFraction(let heightFraction):
cornerRadius = size.height * heightFraction
}
return cornerRadius
}
}
/// Processor for making round corner images. Only CG-based images are supported in macOS,
/// if a non-CG image passed in, the processor will do nothing.
///
/// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain
/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order
/// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That
/// means the alpha channel will be removed for these images. When you load the processed image from cache again, you
/// will lose transparent corner.
///
/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this
/// case.
///
public struct RoundCornerImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
/// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
/// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
public let radius: Radius
/// The target corners which will be applied rounding.
public let roundingCorners: RectCorner
/// Target size of output image should be. If `nil`, the image will keep its original size after processing.
public let targetSize: CGSize?
/// Background color of the output image. If `nil`, it will use a transparent background.
public let backgroundColor: KFCrossPlatformColor?
/// Creates a `RoundCornerImageProcessor`.
///
/// - Parameters:
/// - cornerRadius: Corner radius in point will be applied in processing.
/// - targetSize: Target size of output image should be. If `nil`,
/// the image will keep its original size after processing.
/// Default is `nil`.
/// - corners: The target corners which will be applied rounding. Default is `.all`.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
///
/// - Note:
///
/// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still
/// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a
/// fraction of one dimension of the target image, use the `Radius` version instead.
///
public init(
cornerRadius: CGFloat,
targetSize: CGSize? = nil,
roundingCorners corners: RectCorner = .all,
backgroundColor: KFCrossPlatformColor? = nil
)
{
let radius = Radius.point(cornerRadius)
self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor)
}
/// Creates a `RoundCornerImageProcessor`.
///
/// - Parameters:
/// - radius: The radius will be applied in processing.
/// - targetSize: Target size of output image should be. If `nil`,
/// the image will keep its original size after processing.
/// Default is `nil`.
/// - corners: The target corners which will be applied rounding. Default is `.all`.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(
radius: Radius,
targetSize: CGSize? = nil,
roundingCorners corners: RectCorner = .all,
backgroundColor: KFCrossPlatformColor? = nil
)
{
self.radius = radius
self.targetSize = targetSize
self.roundingCorners = corners
self.backgroundColor = backgroundColor
self.identifier = {
var identifier = ""
if let size = targetSize {
identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
"(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))"
} else {
identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
"(\(radius.radiusIdentifier)\(corners.cornerIdentifier))"
}
if let backgroundColor = backgroundColor {
identifier += "_\(backgroundColor)"
}
return identifier
}()
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
let size = targetSize ?? image.kf.size
return image.kf.scaled(to: options.scaleFactor)
.kf.image(
withRadius: radius,
fit: size,
roundingCorners: roundingCorners,
backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
public struct Border {
public var color: KFCrossPlatformColor
public var lineWidth: CGFloat
/// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
/// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
/// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
public var radius: Radius
/// The target corners which will be applied rounding.
public var roundingCorners: RectCorner
public init(
color: KFCrossPlatformColor = .black,
lineWidth: CGFloat = 4,
radius: Radius = .point(0),
roundingCorners: RectCorner = .all
) {
self.color = color
self.lineWidth = lineWidth
self.radius = radius
self.roundingCorners = roundingCorners
}
var identifier: String {
"\(color.rgbaDescription)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)"
}
}
public struct BorderImageProcessor: ImageProcessor {
public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" }
public let border: Border
public init(border: Border) {
self.border = border
}
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.addingBorder(border)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Represents how a size adjusts itself to fit a target size.
///
/// - none: Not scale the content.
/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio.
/// - aspectFill: Scales the content to fill the size of the view.
public enum ContentMode {
/// Not scale the content.
case none
/// Scales the content to fit the size of the view by maintaining the aspect ratio.
case aspectFit
/// Scales the content to fill the size of the view.
case aspectFill
}
/// Processor for resizing images.
/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
/// instead, which is more efficient and uses less memory.
public struct ResizingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// The reference size for resizing operation in point.
public let referenceSize: CGSize
/// Target content mode of output image should be.
/// Default is `.none`.
public let targetContentMode: ContentMode
/// Creates a `ResizingImageProcessor`.
///
/// - Parameters:
/// - referenceSize: The reference size for resizing operation in point.
/// - mode: Target content mode of output image should be.
///
/// - Note:
/// The instance of `ResizingImageProcessor` will follow its `mode` property
/// and try to resizing the input images to fit or fill the `referenceSize`.
/// That means if you are using a `mode` besides of `.none`, you may get an
/// image with its size not be the same as the `referenceSize`.
///
/// **Example**: With input image size: {100, 200},
/// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
/// you will get an output image with size of {50, 100}, which "fit"s
/// the `referenceSize`.
///
/// If you need an output image exactly to be a specified size, append or use
/// a `CroppingImageProcessor`.
public init(referenceSize: CGSize, mode: ContentMode = .none) {
self.referenceSize = referenceSize
self.targetContentMode = mode
if mode == .none {
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
} else {
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
}
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.resize(to: referenceSize, for: targetContentMode)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
public struct BlurImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Blur radius for the simulated Gaussian blur.
public let blurRadius: CGFloat
/// Creates a `BlurImageProcessor`
///
/// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
public init(blurRadius: CGFloat) {
self.blurRadius = blurRadius
self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
let radius = blurRadius * options.scaleFactor
return image.kf.scaled(to: options.scaleFactor)
.kf.blurred(withRadius: radius)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
public struct OverlayImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Overlay color will be used to overlay the input image.
public let overlay: KFCrossPlatformColor
/// Fraction will be used when overlay the color to image.
public let fraction: CGFloat
/// Creates an `OverlayImageProcessor`
///
/// - parameter overlay: Overlay color will be used to overlay the input image.
/// - parameter fraction: Fraction will be used when overlay the color to image.
/// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) {
self.overlay = overlay
self.fraction = fraction
self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.rgbaDescription)_\(fraction))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.overlaying(with: overlay, fraction: fraction)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for tint images with color. Only CG-based images are supported.
public struct TintImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Tint color will be used to tint the input image.
public let tint: KFCrossPlatformColor
/// Creates a `TintImageProcessor`
///
/// - parameter tint: Tint color will be used to tint the input image.
public init(tint: KFCrossPlatformColor) {
self.tint = tint
self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.rgbaDescription))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.tinted(with: tint)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for applying some color control to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct ColorControlsProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Brightness changing to image.
public let brightness: CGFloat
/// Contrast changing to image.
public let contrast: CGFloat
/// Saturation changing to image.
public let saturation: CGFloat
/// InputEV changing to image.
public let inputEV: CGFloat
/// Creates a `ColorControlsProcessor`
///
/// - Parameters:
/// - brightness: Brightness changing to image.
/// - contrast: Contrast changing to image.
/// - saturation: Saturation changing to image.
/// - inputEV: InputEV changing to image.
public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.inputEV = inputEV
self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
case .data:
return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for applying black and white effect to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct BlackWhiteProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
/// Creates a `BlackWhiteProcessor`
public init() {}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
.process(item: item, options: options)
}
}
/// Processor for cropping an image. Only CG-based images are supported.
/// watchOS is not supported.
public struct CroppingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Target size of output image should be.
public let size: CGSize
/// Anchor point from which the output size should be calculate.
/// The anchor point is consisted by two values between 0.0 and 1.0.
/// It indicates a related point in current image.
/// See `CroppingImageProcessor.init(size:anchor:)` for more.
public let anchor: CGPoint
/// Creates a `CroppingImageProcessor`.
///
/// - Parameters:
/// - size: Target size of output image should be.
/// - anchor: The anchor point from which the size should be calculated.
/// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
/// - Note:
/// The anchor point is consisted by two values between 0.0 and 1.0.
/// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
/// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
/// The `size` property of `CroppingImageProcessor` will be used along with
/// `anchor` to calculate a target rectangle in the size of image.
///
/// The target size will be automatically calculated with a reasonable behavior.
/// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
/// and a target size of `CGSize(width: 20, height: 20)`:
/// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
/// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
/// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
self.size = size
self.anchor = anchor
self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.crop(to: size, anchorOn: anchor)
case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options)
}
}
}
/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor
/// does not render the images to resize. Instead, it downsamples the input data directly to an
/// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
/// as you can than the `ResizingImageProcessor`.
///
/// Only CG-based images are supported. Animated images (like GIF) is not supported.
public struct DownsamplingImageProcessor: ImageProcessor {
/// Target size of output image should be. It should be smaller than the size of
/// input image. If it is larger, the result image will be the same size of input
/// data without downsampling.
public let size: CGSize
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Creates a `DownsamplingImageProcessor`.
///
/// - Parameter size: The target size of the downsample operation.
public init(size: CGSize) {
self.size = size
self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
guard let data = image.kf.data(format: .unknown) else {
return nil
}
return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
case .data(let data):
return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
}
}
}
infix operator |>: AdditionPrecedence
public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
return left.append(another: right)
}
extension KFCrossPlatformColor {
var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
#if os(macOS)
(usingColorSpace(.extendedSRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
#else
getRed(&r, green: &g, blue: &b, alpha: &a)
#endif
return (r, g, b, a)
}
var rgbaDescription: String {
let components = self.rgba
return String(format: "(%.2f,%.2f,%.2f,%.2f)", components.r, components.g, components.b, components.a)
}
}
|
c18932da09d3df3296d7cec423da2db9
| 40.990217 | 125 | 0.654345 | false | false | false | false |
IBM-MIL/BluePic
|
refs/heads/master
|
BluePic-iOS/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/Map.swift
|
apache-2.0
|
3
|
//
// Map.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-10-09.
// Copyright © 2015 hearst. All rights reserved.
//
import Foundation
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
var JSONDictionary: [String : AnyObject] = [:]
var currentValue: AnyObject?
var currentKey: String?
var keyIsNested = false
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
public init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
return self[key, nested: true]
}
public subscript(key: String, nested nested: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
// check if a value exists for the current key
if nested == false {
currentValue = JSONDictionary[key]
} else {
// break down the components of the key that are separated by .
currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), collection: JSONDictionary)
}
return self
}
// MARK: Immutable Mapping
public func value<T>() -> T? {
return currentValue as? T
}
public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T {
return value() ?? defaultValue()
}
/// Returns current JSON value of type `T` if it is existing, or returns a
/// unusable proxy value for `T` and collects failed count.
public func valueOrFail<T>() -> T {
if let value: T = value() {
return value
} else {
// Collects failed count
failedCount++
// Returns dummy memory as a proxy for type `T`
let pointer = UnsafeMutablePointer<T>.alloc(0)
pointer.dealloc(0)
return pointer.memory
}
}
/// Returns whether the receiver is success or failure.
public var isValid: Bool {
return failedCount == 0
}
}
/// Fetch value from JSON dictionary, loop through them until we reach the desired object.
private func valueFor(keyPathComponents: ArraySlice<String>, collection: AnyObject?) -> AnyObject? {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return nil
}
//optional object to keep optional retreived from collection
var optionalObject: AnyObject?
//check if collection is dictionary or array (if it's array, also try to convert keypath to Int as index)
if let dictionary = collection as? [String : AnyObject],
let keyPath = keyPathComponents.first {
//keep retreved optional
optionalObject = dictionary[keyPath]
} else if let array = collection as? [AnyObject],
let keyPath = keyPathComponents.first,
index = Int(keyPath) {
//keep retreved optional
optionalObject = array[index]
}
if let object = optionalObject {
if object is NSNull {
return nil
} else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, collection: dict)
} else if let dict = object as? [AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, collection: dict)
} else {
return object
}
}
return nil
}
|
0cbcc5d4c4e33b4f9ad50c30985ea5da
| 27.162602 | 106 | 0.705458 | false | false | false | false |
Nibelungc/ios-ScrollBar
|
refs/heads/master
|
ios-ScrollBar/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ios-ScrollBar
//
// Created by Николай Кагала on 22/06/2017.
// Copyright © 2017 Николай Кагала. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, ScrollBarDataSource, UITableViewDelegate {
@IBOutlet private weak var tableView: UITableView!
private var scrollBar: ScrollBar!
private var items = [[String]]()
private let identifier = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
reload()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
tableView.sectionHeaderHeight = 20
scrollBar = ScrollBar(scrollView: tableView)
scrollBar.dataSource = self
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reloadAction))
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(shortListAction))
}
func reloadAction() {
reload()
}
func shortListAction() {
reload(max: 5)
}
func reload(min: Int = 0, max: Int = 10_000) {
let maxCount = min + Int(arc4random_uniform(UInt32(max - min + 1)))
items = [
(0...maxCount).map { "Cell \($0)" },
(0...maxCount).map { "Cell \($0)" },
(0...maxCount).map { "Cell \($0)" }
]
navigationItem.title = "\(maxCount) Cells"
tableView?.reloadData()
}
// MARK - ScrollBarDataSource
func textForHintView(_ hintView: UIView, at point: CGPoint, for scrollBar: ScrollBar) -> String? {
guard let indexPath = tableView.indexPathForRow(at: point) else { return nil }
let title = items[indexPath.section][indexPath.row]
return title
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
cell.textLabel?.text = items[indexPath.section][indexPath.row]
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = .groupTableViewBackground
return view
}
}
|
dde301382dd6c192f6b9e944c166b0ed
| 31.380952 | 137 | 0.637868 | false | false | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
Classes/Issues/Merge/GithubClient+Merge.swift
|
mit
|
1
|
//
// GithubClient+Merge.swift
// Freetime
//
// Created by Ryan Nystrom on 2/15/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import Squawk
import GitHubAPI
extension GithubClient {
func merge(
previous: IssueResult,
owner: String,
repo: String,
number: Int,
type: IssueMergeType,
completionHandler: @escaping (_ success: Bool) -> Void
) {
let newLabels = IssueLabelsModel(
status: IssueLabelStatusModel(
status: .merged,
pullRequest: previous.labels.status.pullRequest
),
locked: previous.labels.locked,
labels: previous.labels.labels
)
let newEvent = IssueStatusEventModel(
id: UUID().uuidString,
actor: userSession?.username ?? Constants.Strings.unknown,
commitHash: nil,
date: Date(),
status: .merged,
pullRequest: previous.pullRequest
)
let optimisticResult = previous.updated(
labels: newLabels,
timelinePages: previous.timelinePages(appending: [newEvent])
)
let mergeType: MergeType
switch type {
case .merge: mergeType = .merge
case .rebase: mergeType = .rebase
case .squash: mergeType = .squash
}
let cache = self.cache
client.send(V3MergePullRequestReqeust(owner: owner, repo: repo, number: number, type: mergeType)) { result in
switch result {
case .success:
cache.set(value: optimisticResult)
completionHandler(true)
case .failure(let err):
Squawk.show(error: err)
completionHandler(false)
}
}
}
}
|
22b1c56b04ca1fbdd7bbde538be777d3
| 27.123077 | 117 | 0.565646 | false | false | false | false |
gmission/gmission-ios
|
refs/heads/master
|
gmission/gmission/ImageHitVC.swift
|
mit
|
1
|
//
// CampaignList.swift
// gmission
//
// Created by CHEN Zhao on 4/12/2015.
// Copyright © 2015 CHEN Zhao. All rights reserved.
//
import UIKit
import SwiftyJSON
import WebImage
class ImageHitVM:HitVM{
}
class ImageAnswerCell:UITableViewCell{
@IBOutlet weak var answerImageView: UIImageView!
@IBOutlet weak var createdOnLabel: UILabel!
@IBOutlet weak var workerNameLabel: UILabel!
@IBOutlet weak var answerImageButton: UIButton!
weak var hitVC: HitVC!
internal var aspectConstraint : NSLayoutConstraint? {
didSet {
if oldValue != nil {
answerImageView.removeConstraint(oldValue!)
}
if aspectConstraint != nil {
answerImageView.addConstraint(aspectConstraint!)
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
aspectConstraint = nil
}
@IBAction func fullScreenImage(sender: AnyObject) {
let oldImage = (self.answerImageButton.imageView?.image)!
let image = UIImage(CGImage: (oldImage.CGImage)!, scale: 1.0, orientation: oldImage.imageOrientation)
hitVC.showFullImageView(image)
}
}
class ImageHitVC: HitVC, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// @IBOutlet weak var textView: UITextView!
@IBOutlet weak var imageView: UIImageView!
var imageVM:ImageHitVM {return vm as! ImageHitVM}
@IBOutlet weak var viewForWorker: UIView!
@IBOutlet weak var answerTableView: UITableView!
@IBOutlet weak var requesterBar: UIToolbar!
// @IBOutlet weak var hitStatusLabel: UILabel!
// @IBOutlet weak var hitCreatedOn: UILabel!
@IBOutlet weak var closeBtn: UIBarButtonItem!
let binder:TableBinder<Answer> = TableBinder<Answer>()
override func viewDidLoad() {
super.viewDidLoad()
// answerTableView.rowHeight = UITableViewAutomaticDimension
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
footerView.backgroundColor = UIColor.clearColor()
answerTableView.tableFooterView = footerView
self.binder.bind(answerTableView, items: self.vm.answers, refreshFunc: vm.loadAnswers)
self.binder.cellFunc = { indexPath in
let answer = self.vm.answers[indexPath.row]
let cell = self.answerTableView.dequeueReusableCellWithIdentifier("imageAnswerCell", forIndexPath: indexPath) as! ImageAnswerCell
Attachment.getOne(answer.att_id, done: { (att:Attachment) -> Void in
cell.answerImageButton.simpleSetImage(att.imageURL)
})
cell.workerNameLabel.text = ""
cell.createdOnLabel.text = NSDateToLocalTimeString(HKTimeStringToNSDate(answer.created_on))
cell.hitVC = self
return cell
}
self.showHUD("Loading...")
binder.refreshThen { () -> Void in
self.hideHUD()
self.requesterBar.hidden = !self.vm.isRequester
if self.vm.hit.status == "closed"{
self.closeBtn.enabled = false
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Closed"
self.navigationItem.rightBarButtonItem?.enabled = false
}else if self.vm.hasAnswered{
print("answered")
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Answered"
self.navigationItem.rightBarButtonItem?.enabled = false
}else{
print("has not answered")
if self.vm.isRequester{
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Requested"
self.navigationItem.rightBarButtonItem?.enabled = false
}else{
self.viewForWorker.hidden = false
self.answerTableView.hidden = true
self.navigationItem.rightBarButtonItem?.title = "Submit"
self.navigationItem.rightBarButtonItem?.enabled = true
}
}
}
}
override func viewDidLayoutSubviews() {
// self.textView.contentOffset = CGPointZero;
}
var imagePicker: UIImagePickerController!
@IBAction func takePhotoClicked(sender: AnyObject) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func choosePhotoClicked(sender: AnyObject) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imageView.image = image
imageView.contentMode = .ScaleAspectFit
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction override func closeHit(){
print("children close, image")
vm.hit.jsonDict["status"] = "closed"
Hit.postOne(vm.hit) { (hit:Hit) -> Void in
self.vm.hit = hit
self.navigationController?.popViewControllerAnimated(true)
}
}
override func submitAnswer(){
print("children submit answer, image")
if imageView.image == nil{
self.flashHUD("A photo is needed.", 1)
return
}
self.showHUD("Submitting ..")
let imageData = UIImageJPEGRepresentation(imageView.image!, 0.8)!
HTTP.uploadImage(imageData, fileName: "ios.jpg") { (nameFromServer, error) -> () in
if let e = error{
print("upload image error", e)
}else{
let attDict:[String:AnyObject] = ["type":"image", "value":nameFromServer!]
let att = Attachment(jsonDict: JSON(attDict))
Attachment.postOne(att) { (att:Attachment) -> Void in
print("attachment posted")
let answerDict:[String:AnyObject] = ["brief":"", "hit_id":self.vm.hit.id, "type":"image", "attachment_id":att.id,"worker_id":UserManager.currentUser.id]
self.vm.postAnswer(Answer(dict: answerDict)){
print("answer posted")
self.hideHUD()
self.flashHUD("Done!", 1)
self.viewDidLoad()
self.viewWillAppear(true)
}
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("segue of campaign")
if segue.identifier == "showHit"{
// let hitVC: HitVC = segue.destinationViewController as! HitVC
// hitVC.vm = HitVM(c: vm.hits[tableView.indexPathForSelectedRow!.row])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
8f9271059970a765c6cc014d3301dd60
| 36.129808 | 172 | 0.607665 | false | false | false | false |
dobleuber/my-swift-exercises
|
refs/heads/master
|
Project3/Project1/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Project1
//
// Created by Wbert Castro on 27/05/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var pictures = [String]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Storm Viewer"
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if item.hasPrefix("nssl") {
pictures.append(item)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
cell.textLabel?.text = pictures[indexPath.row]
return cell;
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = pictures[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
}
|
26e2a43d3bf1841b50d36188377be049
| 28.773585 | 110 | 0.636882 | false | false | false | false |
TQtianqian/TQDYZB_swift
|
refs/heads/master
|
TQDouYuZB/TQDouYuZB/Classes/Main/View/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// TQDouYuZB
//
// Created by worry on 2017/2/15.
// Copyright © 2017年 worry. All rights reserved.
//
import UIKit
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//mark:--定义属性
var childVC : [UIViewController]
weak var parentVC : UIViewController?
//mark:--懒加载属性
lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2.创建UICollectionView
let collectionView = UICollectionView(frame: (self?.bounds)!, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:ContentCellID)
return collectionView
}()
//mark:--自定义构造函数
init(frame: CGRect,childVC:[UIViewController],parentViewController:UIViewController?) {
self.childVC = childVC
self.parentVC = parentViewController
super.init(frame: frame)
//设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//mark:--设置UI界面
extension PageContentView{
func setupUI(){
//1.将所有子控制器添加到父控制器中
for childViewContrl in childVC{
parentVC? .addChildViewController(childViewContrl)
}
//2.添加UICollectionView,用于在cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
//mark:--遵守UICollectionDataSource
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVC.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
//2.给cell设置内容
for view in cell.contentView.subviews{
view .removeFromSuperview()
}
let childViewCtrl = childVC[indexPath.item]
childViewCtrl.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childViewCtrl.view)
return cell
}
}
//mark:--对外暴露的方法
extension PageContentView{
func setCurrentIndex(currentIndex :Int) {
let offSetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offSetX,y:0), animated: false)
}
}
|
c8911c87fefad8f09763715c0326c82f
| 23.829268 | 122 | 0.647348 | false | false | false | false |
wilzh40/ShirPrize-Me
|
refs/heads/master
|
SwiftSkeleton/YYSkinkitView.swift
|
mit
|
1
|
import UIKit
import QuartzCore
enum YYSpinKitViewStyle {
case Plane
case Bounce
case Wave
case WanderingCubes
case Pulse
}
let kYYSpinKitDegToRad:CGFloat = 0.0174532925
class YYSpinkitView: UIView {
var _color:UIColor?
var color:UIColor?{
set{
self._color = newValue
// for l:AnyObject in self.layer.sublayers {
// var layer = l as CALayer
// layer.backgroundColor = self._color!.CGColor
// }
}
get{
return self._color
}
}
var hidesWhenStopped:Bool?
var style:YYSpinKitViewStyle?
var stopped:Bool?
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
init(style:YYSpinKitViewStyle){
super.init(frame: CGRectZero)
}
func spinKit3DRotationWithPerspective(#perspective:Float,angle:CDouble,x:Float,y:Float,z:Float)->CATransform3D{
var transform:CATransform3D = CATransform3DIdentity
transform.m34 = CGFloat(perspective)
return CATransform3DRotate(transform, CGFloat(angle), CGFloat(x), CGFloat(y), CGFloat(z))
}
init(style:YYSpinKitViewStyle,color:UIColor){
super.init(frame: CGRectZero)
self.style = style
self.color = color
self.sizeToFit()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
if self.style == YYSpinKitViewStyle.Plane {
var plane = CALayer()
plane.frame = CGRectInset(self.bounds, 2.0, 2.0)
plane.backgroundColor = color.CGColor
plane.anchorPoint = CGPointMake(0.5, 0.5)
plane.anchorPointZ = 0.5
self.layer.addSublayer(plane)
var anim = CAKeyframeAnimation(keyPath:"transform")
anim.removedOnCompletion = false
anim.repeatCount = Float.infinity
anim.duration = 1.2
anim.keyTimes = [0.0, 0.5, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
];
anim.values = [
NSValue(CATransform3D: spinKit3DRotationWithPerspective(perspective:1.0/120.0, angle:0, x:0, y:0, z:0)),
NSValue(CATransform3D: spinKit3DRotationWithPerspective(perspective:1.0/120.0,angle:M_PI,x: 0.0, y:1.0,z:0.0)),
NSValue(CATransform3D: spinKit3DRotationWithPerspective(perspective:1.0/120.0, angle:M_PI, x:0.0, y:0.0,z:1.0))]
plane.addAnimation(anim,forKey:"spinkit-anim")
}
else if self.style == YYSpinKitViewStyle.Bounce {
var beginTime = CACurrentMediaTime()
for var i:Int = 0; i < 2; i+=1 {
var circle = CALayer()
circle.frame = CGRectInset(self.bounds, 2.0, 2.0)
circle.backgroundColor = color.CGColor
circle.anchorPoint = CGPointMake(0.5, 0.5)
circle.opacity = 0.6
circle.cornerRadius = CGRectGetHeight(circle.bounds) * 0.5
circle.transform = CATransform3DMakeScale(0.0, 0.0, 0.0)
self.layer.addSublayer(circle)
var anim = CAKeyframeAnimation(keyPath:"transform")
anim.removedOnCompletion = false
anim.repeatCount = Float.infinity
anim.duration = 2.0
anim.beginTime = beginTime - CFTimeInterval(1.0 * Float(i))
anim.keyTimes = [0.0, 0.5, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
];
anim.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 0.0)),
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 0.0)),
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 0.0))]
circle.addAnimation(anim,forKey:"spinkit-anim")
}
}
else if style == YYSpinKitViewStyle.Wave {
var beginTime = CACurrentMediaTime() + 1.2
var barWidth = CGRectGetWidth(self.bounds) / 5.0
for var i=0; i < 5; i+=1 {
var layer = CALayer()
layer.backgroundColor = color.CGColor
layer.frame = CGRectMake(barWidth * CGFloat(i), 0.0, barWidth - 3.0, CGRectGetHeight(self.bounds));
layer.transform = CATransform3DMakeScale(1.0, 0.3, 0.0)
self.layer.addSublayer(layer)
var anim = CAKeyframeAnimation(keyPath:"transform")
anim.removedOnCompletion = false
anim.beginTime = beginTime - NSTimeInterval(1.2 - (0.1 * Float(i)))
anim.duration = 1.2
anim.repeatCount = Float.infinity
anim.keyTimes = [0.0, 0.2, 0.4, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
];
anim.values = [
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0)),
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 0.0)),
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0)),
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0))]
layer.addAnimation(anim,forKey:"spinkit-anim")
}
}
else if style == YYSpinKitViewStyle.WanderingCubes {
var beginTime = CACurrentMediaTime()
var cubeSize = floor(CDouble(CGRectGetWidth(self.bounds) / 3.0))
var widthMinusCubeSize = CGRectGetWidth(self.bounds) - CGFloat(cubeSize)
for var i=0; i<2; i+=1 {
var cube = CALayer()
cube.backgroundColor = color.CGColor
cube.frame = CGRectMake(0.0, 0.0, CGFloat(cubeSize), CGFloat(cubeSize))
cube.anchorPoint = CGPointMake(0.5, 0.5)
self.layer.addSublayer(cube)
var anim = CAKeyframeAnimation(keyPath:"transform")
anim.removedOnCompletion = false
anim.beginTime = beginTime - NSTimeInterval(Float(i) * 0.9);
anim.duration = 1.8
anim.repeatCount = Float.infinity
anim.keyTimes = [0.0,0.25,0.50,0.75,1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
];
var t0 = CATransform3DIdentity
var t1 = CATransform3DMakeTranslation(widthMinusCubeSize, 0.0, 0.0)
t1 = CATransform3DRotate(t1, -90.0 * kYYSpinKitDegToRad, 0.0, 0.0, 1.0)
t1 = CATransform3DScale(t1, 0.5, 0.5, 1.0)
var t2 = CATransform3DMakeTranslation(widthMinusCubeSize, widthMinusCubeSize, 0.0)
t2 = CATransform3DRotate(t2, -180.0 * kYYSpinKitDegToRad, 0.0, 0.0, 1.0)
t2 = CATransform3DScale(t2, 1.0, 1.0, 1.0)
var t3 = CATransform3DMakeTranslation(0.0, widthMinusCubeSize, 0.0)
t3 = CATransform3DRotate(t3, -270.0 * kYYSpinKitDegToRad, 0.0, 0.0, 1.0)
t3 = CATransform3DScale(t3, 0.5, 0.5, 1.0)
var t4 = CATransform3DMakeTranslation(0.0, 0.0, 0.0)
t4 = CATransform3DRotate(t4, -360.0 * kYYSpinKitDegToRad, 0.0, 0.0, 1.0)
t4 = CATransform3DScale(t4, 1.0, 1.0, 1.0)
anim.values = [NSValue(CATransform3D:t0),
NSValue(CATransform3D:t1),
NSValue(CATransform3D:t2),
NSValue(CATransform3D:t3),
NSValue(CATransform3D:t4)]
cube.addAnimation(anim,forKey:"spinkit-anim")
}
}
else if style == YYSpinKitViewStyle.Pulse {
var beginTime = CACurrentMediaTime()
var circle = CALayer()
circle.frame = CGRectInset(self.bounds, 2.0, 2.0)
circle.backgroundColor = color.CGColor
circle.anchorPoint = CGPointMake(0.5, 0.5)
circle.opacity = 1.0
circle.cornerRadius = CGRectGetHeight(circle.bounds) * 0.5
circle.transform = CATransform3DMakeScale(0.0, 0.0, 0.0)
self.layer.addSublayer(circle)
var scaleAnim = CAKeyframeAnimation(keyPath:"transform")
scaleAnim.values = [
NSValue(CATransform3D:CATransform3DMakeScale(0.0, 0.0, 0.0)),
NSValue(CATransform3D:CATransform3DMakeScale(1.0, 1.0, 0.0))
]
var opacityAnim = CAKeyframeAnimation(keyPath:"opacity")
opacityAnim.values = [1.0,0.0]
var animGroup = CAAnimationGroup()
animGroup.removedOnCompletion = false
animGroup.beginTime = beginTime
animGroup.repeatCount = Float.infinity
animGroup.duration = 1.0
animGroup.animations = [scaleAnim, opacityAnim]
animGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circle.addAnimation(animGroup,forKey:"spinkit-anim")
}
}
func applicationWillEnterForeground(){
if self.stopped!{
self.pauseLayers()
}else{
self.resumeLayers()
}
}
func applicationDidEnterBackground(){
self.pauseLayers()
}
func startAnimating(){
self.hidden = false
self.stopped = false
self.resumeLayers()
}
func stopAnimating(){
if self.hidesWhenStopped == true {
self.hidden = true
}
self.stopped = true
self.pauseLayers()
}
func pauseLayers(){
var pausedTime = self.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
self.layer.speed = 0.0
self.layer.timeOffset = pausedTime
}
func resumeLayers(){
var pausedTime = self.layer.timeOffset
self.layer.speed = 1.0
self.layer.timeOffset = 0.0
self.layer.beginTime = 0.0
var timeSincePause = self.layer.convertTime(CACurrentMediaTime(),fromLayer:nil) - pausedTime
self.layer.beginTime = timeSincePause
}
override func sizeThatFits(size: CGSize) -> CGSize {
return CGSizeMake(37.0, 37.0)
}
}
|
c16bf09360781bcc993c5471aa98e63d
| 40.125828 | 171 | 0.560709 | false | false | false | false |
clonezer/FreeForm
|
refs/heads/master
|
FreeForm/Classes/FreeForm.swift
|
mit
|
1
|
//
// FreeForm.swift
// FreeForm
//
// Created by Peerasak Unsakon on 11/27/16.
// Copyright © 2016 Peerasak Unsakon. All rights reserved.
//
import UIKit
public typealias FreeFormReloadBlock = (_ reloadData: Bool) -> Void
public typealias FreeFormTitleViewBlock = (_ titleView: FreeFormSectionTitleView) -> Void
public typealias FreeFormRowBlock = (_ row: FreeFormRow) -> Void
public typealias FreeFormCellBlock = (_ cell: FreeFormCell) -> Void
public typealias FreeFormValueRowBlock = (_ value: AnyObject, _ row: FreeFormRow) -> Void
open class FreeForm: NSObject {
public var sections = FreeFormSections(array: [])
public var title: String = ""
public var reloadData: FreeFormReloadBlock?
public var validated: Bool {
return self.sections.validated
}
public var numOfSections: Int {
return self.sections.getShowingSection().count
}
public var noValueRows: FreeFormRows {
var blankValueRowArray = [FreeFormRow]()
self.sections.array.forEach { section in
blankValueRowArray = blankValueRowArray + section.rows.blankValueRows.array
}
return FreeFormRows(array: blankValueRowArray)
}
open func numOfRows(_ section: Int) -> Int {
return self.sections.getShowingSection()[section].rows.numOfRows
}
open func addSection(_ section: FreeFormSection) {
self.sections.appendSection(section)
}
open func getRow(_ indexPath: IndexPath) -> FreeFormRow {
return self.sections.getShowingSection()[indexPath.section].rows.getShowingRow()[indexPath.row]
}
open func getRowNibNames() -> [String] {
var nibNames = [String]()
for section in self.sections.array {
for row in section.rows.array {
nibNames.append(row.cellType)
}
}
let set = NSSet(array: nibNames)
return set.allObjects as! [String]
}
open func hideSection(_ section: FreeFormSection) {
section.hidden = true
self.reloadForm(true)
}
open func showSection(_ section: FreeFormSection) {
section.hidden = false
self.reloadForm(true)
}
open func hideRow(_ row: FreeFormRow) {
row.hidden = true
self.reloadForm(true)
}
open func showRow(_ row: FreeFormRow) {
row.hidden = false
self.reloadForm(true)
}
open func setHeight(_ row: FreeFormRow, height: CGFloat) {
row.height = height
self.reloadForm(true)
}
open func reloadForm(_ reloadTableView: Bool) {
guard let block = self.reloadData else { return }
block(reloadTableView)
}
open func validateTextField() {
for section in self.sections.getShowingSection() {
for row in section.rows.getShowingRow() {
guard let textFieldRow = row as? FreeFormTextFieldRow else { continue }
guard let cell = textFieldRow.cell as? FreeFormTextFieldCell else { continue }
cell.validateTextField()
}
}
}
public func clearForm() {
self.sections.removeAll()
}
}
open class FreeFormRow: NSObject {
public var cellType: String = ""
public var tag: String = ""
public var title: String = ""
public var value: AnyObject?
public var hidden: Bool = false
public var disable: Bool = false
public var deletable: Bool = false
public var validated: Bool = true
public var isOptional: Bool = false
public var height: CGFloat = 55
public var tintColor: UIColor = UIColor.blue
public var titleColor: UIColor = UIColor.black
public var customCell: FreeFormCellBlock?
public var didTapped: FreeFormRowBlock?
public var didChanged: FreeFormValueRowBlock?
public var didDeleted: FreeFormRowBlock?
public var cell: FreeFormCell?
public var formViewController: FreeFormViewController!
public var isNoValue: Bool {
if let stringValue = self.value as? String {
return (stringValue.isEmpty || stringValue == "")
}
return (self.value == nil)
}
public init(tag: String, title: String, value: AnyObject?) {
self.tag = tag
self.title = title
self.value = value
}
}
open class FreeFormRows: NSObject {
fileprivate var array: [FreeFormRow] = [FreeFormRow]()
public subscript(index: Int) -> FreeFormRow {
return array[index]
}
public var numOfRows: Int {
return self.getShowingRow().count
}
public var validated: Bool {
for row in self.array {
if row.validated == false {
return false
}
}
return true
}
public var blankValueRows: FreeFormRows {
let blankRows = FreeFormRows(array: [])
self.array.forEach { row in
if row.isNoValue {
blankRows.appendRows(row)
}
}
return blankRows
}
public init(array: [FreeFormRow]) {
self.array = array
}
open func getShowingRow() -> [FreeFormRow] {
let array = self.array.filter { row in
return row.hidden == false
}
return array
}
open func appendRows(_ row: FreeFormRow) {
self.array.append(row)
}
public func removeAll() {
self.array.removeAll()
}
}
open class FreeFormSection: NSObject {
public var tag: String = ""
public var title: String = ""
public var footerTitle: String = ""
public var headerView: FreeFormSectionTitleView?
public var headerHeight: CGFloat = 50
public var hidden: Bool = false
public var rows = FreeFormRows(array: [])
public var customHeader: FreeFormTitleViewBlock?
public var validated: Bool {
return self.rows.validated
}
public init(tag: String, title: String) {
self.tag = tag
self.title = title
}
open func addRow(_ row: FreeFormRow) {
self.rows.appendRows(row)
}
public func removeAllRows() {
self.rows.removeAll()
}
}
open class FreeFormSections: NSObject {
fileprivate var array: [FreeFormSection] = [FreeFormSection]()
public var validated: Bool {
for section in self.array {
if section.validated == false {
return false
}
}
return true
}
subscript(index: Int) -> FreeFormSection {
return array[index]
}
public init(array: [FreeFormSection]) {
self.array = array
}
open func appendSection(_ section: FreeFormSection) {
self.array.append(section)
}
open func getShowingSection() -> [FreeFormSection] {
let array = self.array.filter { section in
return section.hidden == false
}
return array
}
public func removeAll() {
for section in self.array {
section.removeAllRows()
}
self.array.removeAll()
}
}
|
216073c6150a88f0f3f2624ea906a774
| 25.621324 | 103 | 0.59895 | false | false | false | false |
suzp1984/IOS-ApiDemo
|
refs/heads/master
|
ApiDemo-Swift/ApiDemo-Swift/NoThreadMandelbrotViewController.swift
|
apache-2.0
|
1
|
//
// NoThreadMandelbrotViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 8/3/16.
// Copyright © 2016 [email protected]. All rights reserved.
//
import UIKit
class NoThreadMandelbrotViewController: UIViewController {
var mandelbrot : MandelbrotView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let mandelbrot = MandelbrotView()
mandelbrot.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(mandelbrot)
NSLayoutConstraint.activate([
mandelbrot.widthAnchor.constraint(equalToConstant: 350),
mandelbrot.heightAnchor.constraint(equalToConstant: 250),
mandelbrot.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 20),
mandelbrot.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
])
mandelbrot.backgroundColor = UIColor.red
self.mandelbrot = mandelbrot
let button = UIButton(type: .system)
button.setTitle("draw puppy", for: UIControlState())
button.addTarget(self, action: #selector(NoThreadMandelbrotViewController.doDraw(_:)), for: .touchUpInside)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.topAnchor.constraint(equalTo: mandelbrot.bottomAnchor, constant: 20),
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func doDraw(_ sender: UIButton) {
if let mandelbrot = self.mandelbrot {
mandelbrot.drawThatPuppy()
}
}
}
|
45c97cb3234ec0db016b1f01dc98d080
| 34.37037 | 115 | 0.664398 | false | false | false | false |
SwiftOnTheServer/DrinkChooser
|
refs/heads/master
|
lib/Redis/RedisMulti.swift
|
mit
|
1
|
/**
* Copyright IBM Corporation 2016
*
* 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
/// The `RedisMulti` class is a handle for issueing "transactions" against a Redis
/// server. Instances of the `RedisMulti` class are created using the `Redis.multi`
/// function. These transactions are built using the various command related functions
/// of the `RedisMulti` class. Once a "transaction" is built, it is sent to the Redis
/// server and run using the `RedisMulti.exec` function.
public class RedisMulti {
let redis: Redis
var queuedCommands = [[RedisString]]()
init(redis: Redis) {
self.redis = redis
}
// ****************************************************************
// The commands to be queued are all in extensions of RedisMulti *
// ****************************************************************
/// Send the transaction to the server and run it.
///
/// - Parameter callback: a function returning the response in the form of a `RedisResponse`
public func exec(_ callback: @escaping (RedisResponse) -> Void) {
redis.issueCommand("MULTI") {(multiResponse: RedisResponse) in
switch(multiResponse) {
case .Status(let status):
if status == "OK" {
var idx = -1
var handler: ((RedisResponse) -> Void)? = nil
let actualHandler = {(response: RedisResponse) in
switch(response) {
case .Status(let status):
if status == "QUEUED" {
idx += 1
if idx < self.queuedCommands.count {
// Queue another command to Redis
self.redis.issueCommandInArray(self.queuedCommands[idx], callback: handler!)
} else {
self.redis.issueCommand("EXEC", callback: callback)
}
} else {
self.execQueueingFailed(response, callback: callback)
}
default:
self.execQueueingFailed(response, callback: callback)
}
}
handler = actualHandler
actualHandler(RedisResponse.Status("QUEUED"))
} else {
callback(multiResponse)
}
default:
callback(multiResponse)
}
}
}
private func execQueueingFailed(_ response: RedisResponse, callback: (RedisResponse) -> Void) {
redis.issueCommand("DISCARD") {(_: RedisResponse) in
callback(response)
}
}
}
|
02d2e52898fb971f42aaa0b605acd521
| 41.831325 | 120 | 0.502672 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/Generics/connected_components_concrete.swift
|
apache-2.0
|
6
|
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
protocol Base {
associatedtype A
associatedtype B
associatedtype C
associatedtype D : P where B == D.T
}
// CHECK-LABEL: connected_components_concrete.(file).Derived1@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived1 : Base where A == B, A == C, A == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived2@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived2 : Base where A == D.T, A == C, B == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived3@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived3 : Base where A == B, B == C, A == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived4@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived4 : Base where A == Int, B == Int, C == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived5@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived5 : Base where A == Int, D.T == Int, C == Int {}
|
913b7fc613e32558b68eb42bfead96c8
| 45.96875 | 126 | 0.669328 | false | false | false | false |
portah/dangerous-room
|
refs/heads/master
|
dangerous-room/Meteor/MeteorCoreDataStack.swift
|
apache-2.0
|
1
|
// Copyright (c) 2015 Peter Siegesmund <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreData
import SwiftyBeaver
public protocol MeteorCoreDataStack {
var mainContext: NSManagedObjectContext { get }
var backgroundContext: NSManagedObjectContext { get }
var managedObjectContext:NSManagedObjectContext { get }
}
class MeteorCoreDataStackPersisted:NSObject, MeteorCoreDataStack {
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(MeteorCoreDataStackPersisted.mergeCoreDataChanges),
name: NSNotification.Name.NSManagedObjectContextDidSave, object: backgroundContext)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "MeteorCoreData", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
try! coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
return coordinator
}
var managedObjectContext:NSManagedObjectContext {
if (OperationQueue.current == OperationQueue.main) {
return self.mainContext
}
return backgroundContext
}
lazy var mainContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
context.stalenessInterval = 0
return context
}()
lazy var backgroundContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
context.stalenessInterval = 0
return context
}()
@objc func mergeCoreDataChanges(notification: NSNotification) {
let context = notification.object as! NSManagedObjectContext
if context === mainContext {
log.debug("Merging changes mainQueue > privateQueue")
backgroundContext.perform() {
self.backgroundContext.mergeChanges(fromContextDidSave: notification as Notification)
}
} else if context === backgroundContext {
log.debug("Merging changes privateQueue > mainQueue")
mainContext.perform() {
self.mainContext.mergeChanges(fromContextDidSave: notification as Notification)
}
} else {
log.debug("Merging changes mainQueue <> privateQueue")
backgroundContext.perform() {
self.backgroundContext.mergeChanges(fromContextDidSave: notification as Notification)
}
mainContext.perform() {
self.mainContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
}
}
|
1707b008b0d05a21d81fdab5a8fde675
| 42.946429 | 170 | 0.699919 | false | false | false | false |
jalehman/twitter-clone
|
refs/heads/master
|
TwitterClient/AppDelegate.swift
|
gpl-2.0
|
1
|
//
// AppDelegate.swift
// TwitterClient
//
// Created by Josh Lehman on 2/19/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController!
var viewModel: AuthViewModel!
var viewModelServices: ViewModelServices!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
navigationController = UINavigationController()
viewModelServices = ViewModelServices(navigationController: navigationController)
viewModel = AuthViewModel(services: viewModelServices)
let viewController = AuthViewController(viewModel: viewModel)
navigationController.pushViewController(viewController, animated: false)
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.makeKeyAndVisible()
window!.rootViewController = navigationController
UINavigationBar.appearance().barTintColor = UIColor(red: 0.361, green: 0.686, blue: 0.925, alpha: 1)
let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
UINavigationBar.appearance().titleTextAttributes = titleTextAttributes
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UIBarButtonItem.appearance().tintColor = UIColor.whiteColor()
UIBarButtonItem.appearance().setTitleTextAttributes(titleTextAttributes, forState: UIControlState.Normal)
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
viewModelServices.twitterService.executeOpenURL.execute(url)
return true
}
}
|
e89077270046fc922e3798b375dd33a5
| 47.012987 | 285 | 0.731945 | false | false | false | false |
iWeslie/Ant
|
refs/heads/master
|
Ant/Ant/LunTan/Detials/Tools/CustomStyle-Extension.swift
|
apache-2.0
|
2
|
//
// Extension.swift
// DetialsOfAntDemo
//
// Created by Weslie on 2017/7/18.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
extension UIView {
func changeBorderLineStyle(target: UIView, borderColor: UIColor) {
target.layer.borderColor = borderColor.cgColor
target.layer.cornerRadius = 2
target.layer.borderWidth = 1
target.layer.masksToBounds = true
}
}
extension UIButton {
func addSingleUnderline(color: UIColor) {
let text = titleLabel?.text ?? ""
let attrs = [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: color] as [String : Any]
setAttributedTitle(NSAttributedString(string: text, attributes: attrs), for: .normal)
}
}
extension UILabel {
//获取高度
func getLabHeight(labelStr: String, font: UIFont, width: CGFloat) -> CGFloat {
let statusLabelText = labelStr
let size = CGSize(width: width, height: 900)
let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context: nil).size
return strSize.height
}
}
extension UILabel {
func setTitleWithSpace(_ input: String) {
text = " " + input + " "
}
func setPrice(_ input: String) {
text = "$" + input
}
}
|
68f01c6188a222da2ba4e8a3b907c5e6
| 28.836735 | 157 | 0.665527 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/SILOptimizer/access_enforcement_noescape_error.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s
// REQUIRES: asserts
// This is the subset of tests from access_enforcement_noescape.swift
// that cause compile-time errors. All the tests are organized in one
// place so it's easy to see that coverage of all the combinations of
// access patterns is exhaustive. But the ones that cause compile time
// errors are commented out in the original file and compiled here
// instead with the '-verify' option.
// Helper
func doOne(_ f: () -> ()) {
f()
}
// Helper
func doOneInout(_: ()->(), _: inout Int) {}
// Error: noescape read + write inout.
func readWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ _ = x }, &x)
}
// Error: noescape read + write inout of an inout.
func inoutReadWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ _ = x }, &x)
}
// Error: on noescape write + write inout.
func writeWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ x = 42 }, &x)
}
// Error: on noescape write + write inout.
func inoutWriteWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ x = 42 }, &x)
}
// Helper
func doBlockInout(_: @convention(block) ()->(), _: inout Int) {}
func readBlockWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [read] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doBlockInout({ _ = x }, &x)
}
// Test AccessSummaryAnalysis.
//
// The captured @inout_aliasable argument to `doOne` is re-partially applied,
// then stored is a box before passing it to doBlockInout.
func noEscapeBlock() {
var x = 3
doOne {
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doBlockInout({ _ = x }, &x)
}
}
|
56a598c443feaaf5be8bd0ed78d3cf5f
| 38.82716 | 163 | 0.698388 | false | false | false | false |
frankcjw/CJWUtilsS
|
refs/heads/master
|
CJWUtilsS/QPLib/UI/QPHUDUtils.swift
|
mit
|
1
|
//
// QPHUDUtils.swift
// CJWUtilsS
//
// Created by Frank on 1/18/16.
// Copyright © 2016 cen. All rights reserved.
//
import UIKit
import SVProgressHUD
import MBProgressHUD
class QPHUDUtils: NSObject {
var mbHUD: MBProgressHUD?
class var sharedInstance: QPHUDUtils {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: QPHUDUtils? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = QPHUDUtils()
}
return Static.instance!
}
}
// MARK: - 继续SVProgressHUD
//TODO: 还没完善SVProgressHUD
extension NSObject {
// func showHUD(text: String) {
// SVProgressHUD.setBackgroundColor(COLOR_BLACK)
// SVProgressHUD.setForegroundColor(COLOR_WHITE)
// SVProgressHUD.setRingThickness(8)
// SVProgressHUD.showWithStatus(text)
// }
//
// func hideHUD() {
// SVProgressHUD.dismiss()
// }
//
// func showLoading(view: UIView, text: String) {
// MBProgressHUD.showHUDAddedTo(view, animated: true)
// }
}
// MARK: - 显示hud
public extension UIView {
private func cleanHud() {
if let hud = QPHUDUtils.sharedInstance.mbHUD {
hud.hide(true)
}
}
/**
显示HUD(不自动消失)
- parameter text: 需要显示的文字
*/
public func showLoading(text: String) {
var view = self
if view is UITableView {
if let sv = view.superview {
view = sv
}
}
cleanHud()
self.userInteractionEnabled = false
let hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
// if hud != nil { }
hud.labelText = text
hud.mode = .Indeterminate
QPHUDUtils.sharedInstance.mbHUD = hud
}
/**
隐藏HUD
*/
public func hideLoading() {
var view = self
if view is UITableView {
if let sv = view.superview {
view = sv
}
}
cleanHud()
self.userInteractionEnabled = true
MBProgressHUD.hideAllHUDsForView(view, animated: true)
}
/**
老方法,和以前的项目对接
隐藏hud
调用hideLoading
*/
public func hideAllHUD() {
hideLoading()
}
/**
老方法,和以前的项目对接
显示hud
调用showLoading
- parameter text: 需要显示的内容
*/
public func showHUDwith(text: String) {
showLoading(text)
}
/**
老方法,和以前的项目对接
短暂出现hud
- parameter text: 需要显示的内容
*/
public func showTemporary(text: String) {
showHUDTemporary(text)
}
/**
显示hud.默认1.5s后消失
- parameter text: 显示的文字
- parameter duration: 显示时常.默认1.5
*/
public func showHUDTemporary(text: String, duration: NSTimeInterval = 1.5) {
cleanHud()
let view = self
self.userInteractionEnabled = false
let hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
// if hud != nil { }
hud.labelText = text
hud.mode = .Text
QPHUDUtils.sharedInstance.mbHUD = hud
excute(duration) { () -> () in
view.hideAllHUD()
}
}
}
|
90774c4f5e3adf3252d9ed83b035a752
| 17.412587 | 77 | 0.676672 | false | false | false | false |
AndrewBennet/readinglist
|
refs/heads/master
|
ReadingList/ViewControllers/Settings/Appearance.swift
|
gpl-3.0
|
1
|
import Foundation
import SwiftUI
class AppearanceSettings: ObservableObject {
@Published var showExpandedDescription: Bool = GeneralSettings.showExpandedDescription {
didSet {
GeneralSettings.showExpandedDescription = showExpandedDescription
}
}
@Published var showAmazonLinks: Bool = GeneralSettings.showAmazonLinks {
didSet {
GeneralSettings.showAmazonLinks = showAmazonLinks
}
}
@Published var darkModeOverride: Bool? = GeneralSettings.darkModeOverride {
didSet {
GeneralSettings.darkModeOverride = darkModeOverride
}
}
}
struct Appearance: View {
@EnvironmentObject var hostingSplitView: HostingSettingsSplitView
@ObservedObject var settings = AppearanceSettings()
var inset: Bool {
hostingSplitView.isSplit
}
func updateWindowInterfaceStyle() {
if let darkModeOverride = settings.darkModeOverride {
AppDelegate.shared.window?.overrideUserInterfaceStyle = darkModeOverride ? .dark : .light
} else {
AppDelegate.shared.window?.overrideUserInterfaceStyle = .unspecified
}
}
var darkModeSystemSettingToggle: Binding<Bool> {
Binding(
get: { settings.darkModeOverride == nil },
set: {
settings.darkModeOverride = $0 ? nil : false
updateWindowInterfaceStyle()
}
)
}
var body: some View {
SwiftUI.List {
Section(
header: HeaderText("Dark Mode", inset: inset)
) {
Toggle(isOn: darkModeSystemSettingToggle) {
Text("Use System Setting")
}
if let darkModeOverride = settings.darkModeOverride {
CheckmarkCellRow("Light Appearance", checkmark: !darkModeOverride)
.onTapGesture {
settings.darkModeOverride = false
updateWindowInterfaceStyle()
}
CheckmarkCellRow("Dark Appearance", checkmark: darkModeOverride)
.onTapGesture {
settings.darkModeOverride = true
updateWindowInterfaceStyle()
}
}
}
Section(
header: HeaderText("Book Details", inset: inset),
footer: FooterText("Enable Expanded Descriptions to automatically show each book's full description.", inset: inset)
) {
Toggle(isOn: $settings.showAmazonLinks) {
Text("Show Amazon Links")
}
Toggle(isOn: $settings.showExpandedDescription) {
Text("Expanded Descriptions")
}
}
}.possiblyInsetGroupedListStyle(inset: inset)
}
}
struct CheckmarkCellRow: View {
let text: String
let checkmark: Bool
init(_ text: String, checkmark: Bool) {
self.text = text
self.checkmark = checkmark
}
var body: some View {
HStack {
Text(text)
Spacer()
if checkmark {
Image(systemName: "checkmark").foregroundColor(Color(.systemBlue))
}
}.contentShape(Rectangle())
}
}
struct Appearance_Previews: PreviewProvider {
static var previews: some View {
Appearance().environmentObject(HostingSettingsSplitView())
}
}
|
b2e3b64c88066c0e878fef78ac7e4fae
| 30.900901 | 132 | 0.567919 | false | false | false | false |
Rivukis/Parlance
|
refs/heads/master
|
Parlance/SignInModule/SignInViewController.swift
|
mit
|
1
|
//
// SignInViewController.swift
// Parlance
//
// Created by Brian Radebaugh on 1/24/17.
// Copyright © 2017 Brian Radebaugh. All rights reserved.
//
import UIKit
protocol SignInViewControllerDelegate: class {
func didSignIn()
}
class SignInViewController: UIViewController {
let parlance = SignInParlance()
weak var delegate: SignInViewControllerDelegate?
@IBOutlet weak var nameTextField: UITextField! {
didSet {
nameTextField.delegate = self
nameTextField.placeholder = parlance.t(.namePlaceholder)
}
}
@IBOutlet weak var passwordTextField: UITextField! {
didSet {
passwordTextField.delegate = self
passwordTextField.placeholder = parlance.t(.passwordPlaceholder)
}
}
@IBOutlet weak var signInButton: UIButton! {
didSet {
signInButton.layer.cornerRadius = 5
signInButton.setTitle(parlance.t(.signInButtonText), for: .normal)
}
}
@IBOutlet weak var cancelButton: UIButton! {
didSet {
cancelButton.layer.cornerRadius = 5
cancelButton.setTitle(parlance.t(.cancelButtonText), for: .normal)
}
}
// MARK: Lifecycle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
nameTextField.becomeFirstResponder()
}
// MARK: Actions
@IBAction func signInTapped(_ sender: Any) {
guard let name = nameTextField.text, let password = passwordTextField.text else {
return
}
if !name.isEmpty && password == "password" {
User.currentUser = User(name: name)
delegate?.didSignIn()
dismiss()
}
}
@IBAction func cancelTapped(_ sender: Any) {
dismiss()
}
// MARK: Helper
func dismiss() {
nameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
dismiss(animated: true)
}
}
extension SignInViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
passwordTextField.becomeFirstResponder()
} else if textField == passwordTextField {
signInTapped(self)
}
return false
}
}
|
930b0f0a266ef54529c889444458d58a
| 25.611111 | 89 | 0.607098 | false | false | false | false |
goaairlines/capetown-ios
|
refs/heads/master
|
capetown/Model/CurrencyConverter.swift
|
mit
|
1
|
//
// CurrencyConverter.swift
// capetown
//
// Created by Alex Berger on 3/12/16.
// Copyright © 2016 goa airlines. All rights reserved.
//
import Foundation
class CurrencyConverter {
func convert(fromAmount: Double, fromCurreny: Currency, toCurrency: Currency) -> Double {
var toAmount: Double = 0.0
if fromCurreny.id == Currencies.EUR && toCurrency.id == Currencies.VND {
toAmount = fromAmount * 22282.00
}
return toAmount
}
}
|
0057227a2b20297a1343bd702a482046
| 21.26087 | 93 | 0.617188 | false | false | false | false |
yume190/CustomView
|
refs/heads/master
|
CustomViewKit/ViewSources.swift
|
mit
|
2
|
//
// ViewSources.swift
// CustomViewTest
//
// Created by Yume on 2015/4/8.
// Copyright (c) 2015年 yume. All rights reserved.
//
import UIKit
@objc public protocol ViewSource:class{
func action(cv:CustomViewLight)
}
@objc public class ViewSources: NSObject {
public class var sharedInstance: ViewSources {
dispatch_once(&Inner.token) {
Inner.instance = ViewSources()
}
return Inner.instance!
}
struct Inner {
static var instance: ViewSources?
static var token: dispatch_once_t = 0
}
override public func valueForUndefinedKey(key: String) -> AnyObject? {
return nil
}
}
public var ViewSourcesInstance: ViewSources { get { return ViewSources.sharedInstance } }
@objc public class DummyViewSource:ViewSource{
public func action(cv:CustomViewLight){
}
}
@objc public class YumeViewSource<T>:DummyViewSource{
public typealias SettingClosure = ((T) -> ())
private var _settings: SettingClosure
public init(settings:SettingClosure){
_settings = settings
}
public override func action(cv:CustomViewLight){
if let _view = cv as? T {
_settings(_view)
}
}
}
|
08e08b954af9a743980ac218f9aae471
| 21.140351 | 89 | 0.630745 | false | false | false | false |
toggl/superday
|
refs/heads/develop
|
teferiTests/Mocks/SimpleMockTimeSlotService.swift
|
bsd-3-clause
|
1
|
import Foundation
import RxSwift
@testable import teferi
class SimpleMockTimeSlotService : TimeSlotService
{
var newTimeSlotToReturn: TimeSlot? = nil
var timeSlotsToReturn: [TimeSlot]? = nil
var durationToReturn: TimeInterval = 0
private(set) var dateAsked:Date? = nil
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: teferi.Category, categoryWasSetByUser: Bool, tryUsingLatestLocation: Bool) -> TimeSlot?
{
return newTimeSlotToReturn
}
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: teferi.Category, categoryWasSetByUser: Bool, location: Location?) -> TimeSlot?
{
return newTimeSlotToReturn
}
@discardableResult func addTimeSlot(fromTemporaryTimeslot: TemporaryTimeSlot) -> TimeSlot?
{
return newTimeSlotToReturn
}
func getTimeSlots(forDay day: Date) -> [TimeSlot]
{
dateAsked = day
return timeSlotsToReturn ?? []
}
func getTimeSlots(forDay day: Date, category: teferi.Category?) -> [TimeSlot]
{
dateAsked = day
return timeSlotsToReturn ?? []
}
func getTimeSlots(sinceDaysAgo days: Int) -> [TimeSlot]
{
return timeSlotsToReturn ?? []
}
func getTimeSlots(betweenDate firstDate: Date, andDate secondDate: Date) -> [TimeSlot]
{
return timeSlotsToReturn ?? []
}
func update(timeSlots: [TimeSlot], withCategory category: teferi.Category)
{
let updatedTimeSlots = timeSlots.map { $0.withCategory(category) }
}
func getLast() -> TimeSlot?
{
return timeSlotsToReturn?.last
}
func calculateDuration(ofTimeSlot timeSlot: TimeSlot) -> TimeInterval
{
return durationToReturn
}
}
|
e254ae0ea9817707f508b453463913de
| 27.28125 | 168 | 0.664088 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/PackageModel/Manifest/TargetBuildSettingDescription.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 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
//
//===----------------------------------------------------------------------===//
/// A namespace for target-specific build settings.
public enum TargetBuildSettingDescription {
/// The tool for which a build setting is declared.
public enum Tool: String, Codable, Equatable, CaseIterable {
case c
case cxx
case swift
case linker
}
/// The kind of the build setting, with associate configuration
public enum Kind: Codable, Equatable {
case headerSearchPath(String)
case define(String)
case linkedLibrary(String)
case linkedFramework(String)
case unsafeFlags([String])
}
/// An individual build setting.
public struct Setting: Codable, Equatable {
/// The tool associated with this setting.
public let tool: Tool
/// The kind of the setting.
public let kind: Kind
/// The condition at which the setting should be applied.
public let condition: PackageConditionDescription?
public init(
tool: Tool,
kind: Kind,
condition: PackageConditionDescription? = .none
) {
self.tool = tool
self.kind = kind
self.condition = condition
}
}
}
|
f6c5d493b235dc55b6635e6e183f1602
| 29.678571 | 80 | 0.577998 | false | false | false | false |
achimk/Cars
|
refs/heads/master
|
CarsApp/CarsAppTests/Repositories/Cars/CarCreateModelTests.swift
|
mit
|
1
|
//
// CarCreateModelTests.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import XCTest
import Nimble
@testable import CarsApp
final class CarCreateModelTests: XCTestCase {
func testModel() {
let car = CarCreateModel(
name: "Project Code 980",
model: "Carrera GT",
brand: "Porsche",
year: "2004"
)
expect(car.name).to(equal("Project Code 980"))
expect(car.model).to(equal("Carrera GT"))
expect(car.brand).to(equal("Porsche"))
expect(car.year).to(equal("2004"))
}
func testEquatable() {
let car = CarCreateModel(
name: "Project Code 980",
model: "Carrera GT",
brand: "Porsche",
year: "2004"
)
expect(car).to(equal(car))
let diffName = CarCreateModel(
name: "Project Code 98",
model: "Carrera GT",
brand: "Porsche",
year: "2004"
)
expect(car).toNot(equal(diffName))
let diffModel = CarCreateModel(
name: "Project Code 980",
model: "Carrera",
brand: "Porsche",
year: "2004"
)
expect(car).toNot(equal(diffModel))
let diffBrand = CarCreateModel(
name: "Project Code 980",
model: "Carrera GT",
brand: "Fiat",
year: "2004"
)
expect(car).toNot(equal(diffBrand))
let diffYear = CarCreateModel(
name: "Project Code 980",
model: "Carrera GT",
brand: "Porsche",
year: "2001"
)
expect(car).toNot(equal(diffYear))
}
}
|
d9ea8c274ae5cd3e878177b71e86c5d5
| 22.25 | 55 | 0.514431 | false | true | false | false |
danielsaidi/KeyboardKit
|
refs/heads/master
|
Tests/KeyboardKitTests/Mocks/MockKeyboardContext.swift
|
mit
|
1
|
//
// MockKeyboardContext.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-07-02.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
import KeyboardKit
import MockingKit
import UIKit
class MockKeyboardContext: KeyboardContext {
var device: UIDevice = .current
var deviceOrientation: UIInterfaceOrientation = .portrait
var emojiCategory: EmojiCategory = .frequent
var hasDictationKey = false
var hasFullAccess = false
var keyboardAppearance: UIKeyboardAppearance = .dark
var keyboardType: KeyboardType = .alphabetic(.lowercased)
var locale: Locale = .current
var needsInputModeSwitchKey = false
var primaryLanguage: String?
var textDocumentProxy: UITextDocumentProxy = MockTextDocumentProxy()
var textInputMode: UITextInputMode?
var traitCollection: UITraitCollection = .init()
}
|
585a625c0ea11b4fc149ee6fd89a312a
| 28.4 | 72 | 0.747166 | false | false | false | false |
joerocca/GitHawk
|
refs/heads/master
|
Classes/Utility/SearchQueryTokenizer.swift
|
mit
|
1
|
//
// SearchQueryTokenizer.swift
// Freetime
//
// Created by Weyert de Boer on 09/10/2017.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
struct SearchQueryParseResults {
let tokens: [Token]
let leftover: String
}
enum TokenAction: String {
case status = "is"
case user = "user"
}
typealias Token = (action: TokenAction, value: String)
/// Tokenizes a search query and returns an instance of ParseResult which consists
/// of all the found "search tokens" such as `is:closed` and separately returns
/// the text of the search query which isn't part of any search token
func tokenizeSearchQuery(_ query: String) -> SearchQueryParseResults {
let chunks = query.components(separatedBy: " ")
var leftover: String = query
let tokens: [Token] = chunks.flatMap { chunk -> Token? in
let chunk = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
let valueChunks = chunk.components(separatedBy: ":")
guard !valueChunks.isEmpty else { return nil }
if valueChunks.count == 2, let action = valueChunks.first, let tokenValue = valueChunks.last {
guard let tokenAction = TokenAction(rawValue: action.lowercased()) else { return nil }
leftover = leftover.replacingOccurrences(of: chunk, with: "")
return Token(tokenAction, tokenValue)
}
return nil
}
let trimmedLeftover = leftover.trimmingCharacters(in: .whitespacesAndNewlines)
return SearchQueryParseResults(tokens: tokens, leftover: trimmedLeftover)
}
func isIssueStatus(status: IssueStatus, text: String) -> Bool {
let text = text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
switch status {
case .open: return text == "open"
case .closed: return text == "closed"
case .merged: return text == "merged"
}
}
|
23bd639e546ad600863301928732dea3
| 33.660377 | 102 | 0.691345 | false | false | false | false |
cao903775389/MRCBaseLibrary
|
refs/heads/master
|
MRCBaseLibrary/Classes/MRCBaseViewModel/MRCBaseViewModel.swift
|
mit
|
1
|
//
// MRCBaseViewModel.swift
// Pods
//
// Created by 逢阳曹 on 2017/5/27.
//
//
import Foundation
import ReactiveSwift
//所有ViewModel的基类
open class MRCBaseViewModel: NSObject {
public required init(params: [String: Any]? = nil) {
param = params
title = MutableProperty((params?["title"] as? String) ?? "")
}
//导航栏标题
public var title: MutableProperty<String>
//界面将要消失
deinit {
print("\(self)已销毁")
}
//参数
private var param: [String: Any]?
}
public protocol MRCViewModel: class {
//导航栏标题
var title: MutableProperty<String> { set get }
//初始化方法
init(params: [String: Any]?)
}
extension MRCBaseViewModel: MRCViewModel { }
extension SignalProducer {
public static func pipe() -> (SignalProducer, ProducedSignal.Observer) {
let (signal, observer) = ProducedSignal.pipe()
let producer = SignalProducer(signal)
return (producer, observer)
}
}
|
efd9cd5602253f5822448bbdfa8514a7
| 18.918367 | 76 | 0.617828 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/Authentication/Interface/Descriptions/ScreenDescriptions/Registration/SetPasswordStepDescription.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireUtilities
final class SetPasswordStepDescription: DefaultValidatingStepDescription {
let backButton: BackButtonDescription?
let mainView: ViewDescriptor & ValueSubmission
let headline: String
let subtext: String?
let secondaryView: AuthenticationSecondaryViewDescription?
let initialValidation: ValueValidation
init() {
backButton = BackButtonDescription()
let textField = TextFieldDescription(placeholder: "password.placeholder".localized, actionDescription: "general.next".localized, kind: .password(isNew: true))
textField.useDeferredValidation = true
mainView = textField
headline = "team.password.headline".localized
subtext = nil
secondaryView = nil
initialValidation = .info(PasswordRuleSet.localizedErrorMessage)
}
}
|
153b2ee55cb7b245afe509444bcb1fc4
| 36.829268 | 166 | 0.742102 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/Basics/Observability.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Dispatch
import Foundation
import TSCBasic
import enum TSCUtility.Diagnostics
import protocol TSCUtility.DiagnosticDataConvertible
// this could become a struct when we remove the "errorsReported" pattern
// designed after https://github.com/apple/swift-log
// designed after https://github.com/apple/swift-metrics
// designed after https://github.com/apple/swift-distributed-tracing-baggage
public class ObservabilitySystem {
public let topScope: ObservabilityScope
/// Create an ObservabilitySystem with a handler provider providing handler such as a collector.
public init(_ handlerProvider: ObservabilityHandlerProvider) {
self.topScope = .init(
description: "top scope",
parent: .none,
metadata: .none,
diagnosticsHandler: handlerProvider.diagnosticsHandler
)
}
/// Create an ObservabilitySystem with a single diagnostics handler.
public convenience init(_ handler: @escaping (ObservabilityScope, Diagnostic) -> Void) {
self.init(SingleDiagnosticsHandler(handler))
}
private struct SingleDiagnosticsHandler: ObservabilityHandlerProvider, DiagnosticsHandler {
var diagnosticsHandler: DiagnosticsHandler { self }
let underlying: (ObservabilityScope, Diagnostic) -> Void
init(_ underlying: @escaping (ObservabilityScope, Diagnostic) -> Void) {
self.underlying = underlying
}
func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {
self.underlying(scope, diagnostic)
}
}
}
public protocol ObservabilityHandlerProvider {
var diagnosticsHandler: DiagnosticsHandler { get }
}
// MARK: - ObservabilityScope
public final class ObservabilityScope: DiagnosticsEmitterProtocol, CustomStringConvertible {
public let description: String
private let parent: ObservabilityScope?
private let metadata: ObservabilityMetadata?
private var diagnosticsHandler: DiagnosticsHandlerWrapper
fileprivate init(
description: String,
parent: ObservabilityScope?,
metadata: ObservabilityMetadata?,
diagnosticsHandler: DiagnosticsHandler
) {
self.description = description
self.parent = parent
self.metadata = metadata
self.diagnosticsHandler = DiagnosticsHandlerWrapper(diagnosticsHandler)
}
public func makeChildScope(description: String, metadata: ObservabilityMetadata? = .none) -> Self {
let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)
return .init(
description: description,
parent: self,
metadata: mergedMetadata,
diagnosticsHandler: self.diagnosticsHandler
)
}
public func makeChildScope(description: String, metadataProvider: () -> ObservabilityMetadata) -> Self {
self.makeChildScope(description: description, metadata: metadataProvider())
}
// diagnostics
public func makeDiagnosticsEmitter(metadata: ObservabilityMetadata? = .none) -> DiagnosticsEmitter {
let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)
return .init(scope: self, metadata: mergedMetadata)
}
public func makeDiagnosticsEmitter(metadataProvider: () -> ObservabilityMetadata) -> DiagnosticsEmitter {
self.makeDiagnosticsEmitter(metadata: metadataProvider())
}
// FIXME: we want to remove this functionality and move to more conventional error handling
//@available(*, deprecated, message: "this pattern is deprecated, transition to error handling instead")
public var errorsReported: Bool {
self.diagnosticsHandler.errorsReported
}
// FIXME: we want to remove this functionality and move to more conventional error handling
//@available(*, deprecated, message: "this pattern is deprecated, transition to error handling instead")
public var errorsReportedInAnyScope: Bool {
if self.errorsReported {
return true
}
return parent?.errorsReportedInAnyScope ?? false
}
// DiagnosticsEmitterProtocol
public func emit(_ diagnostic: Diagnostic) {
var diagnostic = diagnostic
diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)
self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: diagnostic)
}
private struct DiagnosticsHandlerWrapper: DiagnosticsHandler {
private let underlying: DiagnosticsHandler
private var _errorsReported = ThreadSafeBox<Bool>(false)
init(_ underlying: DiagnosticsHandler) {
self.underlying = underlying
}
public func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {
if diagnostic.severity == .error {
self._errorsReported.put(true)
}
self.underlying.handleDiagnostic(scope: scope, diagnostic: diagnostic)
}
var errorsReported: Bool {
self._errorsReported.get() ?? false
}
}
}
// MARK: - Diagnostics
public protocol DiagnosticsHandler {
func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic)
}
// helper protocol to share default behavior
public protocol DiagnosticsEmitterProtocol {
func emit(_ diagnostic: Diagnostic)
}
extension DiagnosticsEmitterProtocol {
public func emit(_ diagnostics: [Diagnostic]) {
for diagnostic in diagnostics {
self.emit(diagnostic)
}
}
public func emit(severity: Diagnostic.Severity, message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(.init(severity: severity, message: message, metadata: metadata))
}
public func emit(error message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(.init(severity: .error, message: message, metadata: metadata))
}
public func emit(error message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(error: message.description, metadata: metadata)
}
public func emit(_ error: Error, metadata: ObservabilityMetadata? = .none) {
self.emit(.error(error, metadata: metadata))
}
public func emit(warning message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .warning, message: message, metadata: metadata)
}
public func emit(warning message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(warning: message.description, metadata: metadata)
}
public func emit(info message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .info, message: message, metadata: metadata)
}
public func emit(info message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(info: message.description, metadata: metadata)
}
public func emit(debug message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .debug, message: message, metadata: metadata)
}
public func emit(debug message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(debug: message.description, metadata: metadata)
}
/// trap a throwing closure, emitting diagnostics on error and returning the value returned by the closure
public func trap<T>(_ closure: () throws -> T) -> T? {
do {
return try closure()
} catch Diagnostics.fatalError {
// FIXME: (diagnostics) deprecate this with Diagnostics.fatalError
return nil
} catch {
self.emit(error)
return nil
}
}
/// trap a throwing closure, emitting diagnostics on error and returning boolean representing success
@discardableResult
public func trap(_ closure: () throws -> Void) -> Bool {
do {
try closure()
return true
} catch Diagnostics.fatalError {
// FIXME: (diagnostics) deprecate this with Diagnostics.fatalError
return false
} catch {
self.emit(error)
return false
}
}
}
// TODO: consider using @autoclosure to delay potentially expensive evaluation of data when some diagnostics may be filtered out
public struct DiagnosticsEmitter: DiagnosticsEmitterProtocol {
private let scope: ObservabilityScope
private let metadata: ObservabilityMetadata?
fileprivate init(scope: ObservabilityScope, metadata: ObservabilityMetadata?) {
self.scope = scope
self.metadata = metadata
}
public func emit(_ diagnostic: Diagnostic) {
var diagnostic = diagnostic
diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)
self.scope.emit(diagnostic)
}
}
public struct Diagnostic: CustomStringConvertible {
public let severity: Severity
public let message: String
public internal (set) var metadata: ObservabilityMetadata?
public init(severity: Severity, message: String, metadata: ObservabilityMetadata?) {
self.severity = severity
self.message = message
self.metadata = metadata
}
public var description: String {
return "[\(self.severity)]: \(self.message)"
}
public static func error(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .error, message: message, metadata: metadata)
}
public static func error(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .error, message: message.description, metadata: metadata)
}
public static func error(_ error: Error, metadata: ObservabilityMetadata? = .none) -> Self {
var metadata = metadata ?? ObservabilityMetadata()
if metadata.underlyingError == nil {
metadata.underlyingError = .init(error)
}
let message: String
// FIXME: this brings in the TSC API still
// FIXME: string interpolation seems brittle
if let diagnosticData = error as? DiagnosticData {
message = "\(diagnosticData)"
} else if let convertible = error as? DiagnosticDataConvertible {
message = "\(convertible.diagnosticData)"
} else if let localizedError = error as? LocalizedError {
message = localizedError.errorDescription ?? localizedError.localizedDescription
} else {
message = "\(error)"
}
return Self(severity: .error, message: message, metadata: metadata)
}
public static func warning(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .warning, message: message, metadata: metadata)
}
public static func warning(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .warning, message: message.description, metadata: metadata)
}
public static func info(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .info, message: message, metadata: metadata)
}
public static func info(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .info, message: message.description, metadata: metadata)
}
public static func debug(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .debug, message: message, metadata: metadata)
}
public static func debug(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .debug, message: message.description, metadata: metadata)
}
public enum Severity: Comparable {
case error
case warning
case info
case debug
internal var naturalIntegralValue: Int {
switch self {
case .debug:
return 0
case .info:
return 1
case .warning:
return 2
case .error:
return 3
}
}
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.naturalIntegralValue < rhs.naturalIntegralValue
}
}
}
// MARK: - ObservabilityMetadata
/// Provides type-safe access to the ObservabilityMetadata's values.
/// This API should ONLY be used inside of accessor implementations.
///
/// End users should use "accessors" the key's author MUST define rather than using this subscript, following this pattern:
///
/// extension ObservabilityMetadata {
/// var testID: String? {
/// get {
/// self[TestIDKey.self]
/// }
/// set {
/// self[TestIDKey.self] = newValue
/// }
/// }
/// }
///
/// enum TestIDKey: ObservabilityMetadataKey {
/// typealias Value = String
/// }
///
/// This is in order to enforce a consistent style across projects and also allow for fine grained control over
/// who may set and who may get such property. Just access control to the Key type itself lacks such fidelity.
///
/// Note that specific baggage and context types MAY (and usually do), offer also a way to set baggage values,
/// however in the most general case it is not required, as some frameworks may only be able to offer reading.
// FIXME: we currently require that Value conforms to CustomStringConvertible which sucks
// ideally Value would conform to Equatable but that has generic requirement
// luckily, this is about to change so we can clean this up soon
public struct ObservabilityMetadata: CustomDebugStringConvertible {
public typealias Key = ObservabilityMetadataKey
private var _storage = [AnyKey: Any]()
public init() {}
public subscript<Key: ObservabilityMetadataKey>(_ key: Key.Type) -> Key.Value? {
get {
guard let value = self._storage[AnyKey(key)] else { return nil }
// safe to force-cast as this subscript is the only way to set a value.
return (value as! Key.Value)
}
set {
self._storage[AnyKey(key)] = newValue
}
}
/// The number of items in the baggage.
public var count: Int {
self._storage.count
}
/// A Boolean value that indicates whether the baggage is empty.
public var isEmpty: Bool {
self._storage.isEmpty
}
/// Iterate through all items in this `ObservabilityMetadata` by invoking the given closure for each item.
///
/// The order of those invocations is NOT guaranteed and should not be relied on.
///
/// - Parameter body: The closure to be invoked for each item stored in this `ObservabilityMetadata`,
/// passing the type-erased key and the associated value.
public func forEach(_ body: (AnyKey, Any) throws -> Void) rethrows {
try self._storage.forEach { key, value in
try body(key, value)
}
}
public func merging(_ other: ObservabilityMetadata) -> ObservabilityMetadata {
var merged = ObservabilityMetadata()
self.forEach { (key, value) in
merged._storage[key] = value
}
other.forEach { (key, value) in
merged._storage[key] = value
}
return merged
}
public var debugDescription: String {
var items = [String]()
self._storage.forEach { key, value in
items.append("\(key.keyType.self): \(String(describing: value))")
}
return items.joined(separator: ", ")
}
// FIXME: this currently requires that Value conforms to CustomStringConvertible which sucks
// ideally Value would conform to Equatable but that has generic requirement
// luckily, this is about to change so we can clean this up soon
/*
public static func == (lhs: ObservabilityMetadata, rhs: ObservabilityMetadata) -> Bool {
if lhs.count != rhs.count {
return false
}
var equals = true
lhs.forEach { (key, value) in
if rhs._storage[key]?.description != value.description {
equals = false
return
}
}
return equals
}*/
fileprivate static func mergeLeft(_ lhs: ObservabilityMetadata?, _ rhs: ObservabilityMetadata?) -> ObservabilityMetadata? {
switch (lhs, rhs) {
case (.none, .none):
return .none
case (.some(let left), .some(let right)):
return left.merging(right)
case (.some(let left), .none):
return left
case (.none, .some(let right)):
return right
}
}
/// A type-erased `ObservabilityMetadataKey` used when iterating through the `ObservabilityMetadata` using its `forEach` method.
public struct AnyKey {
/// The key's type represented erased to an `Any.Type`.
public let keyType: Any.Type
init<Key: ObservabilityMetadataKey>(_ keyType: Key.Type) {
self.keyType = keyType
}
}
}
public protocol ObservabilityMetadataKey {
/// The type of value uniquely identified by this key.
associatedtype Value
}
extension ObservabilityMetadata.AnyKey: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
ObjectIdentifier(lhs.keyType) == ObjectIdentifier(rhs.keyType)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self.keyType))
}
}
extension ObservabilityMetadata {
public var underlyingError: Error? {
get {
self[UnderlyingErrorKey.self]
}
set {
self[UnderlyingErrorKey.self] = newValue
}
}
private enum UnderlyingErrorKey: Key {
typealias Value = Error
}
public struct UnderlyingError: CustomStringConvertible {
let underlying: Error
public init (_ underlying: Error) {
self.underlying = underlying
}
public var description: String {
String(describing: self.underlying)
}
}
}
// MARK: - Compatibility with TSC Diagnostics APIs
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityScope {
public func makeDiagnosticsEngine() -> DiagnosticsEngine {
return .init(handlers: [{ Diagnostic($0).map{ self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: $0) } }])
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension Diagnostic {
init?(_ diagnostic: TSCBasic.Diagnostic) {
var metadata = ObservabilityMetadata()
if !(diagnostic.location is UnknownLocation) {
metadata.legacyDiagnosticLocation = .init(diagnostic.location)
}
metadata.legacyDiagnosticData = .init(diagnostic.data)
switch diagnostic.behavior {
case .error:
self = .error(diagnostic.message.text, metadata: metadata)
case .warning:
self = .warning(diagnostic.message.text, metadata: metadata)
case .note:
self = .info(diagnostic.message.text, metadata: metadata)
case .remark:
self = .info(diagnostic.message.text, metadata: metadata)
case .ignored:
return nil
}
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityMetadata {
public var legacyDiagnosticLocation: DiagnosticLocationWrapper? {
get {
self[LegacyLocationKey.self]
}
set {
self[LegacyLocationKey.self] = newValue
}
}
private enum LegacyLocationKey: Key {
typealias Value = DiagnosticLocationWrapper
}
public struct DiagnosticLocationWrapper: CustomStringConvertible {
let underlying: DiagnosticLocation
public init (_ underlying: DiagnosticLocation) {
self.underlying = underlying
}
public var description: String {
self.underlying.description
}
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityMetadata {
var legacyDiagnosticData: DiagnosticDataWrapper? {
get {
self[LegacyDataKey.self]
}
set {
self[LegacyDataKey.self] = newValue
}
}
private enum LegacyDataKey: Key {
typealias Value = DiagnosticDataWrapper
}
struct DiagnosticDataWrapper: CustomStringConvertible {
let underlying: DiagnosticData
public init (_ underlying: DiagnosticData) {
self.underlying = underlying
}
public var description: String {
self.underlying.description
}
}
}
|
850ce39c7f009ad6195da4cbaa2fe0a5
| 34.12398 | 132 | 0.655381 | false | false | false | false |
devincoughlin/swift
|
refs/heads/master
|
test/IRGen/objc_retainAutoreleasedReturnValue.swift
|
apache-2.0
|
9
|
// RUN: %target-swift-frontend -module-name objc_retainAutoreleasedReturnValue -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s
// RUN: %target-swift-frontend -module-name objc_retainAutoreleasedReturnValue -O -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s --check-prefix=OPT
// REQUIRES: objc_interop
// REQUIRES: CPU=x86_64
// REQUIRES: OS=macosx
import Foundation
@inline(never)
public func useClosure(_ dict: NSDictionary, _ action : (NSDictionary) -> ()) {
action(dict)
}
@inline(never)
public func test(_ dict: NSDictionary) {
useClosure(dict, { $0.objectEnumerator()} )
}
// Don't tail call objc_retainAutoreleasedReturnValue as this would block the
// autorelease return value optimization.
// callq 0x01ec08 ; symbol stub for: objc_msgSend
// movq %rax, %rdi
// popq %rbp ;<== Blocks the handshake from objc_autoreleaseReturnValue
// jmp 0x01ec20 ; symbol stub for: objc_retainAutoreleasedReturnValue
// CHECK-LABEL: define {{.*}}swiftcc void @"$s34objc_retainAutoreleasedReturnValue4testyySo12NSDictionaryCFyADXEfU_"(%TSo12NSDictionaryC*)
// CHECK: entry:
// CHECK: call {{.*}}@objc_msgSend
// CHECK: notail call i8* @llvm.objc.retainAutoreleasedReturnValue
// CHECK: ret void
// OPT-LABEL: define {{.*}}swiftcc void @"$s34objc_retainAutoreleasedReturnValue4testyySo12NSDictionaryCFyADXEfU_"(%TSo12NSDictionaryC*)
// OPT: entry:
// OPT: call {{.*}}@objc_msgSend
// OPT: notail call i8* @llvm.objc.retainAutoreleasedReturnValue
// OPT: ret void
|
bccb3c36312b96e9a5deccb7ce453846
| 39.5 | 173 | 0.734243 | false | true | false | false |
wowiwj/Yeep
|
refs/heads/master
|
Yeep/Yeep/Caches/AvatarCache.swift
|
mit
|
1
|
//
// AvatarCache.swift
// Yeep
//
// Created by wangju on 16/7/18.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
class AvatarCache{
static let sharedInstance = AvatarCache()
//NSCache是苹果官方提供的缓存类,使用它来管理缓存,NSCache在系统内存很低时,会自动释放一些对象
var cache = NSCache()
func roundImage(named name:String,ofRadoius radius:CGFloat)->UIImage
{
let roundImageKey = "\(name)-\(radius)"
if let roundImage = cache.objectForKey(roundImageKey) as? UIImage {
// 如果在缓存中找到图片,直接取出
return roundImage
}else
{
if let image = UIImage(named: name)
{
let roundImage = image.roundImageOfRadius(radius)
cache.setObject(roundImage, forKey: roundImageKey)
return roundImage
}
}
// 没有得到图片
return roundImage(named: "default_avatar", ofRadoius: radius)
}
}
|
818204045c6302b947745f9c297ce8b8
| 23.487179 | 76 | 0.58534 | false | false | false | false |
JoeLago/MHGDB-iOS
|
refs/heads/master
|
MHGDB/Model/PalicoWeapon.swift
|
mit
|
1
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import Foundation
import GRDB
class PalicoWeapon: RowConvertible {
enum Balance: Int {
case balanced = 0, meleePlus, rangedPlus
var string: String {
switch self {
case .balanced: return "Balanced"
case .meleePlus: return "Melee+"
case .rangedPlus: return "Ranged+"
}
}
}
var id: Int
var name: String
var icon: String?
var description: String
var attackMelee: Int
var attackRanged: Int
var balanceValue: Int
var balance: Balance {
return Balance(rawValue: balanceValue) ?? .balanced
}
var elementString: String?
var element: Element? {
if let elementString = elementString {
return Element(rawValue: elementString)
} else {
return nil
}
}
var elementMelee: Int?
var elementRanged: Int?
var defense: Int?
var sharpnessValue: Int
var sharpness: Sharpness {
return Sharpness(palicoSharpness: sharpnessValue)
}
var affinityMelee: Int
var affinityRanged: Int
var isBlunt: Bool
var type: String {
return isBlunt ? "Blunt" : "Cutting"
}
var creationCost: Int
lazy var components: [Component] = {
return Database.shared.components(itemId: self.id)
}()
required init(row: Row) {
id = row["_id"]
name = row["name"]
icon = row["icon_name"]
description = row["description"]
attackMelee = row["attack_melee"]
attackRanged = row["attack_ranged"]
balanceValue = row["balance"]
elementString = row["element"]
elementMelee = row["element_melee"]
elementRanged = row["element_ranged"]
defense = row["defense"]
sharpnessValue = row["sharpness"]
affinityMelee = row["affinity_melee"]
affinityRanged = row["affinity_ranged"]
isBlunt = row["blunt"]
creationCost = row["creation_cost"]
}
}
extension Database {
func palicoWeapon(id: Int) -> PalicoWeapon {
let query = "SELECT * FROM palico_weapons LEFT JOIN items on palico_weapons._id = items._id"
+ " WHERE palico_weapons._id = \(id)"
return fetch(query)[0]
}
func palicoWeapons() -> [PalicoWeapon] {
let query = "SELECT * FROM palico_weapons LEFT JOIN items on palico_weapons._id = items._id"
return fetch(query)
}
func palicoWeapons(_ search: String) -> [PalicoWeapon] {
let query = "SELECT * FROM palico_weapons LEFT JOIN items on palico_weapons._id = items._id"
return fetch(select: query, search: search)
}
}
|
9a909872c4896a5bcce89066552639da
| 26.088235 | 100 | 0.588129 | false | false | false | false |
mrdepth/EVEOnlineAPI
|
refs/heads/master
|
EVEAPI/EVEAPI/codegen/Location.swift
|
mit
|
1
|
import Foundation
import Alamofire
import Futures
public extension ESI {
var location: Location {
return Location(esi: self)
}
struct Location {
let esi: ESI
@discardableResult
public func getCurrentShip(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Location.CharacterShip>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-location.read_ship_type.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/ship/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<Location.CharacterShip>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Location.CharacterShip>) in
promise.set(response: response, cached: 5.0)
}
return promise.future
}
@discardableResult
public func getCharacterOnline(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Location.GetCharactersCharacterIDOnlineOk>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-location.read_online.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/online/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<Location.GetCharactersCharacterIDOnlineOk>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Location.GetCharactersCharacterIDOnlineOk>) in
promise.set(response: response, cached: 60.0)
}
return promise.future
}
@discardableResult
public func getCharacterLocation(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Location.CharacterLocation>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-location.read_location.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/location/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<Location.CharacterLocation>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Location.CharacterLocation>) in
promise.set(response: response, cached: 5.0)
}
return promise.future
}
public struct CharacterShip: Codable, Hashable {
public var shipItemID: Int64
public var shipName: String
public var shipTypeID: Int
public init(shipItemID: Int64, shipName: String, shipTypeID: Int) {
self.shipItemID = shipItemID
self.shipName = shipName
self.shipTypeID = shipTypeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case shipItemID = "ship_item_id"
case shipName = "ship_name"
case shipTypeID = "ship_type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct CharacterLocation: Codable, Hashable {
public var solarSystemID: Int
public var stationID: Int?
public var structureID: Int64?
public init(solarSystemID: Int, stationID: Int?, structureID: Int64?) {
self.solarSystemID = solarSystemID
self.stationID = stationID
self.structureID = structureID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case solarSystemID = "solar_system_id"
case stationID = "station_id"
case structureID = "structure_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct GetCharactersCharacterIDOnlineOk: Codable, Hashable {
public var lastLogin: Date?
public var lastLogout: Date?
public var logins: Int?
public var online: Bool
public init(lastLogin: Date?, lastLogout: Date?, logins: Int?, online: Bool) {
self.lastLogin = lastLogin
self.lastLogout = lastLogout
self.logins = logins
self.online = online
}
enum CodingKeys: String, CodingKey, DateFormatted {
case lastLogin = "last_login"
case lastLogout = "last_logout"
case logins
case online
var dateFormatter: DateFormatter? {
switch self {
case .lastLogin: return DateFormatter.esiDateTimeFormatter
case .lastLogout: return DateFormatter.esiDateTimeFormatter
default: return nil
}
}
}
}
}
}
|
0225d8ec608cc765b093d8e16abb602e
| 29.915344 | 227 | 0.690912 | false | false | false | false |
Gruppio/Invoke
|
refs/heads/master
|
Sources/Keychain.swift
|
mit
|
1
|
//
// Keychain.swift
// Invoke
//
// Created by Travasoni Giuseppe on 24/08/16.
// KeychainSwift is based on https://github.com/marketplacer/keychain-swift
//
import Security
import Foundation
/**
A collection of helper functions for saving text and data in the keychain.
*/
public class KeychainSwift {
var lastQueryParameters: [String: Any]? // Used by the unit tests
/// Contains result code from the last operation. Value is noErr (0) for a successful result.
public var lastResultCode: OSStatus = noErr
var keyPrefix = "" // Can be useful in test.
/**
Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear.
*/
public var accessGroup: String?
/**
Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings.
Does not work on macOS.
*/
public var synchronizable: Bool = false
/// Instantiate a KeychainSwift object
public init() { }
/**
- parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
*/
public init(keyPrefix: String) {
self.keyPrefix = keyPrefix
}
/**
Stores the text value in the keychain item under the given key.
- parameter key: Key under which the text value is stored in the keychain.
- parameter value: Text string to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
public func set(_ value: String, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
if let value = value.data(using: String.Encoding.utf8) {
return set(value, forKey: key, withAccess: access)
}
return false
}
/**
Stores the string array value in the keychain item under the given key.
- parameter key: Key under which the text value is stored in the keychain.
- parameter value: String array to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
public func set(_ value: [String], forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
if let value = value.joined(separator: "|").data(using: String.Encoding.utf8),
value.count > 0 {
return set(value, forKey: key, withAccess: access)
}
else if value.count == 0 {
return delete(key)
}
return false
}
/**
Stores the data in the keychain item under the given key.
- parameter key: Key under which the data is stored in the keychain.
- parameter value: Data to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
public func set(_ value: Data, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
delete(key) // Delete any existing key before saving it
let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
let prefixedKey = keyWithPrefix(key)
var query: [String : Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.valueData : value,
KeychainSwiftConstants.accessible : accessible
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: true)
lastQueryParameters = query
lastResultCode = SecItemAdd(query as CFDictionary, nil)
return lastResultCode == noErr
}
/**
Stores the boolean value in the keychain item under the given key.
- parameter key: Key under which the value is stored in the keychain.
- parameter value: Boolean to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the value was successfully written to the keychain.
*/
@discardableResult
public func set(_ value: Bool, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
let bytes: [UInt8] = value ? [1] : [0]
let data = Data(bytes: bytes)
return set(data, forKey: key, withAccess: access)
}
/**
Retrieves the text value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
public func getString(_ key: String) -> String? {
if let data = getData(key) {
if let currentString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String {
return currentString
}
lastResultCode = -67853 // errSecInvalidEncoding
}
return nil
}
/**
Retrieves the string array value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The string array value from the keychain. Returns nil if unable to read the item.
*/
public func getStringArray(_ key: String) -> [String]? {
if let data = getData(key) {
if let currentString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String {
return currentString.components(separatedBy: "|")
}
lastResultCode = -67853 // errSecInvalidEncoding
}
return nil
}
/**
Retrieves the data from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
public func getData(_ key: String) -> Data? {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.returnData : kCFBooleanTrue,
KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
var result: AnyObject?
lastResultCode = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if lastResultCode == noErr { return result as? Data }
return nil
}
/**
Retrieves the boolean value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The boolean value from the keychain. Returns nil if unable to read the item.
*/
public func getBool(_ key: String) -> Bool? {
guard let data = getData(key) else { return nil }
guard let firstBit = data.first else { return nil }
return firstBit == 1
}
/**
Deletes the single keychain item specified by the key.
- parameter key: The key that is used to delete the keychain item.
- returns: True if the item was successfully deleted.
*/
@discardableResult
public func delete(_ key: String) -> Bool {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/**
Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class.
- returns: True if the keychain items were successfully deleted.
*/
@discardableResult
public func clear() -> Bool {
var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/// Returns the key with currently set prefix.
func keyWithPrefix(_ key: String) -> String {
return "\(keyPrefix)\(key)"
}
func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] {
guard let accessGroup = accessGroup else { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.accessGroup] = accessGroup
return result
}
/**
Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
- parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
- parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
- returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
*/
func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] {
if !synchronizable { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
return result
}
}
/**
These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
*/
public enum KeychainSwiftAccessOptions {
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
This is the default value for keychain items added without explicitly setting an accessibility constant.
*/
case accessibleWhenUnlocked
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleWhenUnlockedThisDeviceOnly
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAfterFirstUnlock
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAfterFirstUnlockThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAlways
/**
The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
*/
case accessibleWhenPasscodeSetThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAlwaysThisDeviceOnly
static var defaultOption: KeychainSwiftAccessOptions {
return .accessibleWhenUnlocked
}
var value: String {
switch self {
case .accessibleWhenUnlocked:
return toString(kSecAttrAccessibleWhenUnlocked)
case .accessibleWhenUnlockedThisDeviceOnly:
return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .accessibleAfterFirstUnlock:
return toString(kSecAttrAccessibleAfterFirstUnlock)
case .accessibleAfterFirstUnlockThisDeviceOnly:
return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
case .accessibleAlways:
return toString(kSecAttrAccessibleAlways)
case .accessibleWhenPasscodeSetThisDeviceOnly:
return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .accessibleAlwaysThisDeviceOnly:
return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
}
}
func toString(_ value: CFString) -> String {
return KeychainSwiftConstants.toString(value)
}
}
/// Constants used by the library
public struct KeychainSwiftConstants {
/// Specifies a Keychain access group. Used for sharing Keychain items between apps.
public static var accessGroup: String { return toString(kSecAttrAccessGroup) }
/**
A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see KeychainSwiftAccessOptions.
*/
public static var accessible: String { return toString(kSecAttrAccessible) }
/// Used for specifying a String key when setting/getting a Keychain value.
public static var attrAccount: String { return toString(kSecAttrAccount) }
/// Used for specifying synchronization of keychain items between devices.
public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) }
/// An item class key used to construct a Keychain search dictionary.
public static var klass: String { return toString(kSecClass) }
/// Specifies the number of values returned from the keychain. The library only supports single values.
public static var matchLimit: String { return toString(kSecMatchLimit) }
/// A return data type used to get the data from the Keychain.
public static var returnData: String { return toString(kSecReturnData) }
/// Used for specifying a value when setting a Keychain value.
public static var valueData: String { return toString(kSecValueData) }
static func toString(_ value: CFString) -> String {
return value as String
}
}
|
f62b4021df0b1629d010dbcf175a7605
| 39.652561 | 380 | 0.668548 | false | false | false | false |
mauryat/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/TabTrayController.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
static let MenuFixedWidth: CGFloat = 320
static let RearrangeWobblePeriod: TimeInterval = 0.1
static let RearrangeTransitionDuration: TimeInterval = 0.2
static let RearrangeWobbleAngle: CGFloat = 0.02
static let RearrangeDragScale: CGFloat = 1.1
static let RearrangeDragAlpha: CGFloat = 0.9
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.main.traitCollection.verticalSizeClass == .compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.black
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.white
}
protocol TabCellDelegate: class {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case light
case dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
var isBeingArranged: Bool = false {
didSet {
if isBeingArranged {
self.contentView.transform = CGAffineTransform(rotationAngle: TabTrayControllerUX.RearrangeWobbleAngle)
UIView.animate(withDuration: TabTrayControllerUX.RearrangeWobblePeriod, delay: 0, options: [.allowUserInteraction, .repeat, .autoreverse], animations: {
self.contentView.transform = CGAffineTransform(rotationAngle: -TabTrayControllerUX.RearrangeWobbleAngle)
}, completion: nil)
} else {
if oldValue {
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.contentView.transform = CGAffineTransform.identity
}, completion: nil)
}
}
}
}
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.white
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.scaleAspectFill
self.background.clipsToBounds = true
self.background.isUserInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clear
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.left
self.titleText.isUserInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), for: UIControlState())
self.closeButton.tintColor = UIColor.lightGray
self.closeButton.imageEdgeInsets = UIEdgeInsets(equalInset: TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clear.cgColor
super.init(frame: frame)
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self, action: #selector(TabCell.SELclose), for: UIControlEvents.touchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: #selector(SwipeAnimator.SELcloseWithoutGesture))
]
}
fileprivate func applyStyle(_ style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clear
title.contentView.addSubview(self.closeButton)
title.contentView.addSubview(self.titleText)
title.contentView.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp.makeConstraints { make in
make.size.equalTo(title.snp.height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransform.identity
backgroundHolder.alpha = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
}
override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .left:
right = false
case .right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
@objc
func SELclose() {
self.animator.SELcloseWithoutGesture()
}
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
protocol TabTrayDelegate: class {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddBookmark(_ tab: Tab)
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
struct TabTrayState {
var isPrivate: Bool = false
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
weak var appStateDelegate: AppStateDelegate?
var collectionView: UICollectionView!
var draggedCell: TabCell?
var dragOffset: CGPoint = CGPoint.zero
lazy var toolbar: TrayToolbar = {
let toolbar = TrayToolbar()
toolbar.addTabButton.addTarget(self, action: #selector(TabTrayController.SELdidClickAddTab), for: .touchUpInside)
toolbar.menuButton.addTarget(self, action: #selector(TabTrayController.didTapMenu), for: .touchUpInside)
toolbar.maskButton.addTarget(self, action: #selector(TabTrayController.SELdidTogglePrivateMode), for: .touchUpInside)
return toolbar
}()
var tabTrayState: TabTrayState {
return TabTrayState(isPrivate: self.privateMode)
}
var leftToolbarButtons: [UIButton] {
return [toolbar.addTabButton]
}
var rightToolbarButtons: [UIButton]? {
return [toolbar.maskButton]
}
fileprivate(set) internal var privateMode: Bool = false {
didSet {
if oldValue != privateMode {
updateAppState()
}
tabDataSource.tabs = tabsToDisplay
toolbar.styleToolbar(privateMode)
collectionView?.reloadData()
}
}
fileprivate var tabsToDisplay: [Tab] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
let emptyView = EmptyPrivateTabsView()
emptyView.learnMoreButton.addTarget(self, action: #selector(TabTrayController.SELdidTapLearnMore), for: UIControlEvents.touchUpInside)
return emptyView
}()
fileprivate lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self, tabManager: self.tabManager)
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
tabManager.addDelegate(self)
}
convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) {
self.init(tabManager: tabManager, profile: profile)
self.delegate = tabTrayDelegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
self.tabManager.removeDelegate(self)
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
self.collectionView.reloadData()
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIConstants.ToolbarHeight, right: 0)
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
if AppConstants.MOZ_REORDER_TAB_TRAY {
collectionView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(didLongPressTab)))
}
view.addSubview(collectionView)
view.addSubview(toolbar)
makeConstraints()
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.snp.makeConstraints { make in
make.top.left.right.equalTo(self.collectionView)
make.bottom.equalTo(self.toolbar.snp.top)
}
if let tab = tabManager.selectedTab, tab.isPrivate {
privateMode = true
}
// register for previewing delegate to enable peek and pop if force touch feature available
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
self.collectionView.collectionViewLayout.invalidateLayout()
}
fileprivate func cancelExistingGestures() {
if let visibleCells = self.collectionView.visibleCells as? [TabCell] {
for cell in visibleCells {
cell.animator.cancelExistingGestures()
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if AppConstants.MOZ_REORDER_TAB_TRAY {
self.cancelExistingGestures()
}
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
fileprivate func makeConstraints() {
collectionView.snp.makeConstraints { make in
make.left.bottom.right.equalTo(view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
toolbar.snp.makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.height.equalTo(UIConstants.ToolbarHeight)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismiss(animated: true, completion: nil)
}
func SELdidClickSettingsItem() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.formSheet
present(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
openNewTab()
LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source":"Tab Tray" as AnyObject])
}
func SELdidTapLearnMore() {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
if let langID = Locale.preferredLanguages.first {
let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion)/iOS/\(langID)/private-browsing-ios".asURL!)
openNewTab(learnMoreRequest)
}
}
@objc
fileprivate func didTapMenu() {
let state = mainStore.updateState(.tabTray(tabTrayState: self.tabTrayState))
let mvc = MenuViewController(withAppState: state, presentationStyle: .modal)
mvc.delegate = self
mvc.actionDelegate = self
mvc.menuTransitionDelegate = MenuPresentationAnimator()
mvc.modalPresentationStyle = .overCurrentContext
mvc.fixedWidth = TabTrayControllerUX.MenuFixedWidth
if AppConstants.MOZ_REORDER_TAB_TRAY {
self.cancelExistingGestures()
}
self.present(mvc, animated: true, completion: nil)
}
func didLongPressTab(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
let pressPosition = gesture.location(in: self.collectionView)
guard let indexPath = self.collectionView.indexPathForItem(at: pressPosition) else {
break
}
self.collectionView.beginInteractiveMovementForItem(at: indexPath)
self.view.isUserInteractionEnabled = false
self.tabDataSource.isRearrangingTabs = true
for item in 0..<self.tabDataSource.collectionView(self.collectionView, numberOfItemsInSection: 0) {
guard let cell = self.collectionView.cellForItem(at: IndexPath(item: item, section: 0)) as? TabCell else {
continue
}
if item == indexPath.item {
let cellPosition = cell.contentView.convert(cell.bounds.center, to: self.collectionView)
self.draggedCell = cell
self.dragOffset = CGPoint(x: pressPosition.x - cellPosition.x, y: pressPosition.y - cellPosition.y)
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
cell.contentView.transform = CGAffineTransform(scaleX: TabTrayControllerUX.RearrangeDragScale, y: TabTrayControllerUX.RearrangeDragScale)
cell.contentView.alpha = TabTrayControllerUX.RearrangeDragAlpha
}, completion: nil)
continue
}
cell.isBeingArranged = true
}
break
case .changed:
if let view = gesture.view, let draggedCell = self.draggedCell {
var dragPosition = gesture.location(in: view)
let offsetPosition = CGPoint(x: dragPosition.x + draggedCell.frame.center.x * (1 - TabTrayControllerUX.RearrangeDragScale), y: dragPosition.y + draggedCell.frame.center.y * (1 - TabTrayControllerUX.RearrangeDragScale))
dragPosition = CGPoint(x: offsetPosition.x - self.dragOffset.x, y: offsetPosition.y - self.dragOffset.y)
collectionView.updateInteractiveMovementTargetPosition(dragPosition)
}
case .ended, .cancelled:
for item in 0..<self.tabDataSource.collectionView(self.collectionView, numberOfItemsInSection: 0) {
guard let cell = self.collectionView.cellForItem(at: IndexPath(item: item, section: 0)) as? TabCell else {
continue
}
if !cell.isBeingArranged {
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
cell.contentView.transform = CGAffineTransform.identity
cell.contentView.alpha = 1
}, completion: nil)
continue
}
cell.isBeingArranged = false
}
self.tabDataSource.isRearrangingTabs = false
self.view.isUserInteractionEnabled = true
gesture.state == .ended ? self.collectionView.endInteractiveMovement() : self.collectionView.cancelInteractiveMovement()
default:
break
}
}
func SELdidTogglePrivateMode() {
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
let fromView: UIView
if !privateTabsAreEmpty(), let snapshot = collectionView.snapshotView(afterScreenUpdates: false) {
snapshot.frame = collectionView.frame
view.insertSubview(snapshot, aboveSubview: collectionView)
fromView = snapshot
} else {
fromView = emptyPrivateTabsView
}
tabManager.willSwitchTabMode()
privateMode = !privateMode
// If we are exiting private mode and we have the close private tabs option selected, make sure
// we clear out all of the private tabs
let exitingPrivateMode = !privateMode && tabManager.shouldClearPrivateTabs()
toolbar.maskButton.setSelected(privateMode, animated: true)
collectionView.layoutSubviews()
let toView: UIView
if !privateTabsAreEmpty(), let newSnapshot = collectionView.snapshotView(afterScreenUpdates: !exitingPrivateMode) {
emptyPrivateTabsView.isHidden = true
//when exiting private mode don't screenshot the collectionview (causes the UI to hang)
newSnapshot.frame = collectionView.frame
view.insertSubview(newSnapshot, aboveSubview: fromView)
collectionView.alpha = 0
toView = newSnapshot
} else {
emptyPrivateTabsView.isHidden = false
toView = emptyPrivateTabsView
}
toView.alpha = 0
toView.transform = scaleDownTransform
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { () -> Void in
fromView.transform = scaleDownTransform
fromView.alpha = 0
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if toView != self.emptyPrivateTabsView {
toView.removeFromSuperview()
}
self.collectionView.alpha = 1
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.privateTabs.count == 0
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != privateMode {
guard let _ = collectionView else {
privateMode = isPrivate
return
}
SELdidTogglePrivateMode()
}
}
fileprivate func openNewTab(_ request: URLRequest? = nil) {
toolbar.isUserInteractionEnabled = false
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab(request, isPrivate: self.privateMode)
self.tabManager.selectTab(tab)
}, completion: { finished in
self.toolbar.isUserInteractionEnabled = true
if finished {
_ = self.navigationController?.popViewController(animated: true)
if request == nil && NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage {
if let bvc = self.navigationController?.topViewController as? BrowserViewController {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
bvc.urlBar.tabLocationViewDidTapLocation(bvc.urlBar.locationView)
}
}
}
}
})
}
fileprivate func updateAppState() {
let state = mainStore.updateState(.tabTray(tabTrayState: self.tabTrayState))
self.appStateDelegate?.appDidUpdateState(state)
}
fileprivate func closeTabsForCurrentTray() {
tabManager.removeTabsWithUndoToast(tabsToDisplay)
self.collectionView.reloadData()
}
}
// MARK: - App Notifications
extension TabTrayController {
func SELappWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
}
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.collectionView.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
_ = self.navigationController?.popViewController(animated: true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.index(of: tab) else { return }
if !privateTabsAreEmpty() {
emptyPrivateTabsView.isHidden = true
}
tabDataSource.addTab(tab)
self.collectionView?.performBatchUpdates({ _ in
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
_ = self.navigationController?.popViewController(animated: true)
}
}
})
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
// it is possible that we are removing a tab that we are not currently displaying
// through the Close All Tabs feature (which will close tabs that are not in our current privacy mode)
// check this before removing the item from the collection
let removedIndex = tabDataSource.removeTab(tab)
if removedIndex > -1 {
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [IndexPath(item: removedIndex, section: 0)])
}, completion: { finished in
guard finished && self.privateTabsAreEmpty() else { return }
self.emptyPrivateTabsView.isHidden = false
})
// Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the
// animation has finished which causes cells that animate from above to suddenly 'appear'. This
// is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation.
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3 {
let visibleCount = collectionView.indexPathsForVisibleItems.count
var offscreenIndexPaths = [IndexPath]()
for i in 0..<(tabsToDisplay.count - visibleCount) {
offscreenIndexPaths.append(IndexPath(item: i, section: 0))
}
self.collectionView.reloadItems(at: offscreenIndexPaths)
}
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard privateMode else {
return
}
if let toast = toast {
view.addSubview(toast)
toast.snp.makeConstraints { make in
make.left.right.equalTo(view)
make.bottom.equalTo(toolbar.snp.top)
}
toast.showToast()
}
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells as! [TabCell]
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if firstTab == lastTab {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPath(for: tabCell) {
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "Accessibility label (used by assistive technology) notifying the user that the tab is being closed."))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
let indexPath = collectionView.indexPath(for: cell)!
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
}
}
extension TabTrayController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
let request = URLRequest(url: url)
openNewTab(request)
}
}
fileprivate class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: TabCellDelegate & SwipeAnimatorDelegate
fileprivate var tabs: [Tab]
fileprivate var tabManager: TabManager
var isRearrangingTabs: Bool = false
init(tabs: [Tab], cellDelegate: TabCellDelegate & SwipeAnimatorDelegate, tabManager: TabManager) {
self.cellDelegate = cellDelegate
self.tabs = tabs
self.tabManager = tabManager
super.init()
}
/**
Removes the given tab from the data source
- parameter tab: Tab to remove
- returns: The index of the removed tab, -1 if tab did not exist
*/
func removeTab(_ tabToRemove: Tab) -> Int {
var index: Int = -1
for (i, tab) in tabs.enumerated() where tabToRemove === tab {
index = i
tabs.remove(at: index)
break
}
return index
}
/**
Adds the given tab to the data source
- parameter tab: Tab to add
*/
func addTab(_ tab: Tab) {
tabs.append(tab)
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCell.Identifier, for: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .dark : .light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = tab.url?.aboutComponent ?? "" // If there is no title we are most likely on a home panel.
}
if AppConstants.MOZ_REORDER_TAB_TRAY {
tabCell.isBeingArranged = self.isRearrangingTabs
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
var defaultFavicon = UIImage(named: "defaultFavicon")
if tab.isPrivate {
defaultFavicon = defaultFavicon?.withRenderingMode(.alwaysTemplate)
tabCell.favicon.image = defaultFavicon
tabCell.favicon.tintColor = UIColor.white
} else {
tabCell.favicon.image = defaultFavicon
}
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
@objc fileprivate func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let fromIndex = sourceIndexPath.item
let toIndex = destinationIndexPath.item
tabs.insert(tabs.remove(at: fromIndex), at: toIndex < fromIndex ? toIndex : toIndex - 1)
tabManager.moveTab(isPrivate: tabs[fromIndex].isPrivate, fromIndex: fromIndex, toIndex: toIndex)
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(_ index: Int)
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
fileprivate var traitCollection: UITraitCollection
fileprivate var profile: Profile
fileprivate var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(equalInset: TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.white
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.white
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
static let MinBottomMargin: CGFloat = 10
}
// View we display when there are no private tabs created
fileprivate class EmptyPrivateTabsView: UIView {
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.center
return label
}()
fileprivate var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
fileprivate var learnMoreButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(
NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"),
for: UIControlState())
button.setTitleColor(UIConstants.PrivateModeTextHighlightColor, for: UIControlState())
button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont
return button
}()
fileprivate var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
addSubview(learnMoreButton)
titleLabel.snp.makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp.makeConstraints { make in
make.bottom.equalTo(titleLabel.snp.top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
learnMoreButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(descriptionLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin).priority(10)
make.bottom.lessThanOrEqualTo(self).offset(-EmptyPrivateTabsViewUX.MinBottomMargin).priority(1000)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TabTrayController: TabPeekDelegate {
func tabPeekDidAddBookmark(_ tab: Tab) {
delegate?.tabTrayDidAddBookmark(tab)
}
func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
return delegate?.tabTrayDidAddToReadingList(tab)
}
func tabPeekDidCloseTab(_ tab: Tab) {
if let index = self.tabDataSource.tabs.index(of: tab),
let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? TabCell {
cell.SELclose()
}
}
func tabPeekRequestsPresentationOf(_ viewController: UIViewController) {
delegate?.tabTrayRequestsPresentationOf(viewController)
}
}
extension TabTrayController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let collectionView = collectionView else { return nil }
let convertedLocation = self.view.convert(location, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: convertedLocation),
let cell = collectionView.cellForItem(at: indexPath) else { return nil }
let tab = tabDataSource.tabs[indexPath.row]
let tabVC = TabPeekViewController(tab: tab, delegate: self)
if let browserProfile = profile as? BrowserProfile {
tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self)
}
previewingContext.sourceRect = self.view.convert(cell.frame, from: collectionView)
return tabVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return }
tabManager.selectTab(tpvc.tab)
_ = self.navigationController?.popViewController(animated: true)
delegate?.tabTrayDidDismiss(self)
}
}
extension TabTrayController: ClientPickerViewControllerDelegate {
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
if let item = clientPickerViewController.shareItem {
self.profile.sendItems([item], toClients: clients)
}
clientPickerViewController.dismiss(animated: true, completion: nil)
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
clientPickerViewController.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
extension TabTrayController: MenuViewControllerDelegate {
func menuViewControllerDidDismiss(_ menuViewController: MenuViewController) { }
func shouldCloseMenu(_ menuViewController: MenuViewController, forRotationToNewSize size: CGSize, forTraitCollection traitCollection: UITraitCollection) -> Bool {
return false
}
}
extension TabTrayController: MenuActionDelegate {
func performMenuAction(_ action: MenuAction, withAppState appState: AppState) {
if let menuAction = AppMenuAction(rawValue: action.action) {
switch menuAction {
case .openNewNormalTab:
DispatchQueue.main.async {
if self.privateMode {
self.SELdidTogglePrivateMode()
}
self.openNewTab()
LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source":"Tab Tray Menu" as AnyObject])
}
case .openNewPrivateTab:
DispatchQueue.main.async {
if !self.privateMode {
self.SELdidTogglePrivateMode()
}
self.openNewTab()
}
case .openSettings:
DispatchQueue.main.async {
self.SELdidClickSettingsItem()
}
case .closeAllTabs:
DispatchQueue.main.async {
self.closeTabsForCurrentTray()
}
case .openTopSites:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.topSites.localhostURL) as URLRequest)
}
case .openBookmarks:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.bookmarks.localhostURL) as URLRequest)
}
case .openHistory:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.history.localhostURL) as URLRequest)
}
case .openReadingList:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.readingList.localhostURL) as URLRequest)
}
default: break
}
}
}
}
// MARK: - Toolbar
class TrayToolbar: UIView {
fileprivate let toolbarButtonSize = CGSize(width: 44, height: 44)
lazy var settingsButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("settings"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.settingsButton"
return button
}()
lazy var addTabButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("add"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.addTabButton"
return button
}()
lazy var menuButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("bottomNav-menu-pbm"), for: .normal)
button.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel
button.accessibilityIdentifier = "TabTrayController.menuButton"
return button
}()
lazy var maskButton: PrivateModeButton = PrivateModeButton()
fileprivate let sideOffset: CGFloat = 32
fileprivate override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(addTabButton)
var buttonToCenter: UIButton?
addSubview(menuButton)
buttonToCenter = menuButton
maskButton.accessibilityIdentifier = "TabTrayController.maskButton"
buttonToCenter?.snp.makeConstraints { make in
make.center.equalTo(self)
make.size.equalTo(toolbarButtonSize)
}
addTabButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.left.equalTo(self).offset(sideOffset)
make.size.equalTo(toolbarButtonSize)
}
addSubview(maskButton)
maskButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.right.equalTo(self).offset(-sideOffset)
make.size.equalTo(toolbarButtonSize)
}
styleToolbar(false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func styleToolbar(_ isPrivate: Bool) {
addTabButton.tintColor = isPrivate ? .white : .darkGray
menuButton.tintColor = isPrivate ? .white : .darkGray
backgroundColor = isPrivate ? UIConstants.PrivateModeToolbarTintColor : .white
maskButton.styleForMode(privateMode: isPrivate)
}
}
|
083187d6efbe1dcabc65dd8321d8b845
| 40.657978 | 304 | 0.673278 | false | false | false | false |
SerjKultenko/Calculator3
|
refs/heads/master
|
Calculator/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Calculator
//
// Created by Kultenko Sergey on 18.02.17.
// Copyright © 2017 Sergey Kultenko. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
guard
let splitViewController = self.window?.rootViewController as? UISplitViewController,
let leftNavController = splitViewController.viewControllers.first as? UINavigationController,
let calculatorViewController = leftNavController.topViewController as? CalculatorViewController,
let secondViewController = splitViewController.viewControllers.last,
let graphicViewController = secondViewController.contents as? GraphicViewController
else {
return true
}
calculatorViewController.loadCalculatorModel()
graphicViewController.graphDataSource = calculatorViewController.getGraphDataSource()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
e12cb52ce23176c5b9417b847f29a145
| 48.649123 | 285 | 0.74629 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
refs/heads/master
|
EnjoyUniversity/EnjoyUniversity/Classes/View/Main/EUMainViewController.swift
|
mit
|
1
|
//
// EUMainViewController.swift
// EnjoyUniversity
//
// Created by lip on 17/2/27.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
class EUMainViewController: UITabBarController {
// 子控制器数组
let childvcArray = [
["clsName":"Home","title":"首页","imageName":"home"],
["clsName":"Discover","title":"发现","imageName":"discover"],
["":""],
["clsName":"Message","title":"消息","imageName":"message_center"],
["clsName":"Profile","title":"我的","imageName":"profile"]
]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
delegate = self
setupChildViewController(vcarray: childvcArray)
setupPlusButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 初始化子控制器
extension EUMainViewController{
/// 根据字典创建控制器
fileprivate func createChiledViewController(dict:[String:String])->UIViewController{
guard let clsName = dict["clsName"],
let title = dict["title"],
let imageName = dict["imageName"],
let cls = NSClassFromString(Bundle.main.namespace+"." + "EU" + clsName + "ViewController") as? EUBaseViewController.Type
else {
return UIViewController()
}
let vc = cls.init()
vc.title = title
vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
let nav = EUNavigationController(rootViewController: vc)
return nav
}
/// 根据字典数组创建子控制器数组
fileprivate func setupChildViewController(vcarray:[[String:String]]){
var vcs = [UIViewController]()
for dict in vcarray{
vcs.append(createChiledViewController(dict: dict))
}
viewControllers = vcs
}
fileprivate func setupPlusButton(){
let btn = UIButton()
btn.setImage(UIImage(named: "tabbar_plus"), for: .normal)
let width = UIScreen.main.bounds.width / 5
let height = tabBar.bounds.height
btn.frame = CGRect(x: 2 * width, y: 0, width: width, height: height)
btn.addTarget(self, action: #selector(plusButtonWasClicked), for: .touchUpInside)
tabBar.addSubview(btn)
}
}
// MARK: - 监听方法
extension EUMainViewController{
/// PlusButton 监听
@objc fileprivate func plusButtonWasClicked(){
let v = EUPlusButtonView()
v.showPlusButtonView { [weak v] (clsName) in
guard let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else{
v?.removeFromSuperview()
return
}
let vc = cls.init()
if let vc = vc as? EUMyActivityViewController{
vc.isFirstPageSelected = false
}
let nav = EUNavigationController(rootViewController: vc)
if clsName == "EUQRScanViewController" {
if !cameraPermissions(){
SwiftyProgressHUD.showBigFaildHUD(text: "无相机权限", duration: 1)
return
}
}
self.present(nav, animated: true, completion: {
v?.removeFromSuperview()
})
}
}
}
// MARK: - 代理方法
extension EUMainViewController:UITabBarControllerDelegate{
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let nextIndex = (childViewControllers as NSArray).index(of: viewController)
// 本来就在首页,再点一次应该刷新
if selectedIndex == 0 && selectedIndex == nextIndex{
print("刷新首页")
let homenvc = childViewControllers.first as! UINavigationController
let homevc = homenvc.childViewControllers.first as! EUHomeViewController
homevc.tableview.setContentOffset(CGPoint(x: 0, y: -60), animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
homevc.loadData()
})
}else if selectedIndex == 1 && selectedIndex == nextIndex{
let communitynav = childViewControllers[1] as! UINavigationController
let communityvc = communitynav.childViewControllers.first as! EUDiscoverViewController
communityvc.tableview.setContentOffset(CGPoint(x: 0, y: -124), animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
communityvc.loadData()
})
}
return true
}
}
|
3e2dc30df0228ef778f07cfabc711ffc
| 30.317647 | 132 | 0.582645 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.