repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
giginet/Toybox | Sources/ToyboxKit/PlaygroundBuilder.swift | 1 | 2426 | import Foundation
private func metadata(version: String, platform: Platform) -> String {
let targetPlatform = String(describing: platform).lowercased()
return """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='\(version)' target-platform='\(targetPlatform)'>
<timeline fileName='timeline.xctimeline'/>
</playground>
"""
}
private let defaultContent = """
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
"""
private let defaultContentForMac = """
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
"""
private func defaultContent(for platform: Platform) -> Data {
let content: String
switch platform {
case .iOS, .tvOS:
content = defaultContent
case .macOS:
content = defaultContentForMac
}
return content.data(using: .utf8)!
}
class PlaygroundBuilder {
private let metadataFileName = "contents.xcplayground"
private let contentsFileName = "Contents.swift"
private let fileManager: FileManager = .default
private let playgroundVersion = "5.0.0"
enum Error: Swift.Error {
case invalidPath(URL)
case creationFailure
}
func build(for platform: Platform, to destination: URL) throws -> URL {
do {
try fileManager.createDirectory(at: destination, withIntermediateDirectories: false, attributes: nil)
} catch {
throw Error.invalidPath(destination)
}
let metadataURL = destination.appendingPathComponent(metadataFileName)
let metadataContent = metadata(version: playgroundVersion, platform: platform).data(using: .utf8)
guard fileManager.createFile(atPath: metadataURL.path,
contents: metadataContent,
attributes: nil) else {
throw Error.creationFailure
}
let contentsURL = destination.appendingPathComponent(contentsFileName)
let contentData = defaultContent(for: platform)
guard fileManager.createFile(atPath: contentsURL.path,
contents: contentData,
attributes: nil) else {
throw Error.creationFailure
}
return destination
}
}
| mit | 83dd1eb5b519886f0ef8276f861657ad | 31.346667 | 113 | 0.625721 | 5.002062 | false | false | false | false |
HaloWang/SwiftFFNN | FFNN/ViewController.swift | 1 | 926 | //
// ViewController.swift
// FFNN
//
// Created by 王策 on 16/7/3.
// Copyright © 2016年 王策. All rights reserved.
//
import UIKit
import SwiftyJSON
class ViewController: UIViewController {
let ffnn = FFNN(inputCount: 3, hiddenCount: 5, outputCount: 1)
override func viewDidLoad() {
super.viewDidLoad()
let data = DataGenerator.generateItems(1000)
for (index, item) in data.enumerated() {
_ = ffnn.update([item.male, item.single, item.age])
ffnn.backpropagate([item.frequency])
if index % 10 == 0 {
let testData = DataGenerator.getPerson()
let result = ffnn.update([testData.male, testData.single, testData.age])
let answer = testData.frequency
print(result[0] - answer)
}
}
_ = DataGenerator.getPerson()
}
}
| mit | 2754bddf7d72e19cbbc5a3d33e5079c1 | 24.416667 | 88 | 0.562842 | 4.030837 | false | true | false | false |
cruinh/CuriosityPhotos | CuriosityRover/PhotoViewController.swift | 1 | 2279 | //
// PhotoViewController.swift
// CuriosityRover
//
// Created by Matt Hayes on 3/9/16.
//
//
import Foundation
import UIKit
class PhotoViewController: UIViewController, UIScrollViewDelegate {
weak var image: UIImage?
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var scrollView: UIScrollView?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var photoInfo: CuriosityRoverData.PhotoInfo?
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView?.minimumZoomScale = 1.0
self.scrollView?.maximumZoomScale = 6.0
populatePhoto()
refreshTitle()
}
func populatePhoto() {
if let imageURL = photoInfo?.img_src {
activityIndicator?.startAnimating()
CuriosityPhotoRepository.getImage(fromURL: imageURL, completion: { [weak self](image, error) -> Void in
guard self != nil else { print("self was nil: \(#file):\(#line)"); return }
if let image = image {
self!.imageView?.image = image
} else {
print("error: photo url invalid: \(imageURL)")
}
self!.activityIndicator?.stopAnimating()
})
} else {
print("error: photo url was nil")
}
}
func refreshTitle() {
var titleString = photoInfo?.camera?.name ?? ""
if let earthDate = photoInfo?.earth_date {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
titleString = titleString + " " + dateFormatter.string(from: earthDate as Date)
}
title = titleString
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? PhotoInfoController {
destinationViewController.photoInfo = self.photoInfo
}
}
@IBAction func dismiss(_ sender: UIButton?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
| mit | d660672096b665e7f34dabc8b0d25c6d | 28.597403 | 115 | 0.612111 | 5.042035 | false | false | false | false |
debugsquad/nubecero | nubecero/Model/AdminUsers/MAdminUsersItem.swift | 1 | 480 | import Foundation
class MAdminUsersItem
{
let userId:MSession.UserId
let created:TimeInterval
let lastSession:TimeInterval
let diskUsed:Int
let status:MSession.Status
init(userId:MSession.UserId, firebaseUser:FDatabaseModelUser)
{
self.userId = userId
created = firebaseUser.created
lastSession = firebaseUser.session.timestamp
diskUsed = firebaseUser.diskUsed
status = firebaseUser.session.status
}
}
| mit | 1ce3c13b00e86afda0855e905ef31a45 | 24.263158 | 65 | 0.704167 | 4.848485 | false | false | false | false |
tardieu/swift | test/decl/func/throwing_functions.swift | 10 | 5741 | // RUN: %target-typecheck-verify-swift
enum Exception : Error { case A }
// Basic syntax ///////////////////////////////////////////////////////////////
func bar() throws -> Int { return 0 }
func foo() -> Int { return 0 }
// Currying ///////////////////////////////////////////////////////////////////
func curry1() {
}
func curry1Throws() throws {
}
func curry2() -> () -> () {
return curry1
}
func curry2Throws() throws -> () -> () {
return curry1
}
func curry3() -> () throws -> () {
return curry1Throws
}
func curry3Throws() throws -> () throws -> () {
return curry1Throws
}
var a : () -> () -> () = curry2
var b : () throws -> () -> () = curry2Throws
var c : () -> () throws -> () = curry3
var d : () throws -> () throws -> () = curry3Throws
// Partial application ////////////////////////////////////////////////////////
protocol Parallelogram {
static func partialApply1(_ a: Int) throws
}
func partialApply2<T: Parallelogram>(_ t: T) {
_ = T.partialApply1
}
// Overload resolution/////////////////////////////////////////////////////////
func barG<T>(_ t : T) throws -> T { return t }
func fooG<T>(_ t : T) -> T { return t }
var bGE: (_ i: Int) -> Int = barG // expected-error{{invalid conversion from throwing function of type '(_) throws -> _' to non-throwing function type '(Int) -> Int'}}
var bg: (_ i: Int) throws -> Int = barG
var fG: (_ i: Int) throws -> Int = fooG
func fred(_ callback: (UInt8) throws -> ()) throws { }
func rachel() -> Int { return 12 }
func donna(_ generator: () throws -> Int) -> Int { return generator() } // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}}
_ = donna(rachel)
func barT() throws -> Int { return 0 } // expected-note{{}}
func barT() -> Int { return 0 } // expected-error{{invalid redeclaration of 'barT()'}}
func fooT(_ callback: () throws -> Bool) {} //OK
func fooT(_ callback: () -> Bool) {}
// Throwing and non-throwing types are not equivalent.
struct X<T> { }
func specializedOnFuncType1(_ x: X<(String) throws -> Int>) { }
func specializedOnFuncType2(_ x: X<(String) -> Int>) { }
func testSpecializedOnFuncType(_ xThrows: X<(String) throws -> Int>,
xNonThrows: X<(String) -> Int>) {
specializedOnFuncType1(xThrows) // ok
specializedOnFuncType1(xNonThrows) // expected-error{{cannot convert value of type 'X<(String) -> Int>' to expected argument type 'X<(String) throws -> Int>'}}
specializedOnFuncType2(xThrows) // expected-error{{cannot convert value of type 'X<(String) throws -> Int>' to expected argument type 'X<(String) -> Int>'}}
specializedOnFuncType2(xNonThrows) // ok
}
// Subtyping
func subtypeResult1(_ x: (String) -> ((Int) -> String)) { }
func testSubtypeResult1(_ x1: (String) -> ((Int) throws -> String),
x2: (String) -> ((Int) -> String)) {
subtypeResult1(x1) // expected-error{{cannot convert value of type '(String) -> ((Int) throws -> String)' to expected argument type '(String) -> ((Int) -> String)'}}
subtypeResult1(x2)
}
func subtypeResult2(_ x: (String) -> ((Int) throws -> String)) { }
func testSubtypeResult2(_ x1: (String) -> ((Int) throws -> String),
x2: (String) -> ((Int) -> String)) {
subtypeResult2(x1)
subtypeResult2(x2)
}
func subtypeArgument1(_ x: (_ fn: ((String) -> Int)) -> Int) { }
func testSubtypeArgument1(_ x1: (_ fn: ((String) -> Int)) -> Int,
x2: (_ fn: ((String) throws -> Int)) -> Int) {
subtypeArgument1(x1)
subtypeArgument1(x2)
}
func subtypeArgument2(_ x: (_ fn: ((String) throws -> Int)) -> Int) { }
func testSubtypeArgument2(_ x1: (_ fn: ((String) -> Int)) -> Int,
x2: (_ fn: ((String) throws -> Int)) -> Int) {
subtypeArgument2(x1) // expected-error{{cannot convert value of type '(((String) -> Int)) -> Int' to expected argument type '(((String) throws -> Int)) -> Int'}}
subtypeArgument2(x2)
}
// Closures
var c1 = {() throws -> Int in 0}
var c2 : () throws -> Int = c1 // ok
var c3 : () -> Int = c1 // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c4 : () -> Int = {() throws -> Int in 0} // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c5 : () -> Int = { try c2() } // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c6 : () throws -> Int = { do { _ = try c2() } ; return 0 }
var c7 : () -> Int = { do { try c2() } ; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c8 : () -> Int = { do { _ = try c2() } catch _ { var x = 0 } ; return 0 } // expected-warning {{initialization of variable 'x' was never used; consider replacing with assignment to '_' or removing it}}
var c9 : () -> Int = { do { try c2() } catch Exception.A { var x = 0 } ; return 0 }// expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c10 : () -> Int = { throw Exception.A; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c11 : () -> Int = { try! c2() }
var c12 : () -> Int? = { try? c2() }
// Initializers
struct A {
init(doomed: ()) throws {}
}
func fi1() throws {
A(doomed: ()) // expected-error {{call can throw but is not marked with 'try'}} // expected-warning{{unused}}
}
struct B {
init() throws {}
init(foo: Int) {}
}
B(foo: 0) // expected-warning{{unused}}
| apache-2.0 | 103c350b946fbfbd8f98e370557846f9 | 40.007143 | 213 | 0.57969 | 3.532923 | false | false | false | false |
spacedrabbit/FollowButtonConcept | FollowButtonConcept/ProfileViewController.swift | 1 | 3542 | //
// ViewController.swift
// FollowButtonConcept
//
// Created by Louis Tur on 5/3/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
import UIKit
import SnapKit
internal struct ConceptColors {
static let LightBlue: UIColor = UIColor(colorLiteralRed: 130.0/255.0, green: 222.0/255.0, blue: 255.0/255.0, alpha: 1.0)
static let MediumBlue: UIColor = UIColor(colorLiteralRed: 113.0/255.0, green: 156.0/255.0, blue: 255.0/255.0, alpha: 1.0)
static let OffWhite: UIColor = UIColor(colorLiteralRed: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1.0)
static let DarkText: UIColor = UIColor(colorLiteralRed: 100.0/255.0, green: 100.0/255.0, blue: 150.0/255.0, alpha: 1.0)
}
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.grayColor()
self.setupViewHierarchy()
self.configureConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.followButton.updateCornerRadius()
self.drawGradientIn(self.profileTopSectionView)
}
// MARK: - UI Updates
// ------------------------------------------------------------
internal func drawGradientIn(view: UIView) {
self.view.layoutIfNeeded()
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [ConceptColors.LightBlue.CGColor, ConceptColors.MediumBlue.CGColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPointMake(0.0, 0.0)
gradientLayer.endPoint = CGPointMake(1.0, 1.0)
view.layer.addSublayer(gradientLayer)
}
// MARK: - Layout
internal func configureConstraints() {
self.profileBackgroundView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view).offset(60.0)
make.left.equalTo(self.view).offset(22.0)
make.right.equalTo(self.view).inset(22.0)
make.bottom.equalTo(self.view).inset(60.0)
}
self.profileTopSectionView.snp_makeConstraints { (make) -> Void in
make.top.left.right.equalTo(self.profileBackgroundView)
make.bottom.equalTo(self.profileBottomSectionView.snp_top)
}
self.profileBottomSectionView.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.profileBackgroundView)
make.top.equalTo(self.profileBackgroundView.snp_centerY).multipliedBy(1.30)
}
self.followButton.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self.profileBottomSectionView.snp_top)
make.centerX.equalTo(self.profileBottomSectionView)
make.height.width.greaterThanOrEqualTo(0.0).priority(990.0)
}
}
internal func setupViewHierarchy() {
self.view.addSubview(profileBackgroundView)
self.profileBackgroundView.addSubview(self.profileTopSectionView)
self.profileBackgroundView.addSubview(self.profileBottomSectionView)
self.profileBackgroundView.addSubview(self.followButton)
}
// MARK: - Lazy Instances
lazy var profileBackgroundView: UIView = {
let view: UIView = UIView()
view.layer.cornerRadius = 12.0
view.clipsToBounds = true
return view
}()
lazy var profileTopSectionView: UIView = {
let view: UIView = UIView()
return view
}()
lazy var profileBottomSectionView: UIView = {
let view: UIView = UIView()
view.backgroundColor = ConceptColors.OffWhite
return view
}()
lazy var followButton: FollowButton = FollowButton()
}
| mit | d1bd9f89c9ffb26a366fa90463e9eec5 | 32.093458 | 123 | 0.699238 | 3.943207 | false | false | false | false |
dabing1022/AlgorithmRocks | Books/TheArtOfProgrammingByJuly.playground/Pages/1-1 RotateString.xcplaygroundpage/Contents.swift | 1 | 2200 | //: [Previous](@previous)
/*:
给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。
*/
/*: 暴力移位法 */
class Solution {
func leftShiftOne(var string: [Character], length: Int) -> [Character] {
if let firstCharacter = string.first {
for i in 1..<length {
string[i - 1] = string[i]
}
string[length - 1] = firstCharacter
}
return string
}
func leftRotateString(string: [Character], length: Int, var m: Int) -> [Character] {
var resultString = string
while (m > 0) {
resultString = leftShiftOne(resultString, length: string.count)
m = m - 1
}
return resultString
}
}
var string: [Character] = ["I", "L", "O", "V", "E", "Y", "O", "U"]
var string2: [Character] = []
Solution().leftShiftOne(string, length: string.count)
Solution().leftShiftOne(string2, length: string.count)
Solution().leftRotateString(string, length: string.count, m: 7)
/*: 三步反转法 */
class Solution2 {
func reverseString(var string: [Character], var from: Int, var to: Int) -> [Character] {
while (from < to) {
let tmp = string[from]
string[from++] = string[to]
string[to--] = tmp
}
return string
}
func leftRotateString(string: [Character], length: Int, var m: Int) -> [Character] {
m %= length
var resultString = string
resultString = reverseString(resultString, from: 0, to: m - 1)
resultString = reverseString(resultString, from: m, to: length - 1)
resultString = reverseString(resultString, from: 0, to: length - 1)
return resultString
}
}
Solution2().reverseString(string, from: 0, to: 2)
Solution2().leftRotateString(string, length: string.count, m: 7)
//: [Next](@next)
| mit | bc16467d4e6579205485460310826fe7 | 28.727273 | 139 | 0.581549 | 3.497326 | false | true | false | false |
mansoor92/MaksabComponents | MaksabComponents/Classes/Registeration/PhoneNumberAlertTemplateViewController.swift | 1 | 3138 | //
// PhoneNumberAlertViewController.swift
// Pods
//
// Created by Incubasys on 31/07/2017.
//
//
import UIKit
import StylingBoilerPlate
open class PhoneNumberAlertTemplateViewController: UIViewController, NibLoadableView {
@IBOutlet weak public var labelTitle: TitleLabel!
@IBOutlet weak public var labelDescription: TextLabel!
@IBOutlet weak public var fieldPhoneNumber: UITextField!
@IBOutlet weak public var fieldPhoneCode: UITextField!
@IBOutlet weak public var btnCancel: UIButton!
@IBOutlet weak public var btnRegister: UIButton!
@IBOutlet weak public var errorLbl: UILabel!
let bundle = Bundle(for: PhoneNumberAlertTemplateViewController.classForCoder())
override open func viewDidLoad() {
super.viewDidLoad()
labelTitle.text = Bundle.localizedStringFor(key: "phone-no-required")
labelDescription.text = Bundle.localizedStringFor(key: "phone-no-required-description")
btnCancel.setTitle(Bundle.localizedStringFor(key: "alert-action-Cancel"), for: .normal)
btnRegister.setTitle(Bundle.localizedStringFor(key: "phone-no-register"), for: .normal)
fieldPhoneNumber.placeholder = Bundle.localizedStringFor(key: "phone-no-enter-number")
fieldPhoneCode.text = Bundle.localizedStringFor(key: "phone-no-country-code")
errorLbl.textColor = UIColor.appColor(color: .Destructive)
errorLbl.font = UIFont.appFont(font: .RubikRegular, pontSize: 10)
fieldPhoneNumber.delegate = self
fieldPhoneCode.delegate = self
fieldPhoneCode.clearButtonMode = .never
fieldPhoneNumber.becomeFirstResponder()
}
@IBAction func actionCancel(_ sender: Any) {
self.view.endEditing(true)
cancelTapped()
}
func cancelTapped(){
self.dismiss(animated: true, completion: nil)
}
@IBAction func actionRegister(_ sender: UIButton) {
guard let phoneNo = getPhoneNo() else {
errorLbl.text = Bundle.localizedStringFor(key: "phone-no-must-be-twelve-digits")
fieldPhoneCode.shake()
fieldPhoneNumber.shake()
return
}
self.view.endEditing(true)
registerTapped(phoneNo: phoneNo)
}
open func registerTapped(phoneNo: String){}
public func getPhoneNo() -> String? {
return RegisterationTemplateViewController.getValidPhoneNoFrom(fieldCode: fieldPhoneCode, fieldPhoneNo: fieldPhoneNumber)
}
}
extension PhoneNumberAlertTemplateViewController: UITextFieldDelegate{
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
errorLbl.text = ""
if textField == fieldPhoneCode{
return RegisterationTemplateViewController.handlePhoneCode(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
}else{
return RegisterationTemplateViewController.handlePhoneNumber(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
}
}
}
| mit | c311d3a6008653036686a4a58cac5760 | 37.740741 | 154 | 0.70204 | 4.988871 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/Session.swift | 1 | 2384 | //
// Session.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 1.3.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// Session keeps track of user choices within and between sessions
class Session
{
// ATTRIBUTES ---------------
static let instance = Session()
private static let KEY_ACCOUNT = "agricola_account"
private static let KEY_USERNAME = "agricola_username"
private static let KEY_PASSWORD = "agricola_password"
private static let KEY_PROJECT = "agricola_project"
private static let KEY_AVATAR = "agricola_avatar"
private static let KEY_BOOK = "agricola_book"
private var keyChain = KeychainSwift()
// COMPUTED PROPERTIES -------
var projectId: String?
{
get { return self[Session.KEY_PROJECT] }
set { self[Session.KEY_PROJECT] = newValue }
}
var avatarId: String?
{
get { return self[Session.KEY_AVATAR] }
set { self[Session.KEY_AVATAR] = newValue }
}
var bookId: String?
{
get { return self[Session.KEY_BOOK] }
set { self[Session.KEY_BOOK] = newValue }
}
var accountId: String?
{
get { return self[Session.KEY_ACCOUNT] }
set { self[Session.KEY_ACCOUNT] = newValue }
}
private(set) var userName: String?
{
get { return self[Session.KEY_USERNAME] }
set { self[Session.KEY_USERNAME] = newValue }
}
private(set) var password: String?
{
get { return self[Session.KEY_PASSWORD] }
set { self[Session.KEY_PASSWORD] = newValue }
}
// Whether the current session is authorized (logged in)
var isAuthorized: Bool { return userName != nil && password != nil && accountId != nil}
// INIT -----------------------
private init()
{
// Instance accessed statically
}
// SUBSCRIPT ---------------
private subscript(key: String) -> String?
{
get { return keyChain.get(key) }
set
{
print("STATUS: Session changed: \(key) = \(newValue.or("empty"))")
if let newValue = newValue
{
keyChain.set(newValue, forKey: key)
}
else
{
keyChain.delete(key)
}
}
}
// OTHER METHODS -----------
// Notice that this is the couchbase username, not the one typed by the user
func logIn(accountId: String, userName: String, password: String)
{
self.accountId = accountId
self.userName = userName
self.password = password
}
func logout()
{
self.password = nil
self.userName = nil
self.accountId = nil
}
}
| mit | e85215967ac296ccfa49704442d05a84 | 19.903509 | 88 | 0.6517 | 3.277854 | false | false | false | false |
darthpelo/SurviveAmsterdam | mobile/Pods/QuadratTouch/Source/Shared/Endpoints/Endpoint.swift | 3 | 2807 | //
// Endpoint.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public func +=<K, V> (inout left: Dictionary<K, V>, right: Dictionary<K, V>?) -> Dictionary<K, V> {
if right != nil {
for (k, v) in right! {
left.updateValue(v, forKey: k)
}
}
return left
}
public class Endpoint {
weak var session : Session?
private let baseURL : NSURL
var endpoint: String {
return ""
}
init(session: Session) {
self.session = session
self.baseURL = NSURL(string:session.configuration.server.apiBaseURL) as NSURL!
}
func getWithPath(path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
return self.taskWithPath(path, parameters: parameters, HTTPMethod: "GET", completionHandler: completionHandler)
}
func postWithPath(path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
return self.taskWithPath(path, parameters: parameters, HTTPMethod: "POST", completionHandler: completionHandler)
}
func uploadTaskFromURL(fromURL: NSURL, path: String,
parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
let request = self.requestWithPath(path, parameters: parameters, HTTPMethod: "POST")
let task = UploadTask(session: self.session!, request: request, completionHandler: completionHandler)
task.fileURL = fromURL
return task
}
private func taskWithPath(path: String, parameters: Parameters?,
HTTPMethod: String, completionHandler: ResponseClosure?) -> Task {
let request = self.requestWithPath(path, parameters: parameters, HTTPMethod: HTTPMethod)
return DataTask(session: self.session!, request: request, completionHandler: completionHandler)
}
private func requestWithPath(path: String, parameters: Parameters?, HTTPMethod: String) -> Request {
var sessionParameters = session!.configuration.parameters()
if sessionParameters[Parameter.oauth_token] == nil {
do {
let accessToken = try session!.keychain.accessToken()
if let accessToken = accessToken {
sessionParameters[Parameter.oauth_token] = accessToken
}
} catch {
}
}
let request = Request(baseURL: self.baseURL, path: (self.endpoint + "/" + path),
parameters: parameters, sessionParameters: sessionParameters, HTTPMethod: HTTPMethod)
request.timeoutInterval = session!.configuration.timeoutInterval
return request
}
}
| mit | e2e3ee3765d7ee456929f4900886adc6 | 37.986111 | 120 | 0.63876 | 4.907343 | false | false | false | false |
hhroc/yellr-ios | Yellr/Yellr/PollViewController.swift | 1 | 7022 | //
// PollViewController.swift
// Yellr
//
// Created by Debjit Saha on 8/9/15.
// Copyright (c) 2015 wxxi. All rights reserved.
//
import UIKit
class PollViewController : UIViewController, UIScrollViewDelegate {
@IBOutlet weak var mediaContainer: UIScrollView!
@IBOutlet weak var pollQuestionLabel: UILabel!
var pollOptionsTrack = [Int:Bool]()
var pollQuestion: String = ""
var pollOptions = [String]()
var pollId:Int = 0
var pollOptionSelectedTag:Int = 0
var latitude:String = ""
var longitude:String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.mediaContainer.delegate = self;
self.mediaContainer.scrollEnabled = true;
self.mediaContainer.showsVerticalScrollIndicator = true
self.mediaContainer.indicatorStyle = .Default
self.setupPoll()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func viewDidLayoutSubviews() {
self.mediaContainer.contentSize = CGSize(width:self.mediaContainer.frame.width, height: 600)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func cancelTapped(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil);
}
@IBAction func submitTapped(sender: UIBarButtonItem) {
Yellr.println(pollOptionSelectedTag - 100200)
let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
spinningActivity.labelText = "Posting"
spinningActivity.userInteractionEnabled = false
if (pollOptionSelectedTag == 0) {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Please choose an option first")
} else {
post(["media_type":"text", "media_file":"text", "media_text":String(pollOptionSelectedTag - 100200)], method: "upload_media", latitude: self.latitude, longitude: self.longitude) { (succeeded: Bool, msg: String) -> () in
Yellr.println("Media Uploaded : " + msg)
if (msg != "NOTHING" && msg != "Error") {
post(["assignment_id":String(self.pollId), "media_objects":"[\""+msg+"\"]"], method:"publish_post", latitude:self.latitude, longitude:self.longitude) { (succeeded: Bool, msg: String) -> () in
Yellr.println("Post Added : " + msg)
if (msg != "NOTHING") {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
//TODO: show success
self.processPollDone("Thanks!")
//save used assignment ID / poll ID in UserPrefs to grey out used assignment item
let asdefaults = NSUserDefaults.standardUserDefaults()
var savedAssignmentIds = ""
if asdefaults.objectForKey(YellrConstants.Keys.RepliedToAssignments) == nil {
} else {
savedAssignmentIds = asdefaults.stringForKey(YellrConstants.Keys.RepliedToAssignments)!
}
asdefaults.setObject(savedAssignmentIds + "[" + String(self.pollId) + "]", forKey: YellrConstants.Keys.RepliedToAssignments)
asdefaults.synchronize()
} else {
//fail toast
Yellr.println("Poll + Text Upload failed")
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Failed! Please try again.")
}
}
} else {
Yellr.println("Text Upload failed")
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Failed! Please try again.")
}
}
}
}
//MARK: poll setup functions
func setupPoll() {
var button: UIButton!
var buttonPaddingTop: CGFloat
let buttonWidth: CGFloat = UIScreen.mainScreen().bounds.size.width - 35.0
Yellr.println(buttonWidth)
self.pollQuestionLabel.text = self.pollQuestion
self.pollQuestionLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.pollQuestionLabel.numberOfLines = 0
self.pollQuestionLabel.sizeToFit()
var i = 0;
for po in pollOptions {
buttonPaddingTop = 50.0 * CGFloat(i)
button = UIButton(type: UIButtonType.System)
button.setTitle(po, forState: UIControlState.Normal)
button.frame = CGRectMake(0.0, buttonPaddingTop, buttonWidth, 40.0)
button.addTarget(self, action: Selector("pollButtonTouched:"), forControlEvents: UIControlEvents.TouchUpInside)
button.tag = 100200 + i
pollOptionsTrack[button.tag] = false
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow)
button.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow).CGColor
self.mediaContainer.addSubview(button)
i++
//CGRectMake
}
}
func pollButtonTouched(sender: UIButton!) {
for (tag,status) in pollOptionsTrack {
let tmpButton = self.view.viewWithTag(tag) as? UIButton
tmpButton!.backgroundColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow)
tmpButton!.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow).CGColor
pollOptionsTrack[tag] = false
Yellr.println("\(status)")
}
pollOptionSelectedTag = sender.tag
pollOptionsTrack[sender.tag] = true
sender.backgroundColor = UIColorFromRGB(YellrConstants.Colors.dark_yellow)
sender.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.dark_yellow).CGColor
}
func processPollDone(mesg: String) {
let spinningActivityFail = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
spinningActivityFail.customView = UIView()
spinningActivityFail.mode = MBProgressHUDMode.CustomView
spinningActivityFail.labelText = mesg
//spinningActivityFail.yOffset = iOS8 ? 225 : 175
spinningActivityFail.hide(true, afterDelay: NSTimeInterval(2.5))
}
} | mit | 068f967b90b0ebefd6c0ca7d286f9235 | 42.08589 | 231 | 0.58986 | 5.103198 | false | false | false | false |
mibaldi/IOS_MIMO_APP | iosAPP/ingredients/IngredientsViewController.swift | 1 | 4405 | //
// IngredientsViewController.swift
// iosAPP
//
// Created by MIMO on 14/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import UIKit
class IngredientsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
@IBOutlet weak var categorias: UICollectionView!
let reuseIdentifier = "cell"
var items = [Dictionary<String,AnyObject>]()
var category = ""
var screenWidth = UIScreen.mainScreen().bounds.width
var screenHeight = UIScreen.mainScreen().bounds.height
var myLayout = UICollectionViewFlowLayout()
@IBOutlet weak var ingredientsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setText()
categoryInit()
myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
myLayout.minimumInteritemSpacing = 0
myLayout.minimumLineSpacing = 0
if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation){
screenWidth = UIScreen.mainScreen().bounds.width
screenHeight = UIScreen.mainScreen().bounds.height
print("POO")
myLayout.itemSize = CGSize(width:screenWidth/4 , height: screenHeight/3)
}else{
myLayout.itemSize = CGSize(width: screenWidth/3, height: screenHeight/5.5)
}
self.categorias.setCollectionViewLayout(myLayout, animated: false)
}
func setText(){
ingredientsLabel.text = NSLocalizedString("INGREDIENTS",comment:"Ingredientes")
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
screenWidth = UIScreen.mainScreen().bounds.width
screenHeight = UIScreen.mainScreen().bounds.height
if (toInterfaceOrientation.isLandscape){
myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
myLayout.minimumInteritemSpacing = 0
myLayout.minimumLineSpacing = 0
myLayout.itemSize = CGSize(width:screenHeight/4 , height: screenWidth/3)
}else{
myLayout.itemSize = CGSize(width: screenHeight/3, height: screenWidth/5.5)
}
self.categorias.setCollectionViewLayout(myLayout, animated: false)
}
func categoryInit(){
let filePath = NSBundle.mainBundle().pathForResource("Category", ofType: "json")
let jsonData = NSData.init(contentsOfFile: filePath!)
do {
let objOrigen = try NSJSONSerialization.JSONObjectWithData(jsonData!,
options: [.MutableContainers, .MutableLeaves]) as! [String:AnyObject]
for category in objOrigen["Categories"] as! [[String:AnyObject]] {
items.append(category)
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCollectionViewCell
cell.categoryLabel.text = self.items[indexPath.item]["category"] as? String
var image = self.items[indexPath.item]["image"] as! String
if(image == ""){
image = "Carne"
}
cell.image.image = UIImage(named: image)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
category = items[indexPath.row]["category"] as! String
performSegueWithIdentifier("ingredientsCategory", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let segueID = segue.identifier{
if segueID == "ingredientsCategory"{
if let destinoVC = segue.destinationViewController as? IngredientListViewController{
destinoVC.category = self.category
}
}
}
}
}
| apache-2.0 | 58a4ae04fc64cf3816041df0c760deb0 | 36.322034 | 145 | 0.64941 | 5.553594 | false | false | false | false |
kokuyoku82/NumSwift | NumSwift/Source/FFT.swift | 1 | 11893 | //
// Dear maintainer:
//
// When I wrote this code, only I and God
// know what it was.
// Now, only God knows!
//
// So if you are done trying to 'optimize'
// this routine (and failed),
// please increment the following counter
// as warning to the next guy:
//
// var TotalHoursWastedHere = 0
//
// Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
import Accelerate
/**
Complex-to-Complex Fast Fourier Transform.
- Note: we use radix-2 fft. As a result, it may process only partial input
data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns:
- `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func fft(realp:[Double], imagp: [Double]) -> (realp:[Double], imagp:[Double]) {
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputRealp = [Double](realp[0..<fftN])
var inputImagp = [Double](imagp[0..<fftN])
var fftCoefRealp = [Double](count: fftN, repeatedValue:0.0)
var fftCoefImagp = [Double](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD)
vDSP_DFT_ExecuteD(setup, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp)
// destroy setup.
vDSP_DFT_DestroySetupD(setup)
return (fftCoefRealp, fftCoefImagp)
}
/**
Complex-to-Complex Fast Fourier Transform.
- Note: that we use radix-2 fft. As a result, it may process only partial input
data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func fft(realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputRealp = [Float](realp[0..<fftN])
var inputImagp = [Float](imagp[0..<fftN])
var fftCoefRealp = [Float](count: fftN, repeatedValue:0.0)
var fftCoefImagp = [Float](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD)
vDSP_DFT_Execute(setup, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp)
// destroy setup.
vDSP_DFT_DestroySetup(setup)
return (fftCoefRealp, fftCoefImagp)
}
/**
Complex-to-Complex Inverse Fast Fourier Transform.
- Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process
only partial input data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func ifft(realp:[Double], imagp:[Double]) -> (realp:[Double], imagp:[Double]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputCoefRealp = [Double](realp[0..<fftN])
var inputCoefImagp = [Double](imagp[0..<fftN])
var outputRealp = [Double](count: fftN, repeatedValue:0.0)
var outputImagp = [Double](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE)
vDSP_DFT_ExecuteD(setup, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp)
// normalization of ifft
var scale = Double(fftN)
var normalizedOutputRealp = [Double](count: fftN, repeatedValue:0.0)
var normalizedOutputImagp = [Double](count: fftN, repeatedValue:0.0)
vDSP_vsdivD(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN))
vDSP_vsdivD(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN))
// destroy setup.
vDSP_DFT_DestroySetupD(setup)
return (normalizedOutputRealp, normalizedOutputImagp)
}
/**
Complex-to-Complex Inverse Fast Fourier Transform.
- Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process
only partial input data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func ifft(realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputCoefRealp = [Float](realp[0..<fftN])
var inputCoefImagp = [Float](imagp[0..<fftN])
var outputRealp = [Float](count: fftN, repeatedValue:0.0)
var outputImagp = [Float](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE)
defer {
// destroy setup.
vDSP_DFT_DestroySetup(setup)
}
vDSP_DFT_Execute(setup, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp)
// normalization of ifft
var scale = Float(fftN)
var normalizedOutputRealp = [Float](count: fftN, repeatedValue:0.0)
var normalizedOutputImagp = [Float](count: fftN, repeatedValue:0.0)
vDSP_vsdiv(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN))
vDSP_vsdiv(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN))
return (normalizedOutputRealp, normalizedOutputImagp)
}
/**
Convolution with Fast Fourier Transform
Perform convolution by Fast Fourier Transform
- Parameters:
- x: input array for convolution.
- y: input array for convolution.
- mode: mode of the convolution.
- "full": return full result (default).
- "same": return result with the same length as the longest input arrays between x and y.
- "valid": only return the result given for points where two arrays overlap completely.
- Returns: the result of the convolution of x and y.
*/
public func fft_convolve(x:[Double], y:[Double], mode:String = "full") -> [Double] {
var longArray:[Double]
var shortArray:[Double]
if x.count < y.count {
longArray = [Double](y)
shortArray = [Double](x)
} else {
longArray = [Double](x)
shortArray = [Double](y)
}
let N = longArray.count
let M = shortArray.count
let convN = N+M-1
let convNPowTwo = leastPowerOfTwo(convN)
longArray = pad(longArray, toLength:convNPowTwo, value:0.0)
shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0)
let zeros = [Double](count:convNPowTwo, repeatedValue:0.0)
var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros)
var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros)
// setup input buffers for vDSP_zvmulD
// long array:
var coefLongArrayComplex = DSPDoubleSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp)
// short array:
var coefShortArrayComplex = DSPDoubleSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp)
// setup output buffers for vDSP_zvmulD
var coefConvRealp = [Double](count:convNPowTwo, repeatedValue:0.0)
var coefConvImagp = [Double](count:convNPowTwo, repeatedValue:0.0)
var coefConvComplex = DSPDoubleSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp)
// Elementwise Complex Multiplication
vDSP_zvmulD(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1,
&coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1))
// ifft
var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp)
// Remove padded zeros
convResult = [Double](convResult[0..<convN])
// modify the result according mode before return
let finalResult:[Double]
switch mode {
case "same":
let numOfResultToBeRemoved = convN - N
let toBeRemovedHalf = numOfResultToBeRemoved / 2
if numOfResultToBeRemoved % 2 == 0 {
finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)])
} else {
finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)])
}
case "valid":
finalResult = [Double](convResult[(M-1)..<(convN-M+1)])
default:
finalResult = convResult
}
return finalResult
}
/**
Convolution with Fast Fourier Transform
Perform convolution by Fast Fourier Transform
- Parameters:
- x: input array for convolution.
- y: input array for convolution.
- mode: mode of the convolution.
- "full": return full result (default).
- "same": return result with the same length as the longest input array between x and y.
- "valid": only return the result given for points where two arrays overlap completely.
- Returns: the result of the convolution of x and y.
*/
public func fft_convolve(x:[Float], y:[Float], mode:String = "full") -> [Float] {
var longArray:[Float]
var shortArray:[Float]
if x.count < y.count {
longArray = [Float](y)
shortArray = [Float](x)
} else {
longArray = [Float](x)
shortArray = [Float](y)
}
let N = longArray.count
let M = shortArray.count
let convN = N+M-1
let convNPowTwo = leastPowerOfTwo(convN)
longArray = pad(longArray, toLength:convNPowTwo, value:0.0)
shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0)
let zeros = [Float](count:convNPowTwo, repeatedValue:0.0)
var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros)
var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros)
// setup input buffers for vDSP_zvmulD
// long array:
var coefLongArrayComplex = DSPSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp)
// short array:
var coefShortArrayComplex = DSPSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp)
// setup output buffers for vDSP_zvmulD
var coefConvRealp = [Float](count:convNPowTwo, repeatedValue:0.0)
var coefConvImagp = [Float](count:convNPowTwo, repeatedValue:0.0)
var coefConvComplex = DSPSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp)
// Elementwise Complex Multiplication
vDSP_zvmul(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1,
&coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1))
// ifft
var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp)
// Remove padded zeros
convResult = [Float](convResult[0..<convN])
// modify the result according mode before return
let finalResult:[Float]
switch mode {
case "same":
let numOfResultToBeRemoved = convN - N
let toBeRemovedHalf = numOfResultToBeRemoved / 2
if numOfResultToBeRemoved % 2 == 0 {
finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)])
} else {
finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)])
}
case "valid":
finalResult = [Float](convResult[(M-1)..<(convN-M+1)])
default:
finalResult = convResult
}
return finalResult
} | mit | 822606c356b3087a0538f42479ee24f9 | 31.233062 | 121 | 0.66434 | 3.662766 | false | false | false | false |
hooman/swift | test/SILOptimizer/invalid_escaping_captures.swift | 13 | 10207 | // RUN: %target-swift-frontend -emit-sil %s -verify
// RUN: %target-swift-frontend -emit-sil %s -verify
func takesEscaping(_: @escaping () -> ()) {}
func takesNonEscaping(_ fn: () -> ()) { fn() }
func badClosureCaptureInOut1(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
takesEscaping { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
}
}
func badClosureCaptureInOut2(x: inout Int, b: Bool) { // expected-note 2{{parameter 'x' is declared 'inout'}}
takesEscaping(b ? { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
} : { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x -= 1 // expected-note {{captured here}}
})
}
func badClosureCaptureNoEscape1(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
takesEscaping { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
}
}
func badClosureCaptureNoEscape2(y: () -> (), b: Bool) { // expected-note 2{{parameter 'y' is implicitly non-escaping}}
takesEscaping(b ? { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
} : { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
})
}
func badClosureCaptureNoEscape3(y: () -> ()) {
let yy = (y, y)
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
yy.0() // expected-note {{captured here}}
}
}
func badClosureCaptureNoEscape4(y: () -> (), z: () -> (), b: Bool) {
let x = b ? y : z
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
x() // expected-note {{captured here}}
}
}
func badLocalFunctionCaptureInOut1(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() {
x += 1 // expected-note {{captured here}}
}
takesEscaping(local) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
func badLocalFunctionCaptureInOut2(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() {
x += 1 // expected-note {{captured here}}
}
takesEscaping { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
local() // expected-note {{captured indirectly by this call}}
}
}
func badLocalFunctionCaptureInOut3(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local1() {
x += 1 // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
func badLocalFunctionCaptureNoEscape1(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local() {
y() // expected-note {{captured here}}
}
takesEscaping(local) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
func badLocalFunctionCaptureNoEscape2(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local() {
y() // expected-note {{captured here}}
}
takesEscaping { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
local() // expected-note {{captured indirectly by this call}}
}
}
func badLocalFunctionCaptureNoEscape3(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local1() {
y() // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
func badLocalFunctionCaptureNoEscape4(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local1() {
takesNonEscaping(y) // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
// Capturing 'self' produces a different diagnostic.
struct SelfCapture {
var a: Int
mutating func badLocalFunctionCaptureInOut() {
// FIXME: The 'captured here' location chosen here is not ideal, because
// the original closure is formed in a closure that is nested inside the
// local function. That's a funny edge case that trips up the heuristics.
func _foo() {
a += 1
takesEscaping { // expected-error {{escaping closure captures mutating 'self' parameter}}
_foo() // expected-note {{captured here}}
}
}
}
}
// Make sure reabstraction thunks don't cause problems.
func takesEscapingGeneric<T>(_: @escaping () -> T) {}
func testGenericClosureReabstraction(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
takesEscapingGeneric { () -> Int in // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
return 0
}
}
func testGenericLocalFunctionReabstraction(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() -> Int {
x += 1 // expected-note {{captured here}}
return 0
}
takesEscapingGeneric(local) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
// Make sure that withoutActuallyEscaping counts as a safe use.
func goodUseOfNoEscapeClosure(fn: () -> (), fn2: () -> ()) {
withoutActuallyEscaping(fn) { _fn in
takesEscaping(_fn)
}
}
// Some random regression tests
infix operator ~>
protocol Target {}
func ~> <Target, Arg0, Result>(x: inout Target, f: @escaping (_: inout Target, _: Arg0) -> Result) -> (Arg0) -> Result {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
return { f(&x, $0) } // expected-note {{captured here}}
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
}
func ~> (x: inout Int, f: @escaping (_: inout Int, _: Target) -> Target) -> (Target) -> Target {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
return { f(&x, $0) } // expected-note {{captured here}}
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
}
func addHandler(_: @escaping () -> ()) {}
public struct SelfEscapeFromInit {
public init() {
addHandler { self.handler() }
// expected-error@-1 {{escaping closure captures mutating 'self' parameter}}
// expected-note@-2 {{captured here}}
}
public mutating func handler() {}
}
func autoclosureTakesEscaping(_ x: @escaping @autoclosure () ->Int) {}
// Test that captures of escaping autoclosure are diagnosed correctly.
func badCaptureInAutoclosure(x: inout Int) {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
// expected-note@-2 {{parameter 'x' is declared 'inout'}}
autoclosureTakesEscaping(x)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
autoclosureTakesEscaping((x + 1) - 100)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
}
// Test that transitive captures in autoclosures are diagnosed correctly.
func badTransitiveCaptureInClosures(x: inout Int) -> ((Int) -> Void) {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
// expected-note@-2 {{parameter 'x' is declared 'inout'}}
// expected-note@-3 {{parameter 'x' is declared 'inout'}}
// Test capture of x by an autoclosure within a non-escaping closure.
let _ = { (y: Int) in
autoclosureTakesEscaping(x + y)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
}
// Test capture of x by an autoclosure within an escaping closure.
let escapingClosure = { (y: Int) in
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
autoclosureTakesEscaping(x + y)
// expected-note@-1 {{captured indirectly by this call}}
// expected-note@-2 {{captured here}}
// expected-error@-4 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-5 {{pass a copy of 'x'}}
}
return escapingClosure
}
// Test that captures of mutating 'self' in escaping autoclosures are diagnosed correctly.
struct S {
var i = 0
init() {
autoclosureTakesEscaping(i)
// expected-error@-1 {{escaping autoclosure captures mutating 'self' parameter}}
// expected-note@-2 {{pass a copy of 'self'}}
}
mutating func method() {
autoclosureTakesEscaping(i)
// expected-error@-1 {{escaping autoclosure captures mutating 'self' parameter}}
// expected-note@-2 {{pass a copy of 'self'}}
}
}
// Test that we look through the SILBoxType used for a 'var' binding
func badNoEscapeCaptureThroughVar(_ fn: () -> ()) {
var myFunc = fn // expected-warning {{never mutated}} // expected-note {{captured here}}
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
myFunc()
}
}
@inline(never)
func takeNoEscapeReturnGetter(f: ()->()->Int64) -> ()->Int64 { return f() }
// Test that invalid escaping capture diagnostics are run on nested
// closures before exclusivity diagnostics are run. Exclusivity
// diagnostics need to inspect all referenced closures that capture
// inouts. Also ensure that exclusivity diagnostics does not crash
// when verifying that a closure that captures inout does not escape
// as long as a previous diagnostic error is present.
struct TestInoutEscapeInClosure {
var someValue: Int64 = 0
mutating func testInoutEscapeInClosure() -> () -> Int64 {
return takeNoEscapeReturnGetter {
return { return someValue } // expected-error {{escaping closure captures mutating 'self' parameter}}
// expected-note@-1 {{captured here}}
}
}
}
| apache-2.0 | 71f7db69f03d5ff0ecee6d958b12d96b | 35.848375 | 120 | 0.660919 | 3.996476 | false | false | false | false |
cismet/belis-app | belis-app/SimpleInfoCell.swift | 1 | 3225 | //
// SimpleInfoCell.swift
// belis-app
//
// Created by Thorsten Hell on 16/03/15.
// Copyright (c) 2015 cismet. All rights reserved.
//
import Foundation
class SimpleInfoCell : UITableViewCell, CellDataUI {
func fillFromCellData(_ cellData: CellData) {
if let d=cellData as? SimpleInfoCellData{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.none
}else if let d=cellData as? SimpleInfoCellDataWithDetails{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.disclosureIndicator
}else if let d=cellData as? SimpleInfoCellDataWithDetailsDrivenByWholeObject{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.disclosureIndicator
}
}
func getPreferredCellHeight() -> CGFloat {
return CGFloat(44)
}
}
class SimpleInfoCellData : CellData {
var data: String
init(data:String){
self.data=data
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
}
class SimpleInfoCellDataWithDetails : CellData,SimpleCellActionProvider {
var data: String
var details: [String: [CellData]] = ["main":[]]
var sections: [String]
var actions: [BaseEntityAction]?
init(data:String,details:[String: [CellData]], sections: [String]){
self.data=data
self.details=details
self.sections=sections
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
@objc func action(_ vc:UIViewController) {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
detailVC.sections=sections
detailVC.setCellData(details)
vc.navigationController?.pushViewController(detailVC, animated: true)
}
}
class SimpleInfoCellDataWithDetailsDrivenByWholeObject : CellData,SimpleCellActionProvider {
var detailObject: BaseEntity?
var data: String
var showSubActions: Bool
//var mvc: MainViewController
init(data:String,detailObject: BaseEntity, showSubActions:Bool){
assert(detailObject is CellDataProvider)
self.data=data
self.detailObject=detailObject
self.showSubActions=showSubActions
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
@objc func action(_ vc:UIViewController) {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
detailVC.sections=(detailObject as! CellDataProvider).getDataSectionKeys()
detailVC.setCellData((detailObject as! CellDataProvider).getAllData())
detailVC.objectToShow=detailObject
if showSubActions {
if let actionProvider = detailObject as? ActionProvider {
let action = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: detailVC, action:#selector(DetailVC.moreAction))
detailVC.navigationItem.rightBarButtonItem = action
detailVC.actions=actionProvider.getAllActions()
}
}
vc.navigationController?.pushViewController(detailVC, animated: true)
}
}
| mit | 51c321c8cf171a68a207d4a10274522e | 27.539823 | 152 | 0.668837 | 4.708029 | false | false | false | false |
Prosumma/Parsimonious | Parsimonious/ParseError.swift | 1 | 4117 | //
// ParseError.swift
// Parsimonious
//
// Created by Gregory Higley on 2019-03-19.
// Copyright © 2019 Prosumma LLC.
//
// Licensed under the MIT license: https://opensource.org/licenses/MIT
// Permission is granted to use, copy, modify, and redistribute the work.
// Full license information available in the project LICENSE file.
//
import Foundation
/**
A marker protocol indicating a parsing error.
Combinators such as `|` look for this marker
protocol when deciding whether to handle the
error or rethrow it.
Parsimonious has only one class that implements
this protocol: `ParseError`.
See the documentation for `ParseError` on
the philosophy behind errors and error handling
in Parsimonious.
*/
public protocol ParsingError: Error {}
/**
An error that occurs as a result of parser failure.
There really only is one kind of parser failure: a parser was not satisfied.
_Why_ it was not satisfied is a mere detail, but there are really only two
possibilities. In the first case, something unexpected was encountered and
the parser failed to match. In the second case, EOF was encountered and the
parser failed to match. This is true even in the case of a `count` combinator
whose count was unsatisfied. If we say `count(7, parser)` but the underlying
parser was only matched 6 times, we must ask why it was only matched 6 times.
There are only two possibilites: something unexpected or EOF.
Why throw errors at all? A parser is a function with the signature
`(Context<C>) throws -> T`. The return type of a parser is the value matched,
so we indicate failure with an error. Instead of this, we might have defined
a parser as `(Context<C>) -> Result<T, Error>`. This certainly would have
worked, but the problem is the greater ceremony required to deal with it. It
is primarily for this reason that parsers throw errors. By throwing errors,
we can use much more natural syntax to backtrack when a parser fails, e.g.,
```
func match<C, T>(_ parsers: Parser<C, T>...) -> Parser<C, [T]> {
return transact { context in
var values: [T] = []
for parser in parsers {
try values.append(context <- parser)
}
return values
}
}
```
In the example above any error thrown by `try` simply escapes the current
scope and is propagated up. This is exactly what we want and is very
natural in Swift.
Parsers begin parsing at a certain position in the underlying collection.
When a parser fails, it rewinds to the position at which it started and
then throws a `ParseError`.
Some combinators swallow `ParseError`s. For instance, the `optional` combinator
swallows any underlying `ParseError` and returns an optional, e.g.,
```
let s: String? = try context <- optionalS(string("ok"))
```
If the string "ok" is not matched, then `s` will be `nil`. The `|` combinator
swallows the `ParseError` thrown by the left-hand side but not by the right-hand
side:
```
char("a") | char("e")
```
If the character "a" fails to match, then `|` will attempt to match "e", if that fails then
the `ParseError` will be allowed to propagate. Very often it is best to use the `fail` combinator
in this situation to make the error clearer:
```
char("a") | char("e") | fail("Tried and failed to match a or e.")
```
*/
public struct ParseError<Contents: Collection>: ParsingError {
/// An optional, purely informational message.
public let message: String?
/**
The index in the collection at which some parser failed
to match.
*/
public let index: Contents.Index
/// An inner error, if any.
public let inner: Error?
/**
Initializes a `ParseError`.
- parameter index: The index at which some parser failed to match.
- parameter message: An optional, purely informational message.
*/
public init(_ index: Contents.Index, message: String? = nil, inner: Error? = nil) {
self.index = index
self.message = message
self.inner = inner
}
}
public func <?><C: Collection, T>(parser: @escaping Parser<C, T>, error: String) -> Parser<C, T> {
parser | fail(error)
}
| mit | 94bff2e1600672f0c756e02119f2cf59 | 33.3 | 98 | 0.70724 | 4.031342 | false | false | false | false |
emersonbroga/LocationSwift | LocationSwift/BackgroundTaskManager.swift | 1 | 3015 | //
// BackgroundTaskManager.swift
// LocationSwift
//
// Created by Emerson Carvalho on 5/21/15.
// Copyright (c) 2015 Emerson Carvalho. All rights reserved.
//
import Foundation
import UIKit
class BackgroundTaskManager : NSObject {
var bgTaskIdList : NSMutableArray?
var masterTaskId : UIBackgroundTaskIdentifier?
override init() {
super.init()
self.bgTaskIdList = NSMutableArray()
self.masterTaskId = UIBackgroundTaskInvalid
}
class func sharedBackgroundTaskManager() -> BackgroundTaskManager? {
struct Static {
static var sharedBGTaskManager : BackgroundTaskManager?
static var onceToken : dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
Static.sharedBGTaskManager = BackgroundTaskManager()
}
return Static.sharedBGTaskManager
}
func beginNewBackgroundTask() -> UIBackgroundTaskIdentifier? {
var application : UIApplication = UIApplication.sharedApplication()
var bgTaskId : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
bgTaskId = application.beginBackgroundTaskWithExpirationHandler({
print("background task \(bgTaskId as Int) expired\n")
})
if self.masterTaskId == UIBackgroundTaskInvalid {
self.masterTaskId = bgTaskId
print("started master task \(self.masterTaskId)\n")
} else {
// add this ID to our list
print("started background task \(bgTaskId as Int)\n")
self.bgTaskIdList!.addObject(bgTaskId)
//self.endBackgr
}
return bgTaskId
}
func endBackgroundTask(){
self.drainBGTaskList(false)
}
func endAllBackgroundTasks() {
self.drainBGTaskList(true)
}
func drainBGTaskList(all:Bool) {
//mark end of each of our background task
var application: UIApplication = UIApplication.sharedApplication()
let endBackgroundTask : Selector = "endBackgroundTask"
var count: Int = self.bgTaskIdList!.count
for (var i = (all==true ? 0:1); i<count; i++) {
var bgTaskId : UIBackgroundTaskIdentifier = self.bgTaskIdList!.objectAtIndex(0) as! Int
print("ending background task with id \(bgTaskId as Int)\n")
application.endBackgroundTask(bgTaskId)
self.bgTaskIdList!.removeObjectAtIndex(0)
}
if self.bgTaskIdList!.count > 0 {
print("kept background task id \(self.bgTaskIdList!.objectAtIndex(0))\n")
}
if all == true {
print("no more background tasks running\n")
application.endBackgroundTask(self.masterTaskId!)
self.masterTaskId = UIBackgroundTaskInvalid
} else {
print("kept master background task id \(self.masterTaskId)\n")
}
}
} | mit | 87ad591ce5db5e8906a1e546b55ece11 | 30.416667 | 99 | 0.610282 | 5.162671 | false | false | false | false |
primetimer/PrimeFactors | PrimeFactors/Classes/PUtil.swift | 1 | 1471 | //
// PUtil.swift
// PFactors
//
// Created by Stephan Jancar on 17.10.17.
//
import Foundation
import BigInt
public extension BigUInt {
func issquare() -> Bool {
let r2 = self.squareRoot()
if r2 * r2 == self { return true }
return false
}
// Cubic Root
func iroot3()->BigUInt {
if self == 0 { return 0 }
if self < 8 { return 1 }
var x0 = self
var x1 = self
repeat {
x1 = self / x0 / x0
x1 = x1 + 2 * x0
x1 = x1 / 3
if (x0 == x1) || (x0 == x1+1) || (x1 == x0 + 1) {
if x1 * x1 * x1 > self {
return x1 - 1
}
return x1
}
x0 = x1
} while true
}
}
//Quadratwurzel und kubische Wurzel mittels Floating Point Arithmetik
public extension UInt64 {
func squareRoot()->UInt64 {
var r2 = UInt64(sqrt(Double(self)+0.5))
while (r2+1) * (r2+1) <= self {
r2 = r2 + 1
}
return r2
}
func issquare() -> Bool {
let r2 = self.squareRoot()
if r2 * r2 == self { return true }
return false
}
// Cubic Root
func iroot3()->UInt64 {
var r3 = UInt64(pow(Double(self)+0.5, 1.0 / 3.0))
while (r3+1) * (r3+1) * (r3+1) <= self {
r3 = r3 + 1
}
return r3
}
func NumBits() -> UInt64 {
var v = self
var c : UInt64 = 0
while v != 0 {
v = v & (v - 1) //Brian Kernighan's method
c = c + 1
}
return c
}
func greatestCommonDivisor(with b: UInt64) -> UInt64 {
var x = self
var y = b
while y > 0 {
let exc = x
x = y
y = exc % y
}
return x
}
}
| mit | 6dc202a10d245116a12bf4c704f7402a | 15.344444 | 69 | 0.537729 | 2.423394 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/NewCamera/Presenter/NewCameraPresenter.swift | 1 | 6078 | final class NewCameraPresenter:
NewCameraModule
{
// MARK: - Dependencies
private let interactor: NewCameraInteractor
private let router: NewCameraRouter
// MARK: - Config
private let shouldAllowFinishingWithNoPhotos: Bool
// MARK: - Init
init(
interactor: NewCameraInteractor,
router: NewCameraRouter,
shouldAllowFinishingWithNoPhotos: Bool)
{
self.interactor = interactor
self.router = router
self.shouldAllowFinishingWithNoPhotos = shouldAllowFinishingWithNoPhotos
}
// MARK: - Weak properties
weak var view: NewCameraViewInput? {
didSet {
setUpView()
}
}
// MARK: - NewCameraModule
var onFinish: ((NewCameraModule, NewCameraModuleResult) -> ())?
var configureMediaPicker: ((MediaPickerModule) -> ())?
func focusOnModule() {
router.focusOnCurrentModule()
}
// MARK: - Private
private func setUpView() {
view?.setFlashButtonVisible(interactor.isFlashAvailable)
view?.setFlashButtonOn(interactor.isFlashEnabled)
view?.setDoneButtonTitle(localized("Done"))
view?.setPlaceholderText(localized("Select at least one photo"))
view?.setHintText(localized("Place the object inside the frame and take a photo"))
view?.setAccessDeniedTitle(localized("To take photo"))
view?.setAccessDeniedMessage(localized("Allow %@ to use your camera", appName()))
view?.setAccessDeniedButtonTitle(localized("Allow access to camera"))
view?.onCloseButtonTap = { [weak self] in
guard let strongSelf = self else { return }
self?.onFinish?(strongSelf, .cancelled)
}
view?.onDoneButtonTap = { [weak self] in
guard let strongSelf = self else { return }
self?.onFinish?(strongSelf, .finished)
}
view?.onLastPhotoThumbnailTap = { [weak self] in
guard
let strongSelf = self,
let selectedItems = self?.interactor.selectedImagesStorage.images
else { return }
let data = strongSelf.interactor.mediaPickerData
.bySettingMediaPickerItems(selectedItems)
.bySelectingLastItem()
self?.router.showMediaPicker(
data: data,
overridenTheme: nil,
configure: { module in
self?.configureMediaPicker?(module)
}
)
}
view?.onToggleCameraButtonTap = { [weak self] in
self?.interactor.toggleCamera { _ in }
}
view?.onFlashToggle = { [weak self] isFlashEnabled in
guard let strongSelf = self else { return }
if !strongSelf.interactor.setFlashEnabled(isFlashEnabled) {
strongSelf.view?.setFlashButtonOn(!isFlashEnabled)
}
}
view?.onCaptureButtonTap = { [weak self] in
self?.view?.setCaptureButtonState(.nonInteractive)
self?.view?.animateFlash()
self?.interactor.takePhoto { photo in
guard let photo = photo else { return }
self?.interactor.selectedImagesStorage.addItem(MediaPickerItem(photo))
self?.adjustCaptureButtonAvailability()
self?.view?.animateCapturedPhoto(photo.image) { finalizeAnimation in
self?.adjustSelectedPhotosBar {
finalizeAnimation()
}
}
}
}
view?.onAccessDeniedButtonTap = {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
bindAdjustmentsToViewControllerLifecycle()
interactor.observeLatestLibraryPhoto { [weak self] imageSource in
self?.view?.setLatestPhotoLibraryItemImage(imageSource)
}
interactor.observeCameraAuthorizationStatus { [weak self] accessGranted in
self?.view?.setAccessDeniedViewVisible(!accessGranted)
}
}
private func bindAdjustmentsToViewControllerLifecycle() {
var didDisappear = false
var viewDidLayoutSubviewsBefore = false
view?.onViewWillAppear = { _ in
guard didDisappear else { return }
DispatchQueue.main.async {
self.adjustSelectedPhotosBar {}
self.adjustCaptureButtonAvailability()
}
}
view?.onViewDidDisappear = { _ in
didDisappear = true
}
view?.onViewDidLayoutSubviews = {
guard !viewDidLayoutSubviewsBefore else { return }
DispatchQueue.main.async {
self.adjustSelectedPhotosBar {}
}
viewDidLayoutSubviewsBefore = true
}
}
private func adjustSelectedPhotosBar(completion: @escaping () -> ()) {
let images = interactor.selectedImagesStorage.images
let state: SelectedPhotosBarState = images.isEmpty
? (shouldAllowFinishingWithNoPhotos ? .placeholder : .hidden)
: .visible(SelectedPhotosBarData(
lastPhoto: images.last?.image,
penultimatePhoto: images.count > 1 ? images[images.count - 2].image : nil,
countString: "\(images.count) фото"
))
view?.setSelectedPhotosBarState(state, completion: completion)
}
private func adjustCaptureButtonAvailability() {
view?.setCaptureButtonState(interactor.canAddItems() ? .enabled : .disabled)
}
private func appName() -> String {
return Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String ?? ""
}
}
| mit | e97f6e49c5f6eb6ef88c85102430c9fd | 33.511364 | 90 | 0.574745 | 5.582721 | false | false | false | false |
khizkhiz/swift | test/SILGen/decls.swift | 2 | 5762 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen %s | FileCheck %s
// CHECK-LABEL: sil hidden @_TF5decls11void_returnFT_T_
// CHECK: = tuple
// CHECK: return
func void_return() {
}
// CHECK-LABEL: sil hidden @_TF5decls14typealias_declFT_T_
func typealias_decl() {
typealias a = Int
}
// CHECK-LABEL: sil hidden @_TF5decls15simple_patternsFT_T_
func simple_patterns() {
_ = 4
var _ : Int
}
// CHECK-LABEL: sil hidden @_TF5decls13named_patternFT_Si
func named_pattern() -> Int {
var local_var : Int = 4
var defaulted_var : Int // Defaults to zero initialization
return local_var + defaulted_var
}
func MRV() -> (Int, Float, (), Double) {}
// CHECK-LABEL: sil hidden @_TF5decls14tuple_patternsFT_T_
func tuple_patterns() {
var (a, b) : (Int, Float)
// CHECK: [[AADDR1:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBA:%.*]] = project_box [[AADDR1]]
// CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[PBA]]
// CHECK: [[BADDR1:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBB:%.*]] = project_box [[BADDR1]]
// CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[PBB]]
var (c, d) = (a, b)
// CHECK: [[CADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBC:%.*]] = project_box [[CADDR]]
// CHECK: [[DADDR:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBD:%.*]] = project_box [[DADDR]]
// CHECK: copy_addr [[AADDR]] to [initialization] [[PBC]]
// CHECK: copy_addr [[BADDR]] to [initialization] [[PBD]]
// CHECK: [[EADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBE:%.*]] = project_box [[EADDR]]
// CHECK: [[FADDR:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBF:%.*]] = project_box [[FADDR]]
// CHECK: [[GADDR:%[0-9]+]] = alloc_box $()
// CHECK: [[HADDR:%[0-9]+]] = alloc_box $Double
// CHECK: [[PBH:%.*]] = project_box [[HADDR]]
// CHECK: [[EFGH:%[0-9]+]] = apply
// CHECK: [[E:%[0-9]+]] = tuple_extract {{.*}}, 0
// CHECK: [[F:%[0-9]+]] = tuple_extract {{.*}}, 1
// CHECK: [[H:%[0-9]+]] = tuple_extract {{.*}}, 2
// CHECK: store [[E]] to [[PBE]]
// CHECK: store [[F]] to [[PBF]]
// CHECK: store [[H]] to [[PBH]]
var (e,f,g,h) : (Int, Float, (), Double) = MRV()
// CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBI:%.*]] = project_box [[IADDR]]
// CHECK-NOT: alloc_box $Float
// CHECK: copy_addr [[AADDR]] to [initialization] [[PBI]]
// CHECK: [[B:%[0-9]+]] = load [[BADDR]]
// CHECK-NOT: store [[B]]
var (i,_) = (a, b)
// CHECK: [[JADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBJ:%.*]] = project_box [[JADDR]]
// CHECK-NOT: alloc_box $Float
// CHECK: [[KADDR:%[0-9]+]] = alloc_box $()
// CHECK-NOT: alloc_box $Double
// CHECK: [[J_K_:%[0-9]+]] = apply
// CHECK: [[J:%[0-9]+]] = tuple_extract {{.*}}, 0
// CHECK: [[K:%[0-9]+]] = tuple_extract {{.*}}, 2
// CHECK: store [[J]] to [[PBJ]]
var (j,_,k,_) : (Int, Float, (), Double) = MRV()
}
// CHECK-LABEL: sil hidden @_TF5decls16simple_arguments
// CHECK: bb0(%0 : $Int, %1 : $Int):
// CHECK: [[X:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: store %0 to [[PBX]]
// CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBY:%[0-9]+]] = project_box [[Y]]
// CHECK-NEXT: store %1 to [[PBY]]
func simple_arguments(x: Int, y: Int) -> Int {
var x = x
var y = y
return x+y
}
// CHECK-LABEL: sil hidden @_TF5decls14tuple_argument
// CHECK: bb0(%0 : $Int, %1 : $Float):
// CHECK: [[UNIT:%[0-9]+]] = tuple ()
// CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $())
func tuple_argument(x: (Int, Float, ())) {
}
// CHECK-LABEL: sil hidden @_TF5decls14inout_argument
// CHECK: bb0(%0 : $*Int, %1 : $Int):
// CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBX:%.*]] = project_box [[X_LOCAL]]
// CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBY:%[0-9]+]] = project_box [[YADDR]]
// CHECK: copy_addr [[PBY]] to [[PBX]]
func inout_argument(x: inout Int, y: Int) {
var y = y
x = y
}
var global = 42
// CHECK-LABEL: sil hidden @_TF5decls16load_from_global
func load_from_global() -> Int {
return global
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: [[VALUE:%[0-9]+]] = load [[ADDR]]
// CHECK: return [[VALUE]]
}
// CHECK-LABEL: sil hidden @_TF5decls15store_to_global
func store_to_global(x: Int) {
var x = x
global = x
// CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBX:%.*]] = project_box [[XADDR]]
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: copy_addr [[PBX]] to [[ADDR]]
// CHECK: return
}
struct S {
var x:Int
// CHECK-LABEL: sil hidden @_TFV5decls1SCf
init() {
x = 219
}
init(a:Int, b:Int) {
x = a + b
}
}
// CHECK-LABEL: StructWithStaticVar.init
// rdar://15821990 - Don't emit default value for static var in instance init()
struct StructWithStaticVar {
static var a : String = ""
var b : String = ""
init() {
}
}
// <rdar://problem/17405715> lazy property crashes silgen of implicit memberwise initializer
// CHECK-LABEL: // decls.StructWithLazyField.init
// CHECK-NEXT: sil hidden @_TFV5decls19StructWithLazyFieldC{{.*}} : $@convention(thin) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField {
struct StructWithLazyField {
lazy var once : Int = 42
let someProp = "Some value"
}
// <rdar://problem/21057425> Crash while compiling attached test-app.
// CHECK-LABEL: // decls.test21057425
func test21057425() {
var x = 0, y: Int = 0
}
func useImplicitDecls() {
_ = StructWithLazyField(once: 55)
}
| apache-2.0 | 0aed48a81ebf0f3c00eb54187f3a719d | 30.486339 | 166 | 0.567338 | 2.947315 | false | false | false | false |
sol/aeson | tests/JSONTestSuite/parsers/test_Freddy_20161018/test_Freddy/JSONDecodable.swift | 10 | 7789 | //
// JSONDecodable.swift
// Freddy
//
// Created by Matthew D. Mathias on 3/24/15.
// Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//
/// A protocol to provide functionality for creating a model object with a `JSON`
/// value.
public protocol JSONDecodable {
/// Creates an instance of the model with a `JSON` instance.
/// - parameter json: An instance of a `JSON` value from which to
/// construct an instance of the implementing type.
/// - throws: Any `JSON.Error` for errors derived from inspecting the
/// `JSON` value, or any other error involved in decoding.
init(json: JSON) throws
}
extension Double: JSONDecodable {
/// An initializer to create an instance of `Double` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Double` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
if case let .double(double) = json {
self = double
} else if case let .int(int) = json {
self = Double(int)
} else if case let .string(string) = json, let s = Double(string) {
self = s
} else {
throw JSON.Error.valueNotConvertible(value: json, to: Double.self)
}
}
}
extension Int: JSONDecodable {
/// An initializer to create an instance of `Int` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Int` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
if case let .double(double) = json, double <= Double(Int.max) {
self = Int(double)
} else if case let .int(int) = json {
self = int
} else if case let .string(string) = json, let int = Int(string) {
self = int
} else if case let .string(string) = json,
let double = Double(string),
let decimalSeparator = string.characters.index(of: "."),
let int = Int(String(string.characters.prefix(upTo: decimalSeparator))),
double == Double(int) {
self = int
} else {
throw JSON.Error.valueNotConvertible(value: json, to: Int.self)
}
}
}
extension String: JSONDecodable {
/// An initializer to create an instance of `String` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `String` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
switch json {
case let .string(string):
self = string
case let .int(int):
self = String(int)
case let .bool(bool):
self = String(bool)
case let .double(double):
self = String(double)
default:
throw JSON.Error.valueNotConvertible(value: json, to: String.self)
}
}
}
extension Bool: JSONDecodable {
/// An initializer to create an instance of `Bool` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Bool` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
guard case let .bool(bool) = json else {
throw JSON.Error.valueNotConvertible(value: json, to: Bool.self)
}
self = bool
}
}
extension RawRepresentable where RawValue: JSONDecodable {
/// An initializer to create an instance of `RawRepresentable` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `RawRepresentable` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
let raw = try json.decode(type: RawValue.self)
guard let value = Self(rawValue: raw) else {
throw JSON.Error.valueNotConvertible(value: json, to: Self.self)
}
self = value
}
}
internal extension JSON {
/// Retrieves a `[JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Array`.
/// - returns: An `Array` of `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getArray(from json: JSON) throws -> [JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Array.
guard case let .array(array) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Array<JSON>)
}
return array
}
/// Retrieves a `[String: JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Dictionary`.
/// - returns: An `Dictionary` of `String` mapping to `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getDictionary(from json: JSON) throws -> [String: JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, JSON>)
}
return dictionary
}
/// Attempts to decode many values from a descendant JSON array at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Array` of some type conforming to `JSONDecodable`.
/// - returns: An `Array` of `Decoded` elements.
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`, as
/// well as any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedArray<Decoded: JSONDecodable>(from json: JSON) throws -> [Decoded] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
// This implementation also doesn't do the `type = Type.self` trick.
return try getArray(from: json).map(Decoded.init)
}
/// Attempts to decode many values from a descendant JSON object at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Dictionary` of some type conforming to `JSONDecodable`.
/// - returns: A `Dictionary` of string keys and `Decoded` values.
/// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)` or
/// any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedDictionary<Decoded: JSONDecodable>(from json: JSON) throws -> [Swift.String: Decoded] {
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, Decoded>)
}
var decodedDictionary = Swift.Dictionary<String, Decoded>(minimumCapacity: dictionary.count)
for (key, value) in dictionary {
decodedDictionary[key] = try Decoded(json: value)
}
return decodedDictionary
}
}
| bsd-3-clause | 17f447fd476d7c2396875b6fcee87ab9 | 40.870968 | 125 | 0.61415 | 4.276771 | false | false | false | false |
anirudh24seven/wikipedia-ios | Wikipedia/Code/WMFTableOfContentsPresentationController.swift | 1 | 10452 | import UIKit
import Masonry
// MARK: - Delegate
@objc public protocol WMFTableOfContentsPresentationControllerTapDelegate {
func tableOfContentsPresentationControllerDidTapBackground(controller: WMFTableOfContentsPresentationController)
}
public class WMFTableOfContentsPresentationController: UIPresentationController {
var displaySide = WMFTableOfContentsDisplaySideLeft
var displayMode = WMFTableOfContentsDisplayModeModal
// MARK: - init
public required init(presentedViewController: UIViewController, presentingViewController: UIViewController?, tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate) {
self.tapDelegate = tapDelegate
super.init(presentedViewController: presentedViewController, presentingViewController: presentedViewController)
}
weak public var tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate?
public var minimumVisibleBackgroundWidth: CGFloat = 60.0
public var maximumTableOfContentsWidth: CGFloat = 300.0
public var closeButtonLeadingPadding: CGFloat = 10.0
public var closeButtonTopPadding: CGFloat = 0.0
public var statusBarEstimatedHeight: CGFloat = 20.0
// MARK: - Views
lazy var statusBarBackground: UIView = {
let view = UIView(frame: CGRect(x: CGRectGetMinX(self.containerView!.bounds), y: CGRectGetMinY(self.containerView!.bounds), width: CGRectGetWidth(self.containerView!.bounds), height: self.statusBarEstimatedHeight))
view.autoresizingMask = .FlexibleWidth
let statusBarBackgroundBottomBorder = UIView(frame: CGRectMake(CGRectGetMinX(view.bounds), CGRectGetMaxY(view.bounds), CGRectGetWidth(view.bounds), 0.5))
statusBarBackgroundBottomBorder.autoresizingMask = .FlexibleWidth
view.backgroundColor = UIColor.whiteColor()
statusBarBackgroundBottomBorder.backgroundColor = UIColor.lightGrayColor()
view.addSubview(statusBarBackgroundBottomBorder)
return view
}()
lazy var closeButton:UIButton = {
let button = UIButton(frame: CGRectZero)
button.setImage(UIImage(named: "close"), forState: UIControlState.Normal)
button.tintColor = UIColor.blackColor()
button.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)), forControlEvents: .TouchUpInside)
button.accessibilityHint = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-hint")
button.accessibilityLabel = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-label")
return button
}()
lazy var backgroundView :UIVisualEffectView = {
let view = UIVisualEffectView(frame: CGRectZero)
view.autoresizingMask = .FlexibleWidth
view.effect = UIBlurEffect(style: .Light)
view.alpha = 0.0
let tap = UITapGestureRecognizer.init()
tap.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)))
view.addGestureRecognizer(tap)
view.addSubview(self.statusBarBackground)
view.addSubview(self.closeButton)
return view
}()
func updateButtonConstraints() {
self.closeButton.mas_remakeConstraints({ make in
make.width.equalTo()(44)
make.height.equalTo()(44)
switch self.displaySide {
case WMFTableOfContentsDisplaySideLeft:
make.trailing.equalTo()(self.closeButton.superview!.mas_trailing).offset()(0 - self.closeButtonLeadingPadding)
if(self.traitCollection.verticalSizeClass == .Compact){
make.top.equalTo()(self.closeButtonTopPadding)
}else{
make.top.equalTo()(self.closeButtonTopPadding + self.statusBarEstimatedHeight)
}
break
case WMFTableOfContentsDisplaySideRight:
make.leading.equalTo()(self.closeButton.superview!.mas_leading).offset()(self.closeButtonLeadingPadding)
if(self.traitCollection.verticalSizeClass == .Compact){
make.top.equalTo()(self.closeButtonTopPadding)
}else{
make.top.equalTo()(self.closeButtonTopPadding + self.statusBarEstimatedHeight)
}
break
case WMFTableOfContentsDisplaySideCenter:
fallthrough
default:
make.leading.equalTo()(self.closeButton.superview!.mas_leading).offset()(self.closeButtonLeadingPadding)
make.bottom.equalTo()(self.closeButton.superview!.mas_bottom).offset()(self.closeButtonTopPadding)
}
return ()
})
}
func didTap(tap: UITapGestureRecognizer) {
self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self);
}
// MARK: - Accessibility
func togglePresentingViewControllerAccessibility(accessible: Bool) {
self.presentingViewController.view.accessibilityElementsHidden = !accessible
}
// MARK: - UIPresentationController
override public func presentationTransitionWillBegin() {
// Add the dimming view and the presented view to the heirarchy
self.backgroundView.frame = self.containerView!.bounds
self.containerView!.addSubview(self.backgroundView)
if(self.traitCollection.verticalSizeClass == .Compact){
self.statusBarBackground.hidden = true
}
updateButtonConstraints()
self.containerView!.addSubview(self.presentedView()!)
// Hide the presenting view controller for accessibility
self.togglePresentingViewControllerAccessibility(false)
switch displaySide {
case WMFTableOfContentsDisplaySideCenter:
self.presentedView()?.layer.cornerRadius = 10
self.presentedView()?.clipsToBounds = true
self.presentedView()?.layer.borderColor = UIColor.wmf_lightGrayColor().CGColor
self.presentedView()?.layer.borderWidth = 1.0
self.closeButton.setImage(UIImage(named: "toc-close-blue"), forState: .Normal)
self.statusBarBackground.hidden = true
break
default:
//Add shadow to the presented view
self.presentedView()?.layer.shadowOpacity = 0.5
self.presentedView()?.layer.shadowOffset = CGSize(width: 3, height: 5)
self.presentedView()?.clipsToBounds = false
self.closeButton.setImage(UIImage(named: "close"), forState: .Normal)
self.statusBarBackground.hidden = false
}
// Fade in the dimming view alongside the transition
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 1.0
}, completion:nil)
}
}
override public func presentationTransitionDidEnd(completed: Bool) {
if !completed {
self.backgroundView.removeFromSuperview()
}
}
override public func dismissalTransitionWillBegin() {
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 0.0
}, completion:nil)
}
}
override public func dismissalTransitionDidEnd(completed: Bool) {
if completed {
self.backgroundView.removeFromSuperview()
self.togglePresentingViewControllerAccessibility(true)
self.presentedView()?.layer.cornerRadius = 0
self.presentedView()?.layer.borderWidth = 0
self.presentedView()?.layer.shadowOpacity = 0
self.presentedView()?.clipsToBounds = true
}
}
override public func frameOfPresentedViewInContainerView() -> CGRect {
var frame = self.containerView!.bounds;
var bgWidth = self.minimumVisibleBackgroundWidth
var tocWidth = frame.size.width - bgWidth
if(tocWidth > self.maximumTableOfContentsWidth){
tocWidth = self.maximumTableOfContentsWidth
bgWidth = frame.size.width - tocWidth
}
frame.origin.y = UIApplication.sharedApplication().statusBarFrame.size.height + 0.5;
switch displaySide {
case WMFTableOfContentsDisplaySideCenter:
frame.origin.y += 10
frame.origin.x += 0.5*bgWidth
frame.size.height -= 80
break
case WMFTableOfContentsDisplaySideRight:
frame.origin.x += bgWidth
break
default:
break
}
frame.size.width = tocWidth
return frame
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator)
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.frame = self.containerView!.bounds
let frame = self.frameOfPresentedViewInContainerView()
self.presentedView()!.frame = frame
}, completion:nil)
}
override public func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
if newCollection.verticalSizeClass == .Compact
{
self.statusBarBackground.hidden = true;
}
if newCollection.verticalSizeClass == .Regular
{
self.statusBarBackground.hidden = false;
}
coordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.updateButtonConstraints()
}, completion:nil)
}
}
| mit | cf06099a647273e71985c7a24f1bde2d | 41.661224 | 222 | 0.676713 | 6.319226 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift | 9 | 5407 | //
// AnimatedImage.swift
// Kingfisher
//
// Created by onevcat on 2018/09/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 ImageIO
/// Represents a set of image creating options used in Kingfisher.
public struct ImageCreatingOptions {
/// The target scale of image needs to be created.
public let scale: CGFloat
/// The expected animation duration if an animated image being created.
public let duration: TimeInterval
/// For an animated image, whether or not all frames should be loaded before displaying.
public let preloadAll: Bool
/// For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
public let onlyFirstFrame: Bool
/// Creates an `ImageCreatingOptions` object.
///
/// - Parameters:
/// - scale: The target scale of image needs to be created. Default is `1.0`.
/// - duration: The expected animation duration if an animated image being created.
/// A value less or equal to `0.0` means the animated image duration will
/// be determined by the frame data. Default is `0.0`.
/// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
/// Default is `false`.
/// - onlyFirstFrame: For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
/// Default is `false`.
public init(
scale: CGFloat = 1.0,
duration: TimeInterval = 0.0,
preloadAll: Bool = false,
onlyFirstFrame: Bool = false)
{
self.scale = scale
self.duration = duration
self.preloadAll = preloadAll
self.onlyFirstFrame = onlyFirstFrame
}
}
// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
// hold the images for later use.
class GIFAnimatedImage {
let images: [Image]
let duration: TimeInterval
init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else {
return nil
}
if frameCount == 1 {
gifDuration = .infinity
} else {
// Get current animated GIF frame duration
gifDuration += GIFAnimatedImage.getFrameDuration(from: imageSource, at: i)
}
images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
if options.onlyFirstFrame { break }
}
self.images = images
self.duration = gifDuration
}
// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
let defaultFrameDuration = 0.1
guard let gifInfo = gifInfo else { return defaultFrameDuration }
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else { return defaultFrameDuration }
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
}
// Calculates frame duration at a specific index for a gif from an `imageSource`.
static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
as? [String: Any] else { return 0.0 }
let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
return getFrameDuration(from: gifInfo)
}
}
| mit | ad6ae39a441d5d589481e7b48b97b419 | 43.68595 | 109 | 0.674681 | 4.997227 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GroupCallSettingsController.swift | 1 | 47216 | //
// GroupCallSettingsController.swift
// Telegram
//
// Created by Mikhail Filimonov on 25/11/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import TelegramCore
import InAppSettings
import Postbox
import HotKey
import ColorPalette
private final class Arguments {
let sharedContext: SharedAccountContext
let toggleInputAudioDevice:(String?)->Void
let toggleOutputAudioDevice:(String?)->Void
let toggleInputVideoDevice:(String?)->Void
let finishCall:()->Void
let updateDefaultParticipantsAreMuted: (Bool)->Void
let updateSettings: (@escaping(VoiceCallSettings)->VoiceCallSettings)->Void
let checkPermission:()->Void
let showTooltip:(String)->Void
let switchAccount:(PeerId)->Void
let startRecording:()->Void
let stopRecording:()->Void
let resetLink:()->Void
let setNoiseSuppression:(Bool)->Void
let reduceMotions:(Bool)->Void
let selectVideoRecordOrientation:(GroupCallSettingsState.VideoOrientation)->Void
let toggleRecordVideo: ()->Void
let copyToClipboard:(String)->Void
let toggleHideKey:()->Void
let revokeStreamKey: ()->Void
init(sharedContext: SharedAccountContext,
toggleInputAudioDevice: @escaping(String?)->Void,
toggleOutputAudioDevice:@escaping(String?)->Void,
toggleInputVideoDevice:@escaping(String?)->Void,
finishCall:@escaping()->Void,
updateDefaultParticipantsAreMuted: @escaping(Bool)->Void,
updateSettings: @escaping(@escaping(VoiceCallSettings)->VoiceCallSettings)->Void,
checkPermission:@escaping()->Void,
showTooltip: @escaping(String)->Void,
switchAccount: @escaping(PeerId)->Void,
startRecording: @escaping()->Void,
stopRecording: @escaping()->Void,
resetLink: @escaping()->Void,
setNoiseSuppression:@escaping(Bool)->Void,
reduceMotions:@escaping(Bool)->Void,
selectVideoRecordOrientation:@escaping(GroupCallSettingsState.VideoOrientation)->Void,
toggleRecordVideo: @escaping()->Void,
copyToClipboard:@escaping(String)->Void,
toggleHideKey:@escaping()->Void,
revokeStreamKey: @escaping()->Void) {
self.sharedContext = sharedContext
self.toggleInputAudioDevice = toggleInputAudioDevice
self.toggleOutputAudioDevice = toggleOutputAudioDevice
self.toggleInputVideoDevice = toggleInputVideoDevice
self.finishCall = finishCall
self.updateDefaultParticipantsAreMuted = updateDefaultParticipantsAreMuted
self.updateSettings = updateSettings
self.checkPermission = checkPermission
self.showTooltip = showTooltip
self.switchAccount = switchAccount
self.startRecording = startRecording
self.stopRecording = stopRecording
self.resetLink = resetLink
self.setNoiseSuppression = setNoiseSuppression
self.reduceMotions = reduceMotions
self.selectVideoRecordOrientation = selectVideoRecordOrientation
self.toggleRecordVideo = toggleRecordVideo
self.copyToClipboard = copyToClipboard
self.toggleHideKey = toggleHideKey
self.revokeStreamKey = revokeStreamKey
}
}
final class GroupCallSettingsView : View {
fileprivate let tableView:TableView = TableView()
private let titleContainer = View()
fileprivate let backButton: ImageButton = ImageButton()
private let title: TextView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(tableView)
addSubview(titleContainer)
titleContainer.addSubview(backButton)
titleContainer.addSubview(title)
let backColor = NSColor(srgbRed: 175, green: 170, blue: 172, alpha: 1.0)
title.userInteractionEnabled = false
title.isSelectable = false
let icon = #imageLiteral(resourceName: "Icon_NavigationBack").precomposed(backColor)
let activeIcon = #imageLiteral(resourceName: "Icon_NavigationBack").precomposed(backColor.withAlphaComponent(0.7))
backButton.set(image: icon, for: .Normal)
backButton.set(image: activeIcon, for: .Highlight)
_ = backButton.sizeToFit(.zero, NSMakeSize(24, 24), thatFit: true)
let layout = TextViewLayout.init(.initialize(string: strings().voiceChatSettingsTitle, color: GroupCallTheme.customTheme.textColor, font: .medium(.header)))
layout.measure(width: frame.width - 200)
title.update(layout)
tableView.getBackgroundColor = {
GroupCallTheme.windowBackground.withAlphaComponent(1)
}
updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
// super.updateLocalizationAndTheme(theme: theme)
backgroundColor = GroupCallTheme.windowBackground
titleContainer.backgroundColor = GroupCallTheme.windowBackground
title.backgroundColor = GroupCallTheme.windowBackground
}
override func layout() {
super.layout()
titleContainer.frame = NSMakeRect(0, 0, frame.width, 54)
tableView.frame = NSMakeRect(0, titleContainer.frame.maxY, frame.width, frame.height - titleContainer.frame.height)
backButton.centerY(x: 90)
let f = titleContainer.focus(title.frame.size)
title.setFrameOrigin(NSMakePoint(max(126, f.minX), f.minY))
}
}
struct GroupCallSettingsState : Equatable {
enum VideoOrientation : Equatable {
case landscape
case portrait
var rawValue: Bool {
switch self {
case .portrait:
return true
case .landscape:
return false
}
}
}
var hasPermission: Bool?
var title: String?
var displayAsList: [FoundPeer]?
var recordName: String?
var recordVideo: Bool
var videoOrientation: VideoOrientation
var hideKey: Bool = true
var credentials: GroupCallStreamCredentials?
}
private let _id_leave_chat = InputDataIdentifier.init("_id_leave_chat")
private let _id_reset_link = InputDataIdentifier.init("_id_reset_link")
private let _id_input_audio = InputDataIdentifier("_id_input_audio")
private let _id_output_audio = InputDataIdentifier("_id_output_audio")
private let _id_micro = InputDataIdentifier("_id_micro")
private let _id_speak_admin_only = InputDataIdentifier("_id_speak_admin_only")
private let _id_speak_all_members = InputDataIdentifier("_id_speak_all_members")
private let _id_input_mode_always = InputDataIdentifier("_id_input_mode_always")
private let _id_input_mode_ptt = InputDataIdentifier("_id_input_mode_ptt")
private let _id_ptt = InputDataIdentifier("_id_ptt")
private let _id_input_mode_ptt_se = InputDataIdentifier("_id_input_mode_ptt_se")
private let _id_input_mode_toggle = InputDataIdentifier("_id_input_mode_toggle")
private let _id_noise_suppression = InputDataIdentifier("_id_noise_suppression")
private let _id_server_url = InputDataIdentifier("_id_server_url")
private let _id_stream_key = InputDataIdentifier("_id_stream_key")
private let _id_revoke_stream_key = InputDataIdentifier("_id_revoke_stream_key")
private let _id_input_chat_title = InputDataIdentifier("_id_input_chat_title")
private let _id_input_record_title = InputDataIdentifier("_id_input_record_title")
private let _id_listening_link = InputDataIdentifier("_id_listening_link")
private let _id_speaking_link = InputDataIdentifier("_id_speaking_link")
private let _id_reduce_motion = InputDataIdentifier("_id_reduce_motion")
private let _id_record_video_toggle = InputDataIdentifier("_id_record_video_toggle")
private func _id_peer(_ id:PeerId) -> InputDataIdentifier {
return InputDataIdentifier("_id_peer_\(id.toInt64())")
}
private func groupCallSettingsEntries(callState: GroupCallUIState, devices: IODevices, uiState: GroupCallSettingsState, settings: VoiceCallSettings, context: AccountContext, peer: Peer, accountPeer: Peer, joinAsPeerId: PeerId, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
let theme = GroupCallTheme.customTheme
var sectionId: Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .customModern(10)))
sectionId += 1
let state = callState.state
if state.canManageCall {
// entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
// index += 1
entries.append(.input(sectionId: sectionId, index: index, value: .string(uiState.title), error: nil, identifier: _id_input_chat_title, mode: .plain, data: .init(viewType: .singleItem, pasteFilter: nil, customTheme: theme), placeholder: nil, inputPlaceholder: strings().voiceChatSettingsTitlePlaceholder, filter: { $0 }, limit: 40))
index += 1
}
if let list = uiState.displayAsList {
if !list.isEmpty {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
struct Tuple : Equatable {
let peer: FoundPeer
let viewType: GeneralViewType
let selected: Bool
let status: String?
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsDisplayAsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let tuple = Tuple(peer: FoundPeer(peer: accountPeer, subscribers: nil), viewType: uiState.displayAsList == nil || uiState.displayAsList?.isEmpty == false ? .firstItem : .singleItem, selected: accountPeer.id == joinAsPeerId, status: strings().voiceChatSettingsDisplayAsPersonalAccount)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("self"), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: tuple.peer.peer, account: context.account, context: context, stableId: stableId, height: 50, photoSize: NSMakeSize(36, 36), titleStyle: ControlStyle(font: .medium(.title), foregroundColor: theme.textColor, highlightColor: .white), statusStyle: ControlStyle(foregroundColor: theme.grayTextColor), status: tuple.status, inset: NSEdgeInsets(left: 30, right: 30), interactionType: .plain, generalType: .selectable(tuple.selected), viewType: tuple.viewType, action: {
arguments.switchAccount(tuple.peer.peer.id)
}, customTheme: theme)
}))
index += 1
for peer in list {
var status: String?
if let subscribers = peer.subscribers {
if peer.peer.isChannel {
status = strings().voiceChatJoinAsChannelCountable(Int(subscribers))
} else if peer.peer.isSupergroup || peer.peer.isGroup {
status = strings().voiceChatJoinAsGroupCountable(Int(subscribers))
}
}
var viewType = bestGeneralViewType(list, for: peer)
if list.first == peer {
if list.count == 1 {
viewType = .lastItem
} else {
viewType = .innerItem
}
}
let tuple = Tuple(peer: peer, viewType: viewType, selected: peer.peer.id == joinAsPeerId, status: status)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_peer(peer.peer.id), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: tuple.peer.peer, account: context.account, context: context, stableId: stableId, height: 50, photoSize: NSMakeSize(36, 36), titleStyle: ControlStyle(font: .medium(.title), foregroundColor: theme.textColor, highlightColor: .white), statusStyle: ControlStyle(foregroundColor: theme.grayTextColor), status: tuple.status, inset: NSEdgeInsets(left: 30, right: 30), interactionType: .plain, generalType: .selectable(tuple.selected), viewType: tuple.viewType, action: {
arguments.switchAccount(tuple.peer.peer.id)
}, customTheme: theme)
}))
}
}
} else {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("loading"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralLoadingRowItem(initialSize, stableId: stableId, viewType: .lastItem)
}))
index += 1
}
if state.canManageCall && state.scheduleTimestamp == nil {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let recordTitle: String
let recordPlaceholder: String = strings().voiecChatSettingsRecordPlaceholder1
if callState.peer.isChannel || callState.peer.isGigagroup {
recordTitle = strings().voiecChatSettingsRecordLiveTitle
} else if !callState.videoActive(.list).isEmpty {
recordTitle = strings().voiecChatSettingsRecordVideoTitle
} else {
recordTitle = strings().voiecChatSettingsRecordTitle
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(recordTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let recordingStartTimestamp = state.recordingStartTimestamp
if recordingStartTimestamp == nil {
entries.append(.input(sectionId: sectionId, index: index, value: .string(uiState.recordName), error: nil, identifier: _id_input_record_title, mode: .plain, data: .init(viewType: .firstItem, pasteFilter: nil, customTheme: theme), placeholder: nil, inputPlaceholder: recordPlaceholder, filter: { $0 }, limit: 40))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_record_video_toggle, data: .init(name: strings().voiceChatSettingsRecordIncludeVideo, color: theme.textColor, type: .switchable(uiState.recordVideo), viewType: .innerItem, action: arguments.toggleRecordVideo, theme: theme)))
index += 1
if uiState.recordVideo {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("video_orientation"), equatable: InputDataEquatable(uiState), comparable: nil, item: { initialSize, stableId in
return GroupCallVideoOrientationRowItem(initialSize, stableId: stableId, viewType: .innerItem, account: context.account, customTheme: theme, selected: uiState.videoOrientation, select: arguments.selectVideoRecordOrientation)
}))
index += 1
}
}
struct Tuple : Equatable {
let recordingStartTimestamp: Int32?
let viewType: GeneralViewType
}
let tuple = Tuple(recordingStartTimestamp: recordingStartTimestamp, viewType: recordingStartTimestamp == nil ? .lastItem : .singleItem)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("recording"), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return GroupCallRecorderRowItem(initialSize, stableId: stableId, viewType: tuple.viewType, account: context.account, startedRecordedTime: tuple.recordingStartTimestamp, customTheme: theme, start: arguments.startRecording, stop: arguments.stopRecording)
}))
index += 1
}
if state.canManageCall, let defaultParticipantMuteState = state.defaultParticipantMuteState, !state.isStream {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPermissionsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let isMuted = defaultParticipantMuteState == .muted
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_speak_all_members, data: InputDataGeneralData(name: strings().voiceChatSettingsAllMembers, color: theme.textColor, type: .selectable(!isMuted), viewType: .firstItem, enabled: true, action: {
arguments.updateDefaultParticipantsAreMuted(false)
}, theme: theme)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_speak_admin_only, data: InputDataGeneralData(name: strings().voiceChatSettingsOnlyAdmins, color: theme.textColor, type: .selectable(isMuted), viewType: .lastItem, enabled: true, action: {
arguments.updateDefaultParticipantsAreMuted(true)
}, theme: theme)))
index += 1
}
if !state.isStream {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let microDevice = settings.audioInputDeviceId == nil ? devices.audioInput.first : devices.audioInput.first(where: { $0.uniqueID == settings.audioInputDeviceId })
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().callSettingsInputTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_audio, data: .init(name: strings().callSettingsInputText, color: theme.textColor, type: .contextSelector(settings.audioInputDeviceId == nil ? strings().callSettingsDeviceDefault : microDevice?.localizedName ?? strings().callSettingsDeviceDefault, [SPopoverItem(strings().callSettingsDeviceDefault, {
arguments.toggleInputAudioDevice(nil)
})] + devices.audioInput.map { value in
return SPopoverItem(value.localizedName, {
arguments.toggleInputAudioDevice(value.uniqueID)
})
}), viewType: microDevice == nil ? .singleItem : .firstItem, theme: theme)))
index += 1
if let microDevice = microDevice {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_micro, equatable: InputDataEquatable(microDevice.uniqueID), comparable: nil, item: { initialSize, stableId -> TableRowItem in
return MicrophonePreviewRowItem(initialSize, stableId: stableId, context: arguments.sharedContext, viewType: .lastItem, customTheme: theme)
}))
index += 1
}
}
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let outputDevice = devices.audioOutput.first(where: { $0.uniqueID == settings.audioOutputDeviceId })
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsOutput), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_output_audio, data: .init(name: strings().voiceChatSettingsOutputDevice, color: theme.textColor, type: .contextSelector(outputDevice?.localizedName ?? strings().callSettingsDeviceDefault, [SPopoverItem(strings().callSettingsDeviceDefault, {
arguments.toggleOutputAudioDevice(nil)
})] + devices.audioOutput.map { value in
return SPopoverItem(value.localizedName, {
arguments.toggleOutputAudioDevice(value.uniqueID)
})
}), viewType: .singleItem, theme: theme)))
index += 1
if !state.isStream {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalkTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_toggle, data: .init(name: strings().voiceChatSettingsPushToTalkEnabled, color: theme.textColor, type: .switchable(settings.mode != .none), viewType: .singleItem, action: {
if settings.mode == .none {
arguments.checkPermission()
}
arguments.updateSettings {
$0.withUpdatedMode($0.mode == .none ? .pushToTalk : .none)
}
}, theme: theme)))
index += 1
switch settings.mode {
case .none:
break
default:
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsInputMode), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_always, data: .init(name: strings().voiceChatSettingsInputModeAlways, color: theme.textColor, type: .selectable(settings.mode == .always), viewType: .firstItem, action: {
arguments.updateSettings {
$0.withUpdatedMode(.always)
}
}, theme: theme)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_ptt, data: .init(name: strings().voiceChatSettingsInputModePushToTalk, color: theme.textColor, type: .selectable(settings.mode == .pushToTalk), viewType: .lastItem, action: {
arguments.updateSettings {
$0.withUpdatedMode(.pushToTalk)
}
}, theme: theme)))
index += 1
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalk), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_ptt, equatable: InputDataEquatable(settings.pushToTalk), comparable: nil, item: { initialSize, stableId -> TableRowItem in
return PushToTalkRowItem(initialSize, stableId: stableId, settings: settings.pushToTalk, update: { value in
arguments.updateSettings {
$0.withUpdatedPushToTalk(value)
}
}, checkPermission: arguments.checkPermission, viewType: .singleItem)
}))
index += 1
if let permission = uiState.hasPermission {
if !permission {
let text: String
if #available(macOS 10.15, *) {
text = strings().voiceChatSettingsPushToTalkAccess
} else {
text = strings().voiceChatSettingsPushToTalkAccessOld
}
entries.append(.desc(sectionId: sectionId, index: index, text: .customMarkdown(text, linkColor: GroupCallTheme.speakLockedColor, linkFont: .bold(11.5), linkHandler: { permission in
PermissionsManager.openInputMonitoringPrefs()
}), data: .init(color: GroupCallTheme.speakLockedColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
} else {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalkDesc), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
}
}
}
}
if !state.isStream {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPerformanceHeader), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_noise_suppression, data: InputDataGeneralData(name: strings().voiceChatSettingsNoiseSuppression, color: theme.textColor, type: .switchable(settings.noiseSuppression), viewType: .singleItem, enabled: true, action: {
arguments.setNoiseSuppression(!settings.noiseSuppression)
}, theme: theme)))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPerformanceDesc), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textBottomItem)))
index += 1
}
if state.canManageCall, peer.groupAccess.isCreator {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
if !state.isStream {
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_reset_link, data: InputDataGeneralData(name: strings().voiceChatSettingsResetLink, color: GroupCallTheme.customTheme.accentColor, type: .none, viewType: .firstItem, enabled: true, action: arguments.resetLink, theme: theme)))
index += 1
} else if let credentials = uiState.credentials {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsRTMP), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_server_url, equatable: .init(uiState), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPServerURL, copyMenuText: strings().textCopy, labelColor: theme.textColor, textColor: theme.accentColor, backgroundColor: theme.backgroundColor, text: credentials.url, context: nil, viewType: .firstItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.url)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.url)
}, textFont: .code(.title), accentColor: theme.accentColor, borderColor: theme.borderColor)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_stream_key, equatable: .init(uiState), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPStreamKey, copyMenuText: strings().textCopy, labelColor: theme.textColor, textColor: theme.accentColor, backgroundColor: theme.backgroundColor, text: credentials.streamKey, context: nil, viewType: .innerItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.streamKey)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.streamKey)
}, textFont: .code(.title), hideText: uiState.hideKey, toggleHide: arguments.toggleHideKey, accentColor: theme.accentColor, borderColor: theme.borderColor)
}))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_revoke_stream_key, data: InputDataGeneralData(name: strings().voiceChatRTMPRevoke, color: GroupCallTheme.speakLockedColor, type: .none, viewType: .lastItem, enabled: true, action: arguments.revokeStreamKey, theme: theme)))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatRTMPInfo), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textBottomItem)))
index += 1
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_leave_chat, data: InputDataGeneralData(name: strings().voiceChatSettingsEnd, color: GroupCallTheme.speakLockedColor, type: .none, viewType: state.isStream ? .singleItem : .lastItem, enabled: true, action: arguments.finishCall, theme: theme)))
index += 1
}
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
return entries
}
// entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_ptt_se, data: .init(name: "Sound Effects", color: .white, type: .switchable(settings.pushToTalkSoundEffects), viewType: .lastItem, action: {
// updateSettings {
// $0.withUpdatedSoundEffects(!$0.pushToTalkSoundEffects)
// }
// }, theme: theme)))
// index += 1
//
final class GroupCallSettingsController : GenericViewController<GroupCallSettingsView> {
fileprivate let sharedContext: SharedAccountContext
fileprivate let call: PresentationGroupCall
private let disposable = MetaDisposable()
private let context: AccountContext
private let monitorPermissionDisposable = MetaDisposable()
private let actualizeTitleDisposable = MetaDisposable()
private let displayAsPeersDisposable = MetaDisposable()
private let credentialsDisposable = MetaDisposable()
private let callState: Signal<GroupCallUIState, NoError>
init(sharedContext: SharedAccountContext, context: AccountContext, callState: Signal<GroupCallUIState, NoError>, call: PresentationGroupCall) {
self.sharedContext = sharedContext
self.call = call
self.callState = callState
self.context = context
super.init()
bar = .init(height: 0)
}
private var tableView: TableView {
return genericView.tableView
}
private var firstTake: Bool = true
override func firstResponder() -> NSResponder? {
if self.window?.firstResponder == self.window || self.window?.firstResponder == tableView.documentView {
var first: NSResponder? = nil
var isRecordingPushToTalk: Bool = false
tableView.enumerateViews { view -> Bool in
if let view = view as? PushToTalkRowView {
if view.mode == .editing {
isRecordingPushToTalk = true
return false
}
}
return true
}
if !isRecordingPushToTalk {
tableView.enumerateViews { view -> Bool in
first = view.firstResponder
if first != nil, self.firstTake {
if let item = view.item as? InputDataRowDataValue {
switch item.value {
case let .string(value):
let value = value ?? ""
if !value.isEmpty {
return true
}
default:
break
}
}
}
return first == nil
}
self.firstTake = false
return first
} else {
return window?.firstResponder
}
}
return window?.firstResponder
}
override func escapeKeyAction() -> KeyHandlerResult {
return .rejected
}
override var enableBack: Bool {
return true
}
deinit {
disposable.dispose()
monitorPermissionDisposable.dispose()
actualizeTitleDisposable.dispose()
displayAsPeersDisposable.dispose()
credentialsDisposable.dispose()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_ = self.window?.makeFirstResponder(nil)
window?.set(mouseHandler: { [weak self] event -> KeyHandlerResult in
guard let `self` = self else {return .rejected}
let index = self.tableView.row(at: self.tableView.documentView!.convert(event.locationInWindow, from: nil))
if index > -1, let view = self.tableView.item(at: index).view {
if view.mouseInsideField {
if self.window?.firstResponder != view.firstResponder {
_ = self.window?.makeFirstResponder(view.firstResponder)
return .invoked
}
}
}
return .invokeNext
}, with: self, for: .leftMouseUp, priority: self.responderPriority)
}
private func fetchData() -> [InputDataIdentifier : InputDataValue] {
var values:[InputDataIdentifier : InputDataValue] = [:]
tableView.enumerateItems { item -> Bool in
if let identifier = (item.stableId.base as? InputDataEntryId)?.identifier {
if let item = item as? InputDataRowDataValue {
values[identifier] = item.value
}
}
return true
}
return values
}
private var getState:(()->GroupCallSettingsState?)? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.genericView.tableView._mouseDownCanMoveWindow = true
let context = self.context
let peerId = self.call.peerId
let initialState = GroupCallSettingsState(hasPermission: nil, title: nil, recordVideo: true, videoOrientation: .landscape)
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((GroupCallSettingsState) -> GroupCallSettingsState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
monitorPermissionDisposable.set((KeyboardGlobalHandler.getPermission() |> deliverOnMainQueue).start(next: { value in
updateState { current in
var current = current
current.hasPermission = value
return current
}
}))
getState = { [weak stateValue] in
return stateValue?.with { $0 }
}
actualizeTitleDisposable.set(call.state.start(next: { state in
updateState { current in
var current = current
if current.title == nil {
current.title = state.title
}
return current
}
}))
displayAsPeersDisposable.set(combineLatest(queue: prepareQueue,call.displayAsPeers, context.account.postbox.peerView(id: context.peerId)).start(next: { list, peerView in
updateState { current in
var current = current
current.displayAsList = list
return current
}
}))
genericView.backButton.set(handler: { [weak self] _ in
self?.navigationController?.back()
}, for: .Click)
let sharedContext = self.sharedContext
let arguments = Arguments(sharedContext: sharedContext, toggleInputAudioDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedAudioInputDeviceId(value)
}).start()
}, toggleOutputAudioDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedAudioOutputDeviceId(value)
}).start()
}, toggleInputVideoDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedCameraInputDeviceId(value)
}).start()
}, finishCall: { [weak self] in
guard let window = self?.window else {
return
}
confirm(for: window, header: strings().voiceChatSettingsEndConfirmTitle, information: strings().voiceChatSettingsEndConfirm, okTitle: strings().voiceChatSettingsEndConfirmOK, successHandler: { [weak self] _ in
guard let call = self?.call, let window = self?.window else {
return
}
_ = showModalProgress(signal: call.sharedContext.endGroupCall(terminate: true), for: window).start()
}, appearance: darkPalette.appearance)
}, updateDefaultParticipantsAreMuted: { [weak self] value in
self?.call.updateDefaultParticipantsAreMuted(isMuted: value)
}, updateSettings: { f in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, f).start()
}, checkPermission: {
updateState { current in
var current = current
current.hasPermission = KeyboardGlobalHandler.hasPermission()
return current
}
}, showTooltip: { [weak self] text in
if let window = self?.window {
showModalText(for: window, text: text)
}
}, switchAccount: { [weak self] peerId in
self?.call.reconnect(as: peerId)
}, startRecording: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRecordingStartTitle, information: strings().voiceChatRecordingStartText1, okTitle: strings().voiceChatRecordingStartOK, successHandler: { _ in
self?.call.setShouldBeRecording(true, title: stateValue.with { $0.recordName }, videoOrientation: stateValue.with { $0.recordVideo ? $0.videoOrientation.rawValue : nil})
})
}
}, stopRecording: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRecordingStopTitle, information: strings().voiceChatRecordingStopText, okTitle: strings().voiceChatRecordingStopOK, successHandler: { [weak window] _ in
self?.call.setShouldBeRecording(false, title: nil, videoOrientation: nil)
if let window = window {
showModalText(for: window, text: strings().voiceChatToastStop)
}
})
}
}, resetLink: { [weak self] in
self?.call.resetListenerLink()
if let window = self?.window {
showModalText(for: window, text: strings().voiceChatSettingsResetLinkSuccess)
}
}, setNoiseSuppression: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedNoiseSuppression(value)
}).start()
}, reduceMotions: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedVisualEffects(value)
}).start()
}, selectVideoRecordOrientation: { value in
updateState { current in
var current = current
current.videoOrientation = value
return current
}
}, toggleRecordVideo: {
updateState { current in
var current = current
current.recordVideo = !current.recordVideo
return current
}
}, copyToClipboard: { [weak self] value in
copyToClipboard(value)
if let window = self?.window {
showModalText(for: window, text: strings().contextAlertCopied)
}
}, toggleHideKey: {
updateState { current in
var current = current
current.hideKey = !current.hideKey
return current
}
}, revokeStreamKey: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRTMPRevoke, information: strings().voiceChatRTMPRevokeInfo, okTitle: strings().alertYes, cancelTitle: strings().alertNO, successHandler: { [weak self] _ in
let signal = self?.call.engine.calls.getGroupCallStreamCredentials(peerId: .init(peerId.toInt64()), revokePreviousCredentials: true)
if let signal = signal {
_ = showModalProgress(signal: signal, for: window).start(next: { value in
updateState { current in
var current = current
current.credentials = value
return current
}
})
}
}, appearance: GroupCallTheme.customTheme.appearance)
}
})
let previousEntries:Atomic<[AppearanceWrapperEntry<InputDataEntry>]> = Atomic(value: [])
let inputDataArguments = InputDataArguments(select: { _, _ in }, dataUpdated: { [weak self] in
guard let `self` = self else {
return
}
let data = self.fetchData()
var previousTitle: String? = stateValue.with { $0.title }
updateState { current in
var current = current
current.title = data[_id_input_chat_title]?.stringValue ?? current.title
current.recordName = data[_id_input_record_title]?.stringValue ?? current.title
return current
}
let title = stateValue.with({ $0.title })
if previousTitle != title, let title = title {
self.call.updateTitle(title, force: false)
}
})
let initialSize = self.atomicSize
let joinAsPeer: Signal<PeerId, NoError> = self.call.joinAsPeerIdValue
let rtmp_credentials: Signal<GroupCallStreamCredentials?, NoError>
if let peer = self.call.peer, peer.groupAccess.isCreator {
let credentials = self.call.engine.calls.getGroupCallStreamCredentials(peerId: .init(self.call.peerId.toInt64()), revokePreviousCredentials: false)
|> map(Optional.init)
|> `catch` { _ -> Signal<GroupCallStreamCredentials?, NoError> in
return .single(nil)
}
rtmp_credentials = .single(nil) |> then(credentials)
} else {
rtmp_credentials = .single(nil)
}
credentialsDisposable.set(rtmp_credentials.start(next: { value in
updateState { current in
var current = current
current.credentials = value
return current
}
}))
let signal: Signal<TableUpdateTransition, NoError> = combineLatest(queue: prepareQueue, sharedContext.devicesContext.signal, voiceCallSettings(sharedContext.accountManager), appearanceSignal, self.call.account.postbox.loadedPeerWithId(self.call.peerId), self.call.account.postbox.loadedPeerWithId(context.peerId), joinAsPeer, self.callState, statePromise.get()) |> mapToQueue { devices, settings, appearance, peer, accountPeer, joinAsPeerId, state, uiState in
let entries = groupCallSettingsEntries(callState: state, devices: devices, uiState: uiState, settings: settings, context: context, peer: peer, accountPeer: accountPeer, joinAsPeerId: joinAsPeerId, arguments: arguments).map { AppearanceWrapperEntry(entry: $0, appearance: appearance) }
return prepareInputDataTransition(left: previousEntries.swap(entries), right: entries, animated: true, searchState: nil, initialSize: initialSize.with { $0 }, arguments: inputDataArguments, onMainQueue: false)
} |> deliverOnMainQueue
disposable.set(signal.start(next: { [weak self] value in
self?.genericView.tableView.merge(with: value)
self?.readyOnce()
}))
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
backgroundColor = GroupCallTheme.windowBackground.withAlphaComponent(1)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let state = getState?(), let title = state.title {
self.call.updateTitle(title, force: true)
}
self.window?.removeObserver(for: self)
}
override func backKeyAction() -> KeyHandlerResult {
return .invokeNext
}
override func returnKeyAction() -> KeyHandlerResult {
self.navigationController?.back()
return super.returnKeyAction()
}
}
| gpl-2.0 | bfc407f0b0bda340cade9b3ce66fd994 | 48.388075 | 525 | 0.629906 | 4.934678 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/HackerRank/EvenTree/EvenTree.swift | 1 | 1687 | //
// EvenTree.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 29/06/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import Foundation
//https://www.hackerrank.com/challenges/even-tree
class EvenTree: NSObject {
// MARK: Edges
class func totalEdgesRemovedToFormForestOfEvenTrees(numberOfNodes: Int, edges: [[Int]]) -> Int {
let nodes = buildNodes(numberOfNodes: numberOfNodes)
connectEdges(nodes: nodes, edges: edges)
var totalEdgesRemoved = 0
for node in nodes {
if node.parent != nil { // skip root
let count = nodesInTree(root: node)
if count % 2 == 0 {
totalEdgesRemoved += 1
}
}
}
return totalEdgesRemoved
}
// MARK: Build
class func buildNodes(numberOfNodes: Int) -> [EvenTreeNode] {
var nodes = [EvenTreeNode]()
for i in 0..<numberOfNodes {
let node = EvenTreeNode(value: i)
nodes.append(node)
}
return nodes
}
class func connectEdges(nodes: [EvenTreeNode], edges: [[Int]]) {
for edge in edges {
let child = nodes[edge[0]]
let parent = nodes[edge[1]]
parent.addChild(child: child)
}
}
// MARK: DFS
class func nodesInTree(root: EvenTreeNode) -> Int {
var count = 1 // start at 1 as you need to count the root node
for child in root.children {
count += nodesInTree(root: child)
}
return count
}
}
| mit | 24481a10a95b7123ee26d8ec10f9e9a1 | 24.164179 | 100 | 0.529656 | 4.544474 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Controllers/RootViewController.swift | 1 | 16466 | //
// RootViewController.swift
// zhuishushenqi
//
// Created by Nory Cao on 16/9/16.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
let AllChapterUrl = "http://api.zhuishushenqi.com/ctoc/57df797cb061df9e19b8b030"
class RootViewController: UIViewController {
let kHeaderViewHeight:CGFloat = 5
fileprivate let kHeaderBigHeight:CGFloat = 44
fileprivate let kCellHeight:CGFloat = 60
// 采用dict保存书架中的书籍
var bookshelf:[String:Any]?
// 保存所有书籍的id
var books:[String]?
var bookShelfArr:[BookDetail]?
var updateInfoArr:[UpdateInfo]?
var segMenu:SegMenu!
var bookShelfLB:UILabel!
var communityView:CommunityView!
var headerView:UIView!
var reachability:Reachability?
var semaphore:DispatchSemaphore!
var totalCacheChapter:Int = 0
var curCacheChapter:Int = 0
private var tipImageView:UIImageView!
private var recView:QSLaunchRecView!
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = self.kCellHeight
tableView.estimatedRowHeight = self.kCellHeight
tableView.estimatedSectionHeaderHeight = self.kHeaderViewHeight
tableView.sectionFooterHeight = CGFloat.leastNonzeroMagnitude
tableView.qs_registerCellClass(SwipableCell.self)
// let refresh = PullToRefresh(height: 50, position: .top, tip: "正在刷新")
// tableView.addPullToRefresh(refresh, action: {
// self.requetShelfMsg()
// self.requestBookShelf()
// self.updateInfo()
// })
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupReachability(IMAGE_BASEURL, useClosures: false)
self.startNotifier()
NotificationCenter.default.addObserver(self, selector: #selector(bookShelfUpdate(noti:)), name: Notification.Name(rawValue: BOOKSHELF_ADD), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(bookShelfUpdate(noti:)), name: Notification.Name(rawValue: BOOKSHELF_DELETE), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showRecommend), name: Notification.Name(rawValue:SHOW_RECOMMEND), object: nil)
self.setupSubviews()
self.requetShelfMsg()
self.requestBookShelf()
self.updateInfo()
}
func removeBook(book:BookDetail){
if let books = self.books {
var index = 0
for bookid in books {
if book._id == bookid {
self.books?.remove(at: index)
self.bookshelf?.removeValue(forKey: bookid)
BookManager.shared.deleteBook(book: book)
}
index += 1
}
}
}
@objc func bookShelfUpdate(noti:Notification){
let name = noti.name.rawValue
if let book = noti.object as? BookDetail {
if name == BOOKSHELF_ADD {
self.bookshelf?[book._id] = book
self.books?.append(book._id)
BookManager.shared.addBook(book: book)
} else {
removeBook(book: book)
}
}
//先刷新书架,然后再请求
self.tableView.reloadData()
self.updateInfo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = UIColor.cyan
self.navigationController?.navigationBar.barTintColor = UIColor ( red: 0.7235, green: 0.0, blue: 0.1146, alpha: 1.0 )
UIApplication.shared.isStatusBarHidden = false
// 刷新书架
self.bookshelf = BookManager.shared.books
}
@objc private func showRecommend(){
// animate
let recommend = ZSRecommend()
recommend.show(boyTipCallback: { (btn) in
}, girlTipCallback: { (btn) in
}) { (btn) in
}
// let nib = UINib(nibName: "QSLaunchRecView", bundle: nil)
// recView = nib.instantiate(withOwner: nil, options: nil).first as? QSLaunchRecView
// recView.frame = self.view.bounds
// recView.alpha = 0.0
// recView.closeCallback = { (btn) in
// self.dismissRecView()
// }
// recView.boyTipCallback = { (btn) in
// self.fetchRecList(index: 0)
// self.perform(#selector(self.dismissRecView), with: nil, afterDelay: 1)
// }
//
// recView?.girlTipCallback = { (btn) in
// self.fetchRecList(index: 1)
// self.perform(#selector(self.dismissRecView), with: nil, afterDelay: 1)
// }
// KeyWindow?.addSubview(recView)
// UIView.animate(withDuration: 0.35, animations: {
// self.recView.alpha = 1.0
// }) { (finished) in
//
// }
}
func fetchRecList(index:Int){
let gender = ["male","female"]
let recURL = "\(BASEURL)/book/recommend?gender=\(gender[index])"
zs_get(recURL, parameters: nil) { (response) in
if let books = response?["books"] {
if let models = [BookDetail].deserialize(from: books as? [Any]) as? [BookDetail] {
ZSBookManager.shared.addBooks(books: models)
BookManager.shared.modifyBookshelf(books: models)
self.tableView.reloadData()
}
self.updateInfo()
}
}
}
func showUserTipView(){
tipImageView = UIImageView(frame: self.view.bounds)
tipImageView.image = UIImage(named: "add_book_hint")
tipImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissTipView(sender:)))
tipImageView.addGestureRecognizer(tap)
KeyWindow?.addSubview(tipImageView)
}
@objc func dismissTipView(sender:Any){
tipImageView.removeFromSuperview()
}
@objc func dismissRecView(){
UIView.animate(withDuration: 0.35, animations: {
self.recView.alpha = 0.0
}) { (finished) in
self.recView.removeFromSuperview()
self.showUserTipView()
}
}
@objc func leftAction(_ btn:UIButton){
SideVC.showLeftViewController()
}
@objc func rightAction(_ btn:UIButton){
SideVC.showRightViewController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
}
extension RootViewController:UITableViewDataSource,UITableViewDelegate{
//MARK: - UITableViewDataSource and UITableViewDelegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let keys = books?.count {
return keys
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SwipableCell? = tableView.qs_dequeueReusableCell(SwipableCell.self)
cell?.delegate = self
if let id = books?[indexPath.row] {
if let value = bookshelf?.valueForKey(key: id) as? BookDetail {
cell?.configureCell(model: value)
}
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.kCellHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if bookShelfLB.text == nil || bookShelfLB.text == ""{
return kHeaderViewHeight
}
return kHeaderBigHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let id = self.books?[indexPath.row] {
if let value = bookshelf?.valueForKey(key: id) as? BookDetail {
let viewController = QSTextRouter.createModule(bookDetail:value,callback: { (book:BookDetail) in
let beginDate = Date()
self.bookshelf = BookManager.shared.modifyBookshelf(book:book)
tableView.reloadRow(at: indexPath, with: .automatic)
let endDate = Date()
let time = endDate.timeIntervalSince(beginDate as Date)
QSLog("用时\(time)")
})
self.present(viewController, animated: true, completion: nil)
}
// 进入阅读,当前书籍移到最前面
self.books?.remove(at: indexPath.row)
self.books?.insert(id, at: 0)
let deadline = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline:deadline , execute: {
self.tableView.reloadData()
})
}
}
}
extension RootViewController:ComnunityDelegate{
//MARK: - CommunityDelegate
func didSelectCellAtIndex(_ index:Int){
if index == 3{
let lookVC = LookBookViewController()
SideVC.navigationController?.pushViewController(lookVC, animated: true)
}else
if index == 5 {
let historyVC = ReadHistoryViewController()
SideVC.navigationController?.pushViewController(historyVC, animated: true)
} else if (index == 1) {
let rootVC = ZSRootViewController()
SideVC.navigationController?.pushViewController(rootVC, animated: true)
}
// else if (index == 2) {
// let rootVC = ZSForumViewController()
// SideVC.navigationController?.pushViewController(rootVC, animated: true)
// }
else{
let dynamicVC = DynamicViewController()
SideVC.navigationController?.pushViewController(dynamicVC, animated: true)
}
}
}
extension RootViewController:SwipableCellDelegate{
func swipableCell(swipableCell: SwipableCell, didSelectAt index: Int) {
}
func swipeCell(clickAt: Int,model:BookDetail,cell:SwipableCell,selected:Bool) {
if clickAt == 0 {
if selected == false {
// 取消下载
return
}
let indexPath = tableView.indexPath(for: cell)
// 选择一种缓存方式后,缓存按钮变为选中状态,小说图标变为在缓存中
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let firstAcion = UIAlertAction(title: "全本缓存", style: .default, handler: { (action) in
self.cacheChapter(book: model, startChapter: 0,indexPath: indexPath)
})
let secondAction = UIAlertAction(title: "从当前章节缓存", style: .default, handler: { (action) in
self.cacheChapter(book: model, startChapter: model.chapter,indexPath: indexPath)
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
})
alert.addAction(firstAcion)
alert.addAction(secondAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
else if clickAt == 3 {
self.removeBook(book: model)
self.tableView.reloadData()
}
}
func cacheChapter(book:BookDetail,startChapter:Int,indexPath:IndexPath?){
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .prepare
// 使用信号量控制,避免创建过多线程浪费性能
semaphore = DispatchSemaphore(value: 5)
if let chapters = book.book?.chapters {
self.totalCacheChapter = chapters.count
let group = DispatchGroup()
let global = DispatchQueue.global(qos: .userInitiated)
for index in startChapter..<chapters.count {
global.async(group: group){
if chapters[index].content == "" {
self.fetchChapter(index: index,bookDetail: book,indexPath: indexPath)
let timeout:Double? = 30.00
let timeouts = timeout.flatMap { DispatchTime.now() + $0 }
?? DispatchTime.distantFuture
_ = self.semaphore.wait(timeout: timeouts)
}else {
self.totalCacheChapter -= 1
let cell:SwipableCell = self.tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
if self.totalCacheChapter == self.curCacheChapter {
cell.state = .finish
}
}
}
}
}
}
func fetchChapter(index:Int,bookDetail:BookDetail,indexPath: IndexPath?){
let chapters = bookDetail.chapters
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .download
if index >= (chapters?.count ?? 0) {
cell.state = .none
return
}
var link:NSString = "\(chapters?[index].object(forKey: "link") ?? "")" as NSString
link = link.urlEncode() as NSString
let url = "\(CHAPTERURL)/\(link)?k=22870c026d978c75&t=1489933049"
zs_get(url, parameters: nil) { (response) in
DispatchQueue.global().async {
if let json = response as? Dictionary<String, Any> {
QSLog("JSON:\(json)")
if let chapter = json["chapter"] as? Dictionary<String, Any> {
self.cacheSuccessHandler(chapterIndex: index, chapter: chapter, bookDetail: bookDetail,indexPath: indexPath)
} else {
self.cacheFailureHandler(chapterIndex: index)
}
}else{
self.cacheFailureHandler(chapterIndex:index)
}
}
}
}
}
extension RootViewController:SegMenuDelegate{
func didSelectAtIndex(_ index: Int) {
QSLog("选择了第\(index)个")
if index == 1{
communityView.models = self.bookShelfArr ?? []
}
communityView.isHidden = (index == 0 ? true:false)
}
func cacheSuccessHandler(chapterIndex:Int,chapter: Dictionary<String, Any>,bookDetail:BookDetail,indexPath:IndexPath?){
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .download
if curCacheChapter == totalCacheChapter - 1 {
// 缓存完成
cell.state = .finish
}
self.updateChapter(chapterIndex: chapterIndex, chapter: chapter, bookDetail: bookDetail, indexPath: indexPath)
self.semaphore.signal()
}
func cacheFailureHandler(chapterIndex:Int){
QSLog("下载失败第\(chapterIndex)章节")
self.semaphore.signal()
}
// 更新当前model,更新本地保存model
func updateChapter(chapterIndex:Int,chapter: Dictionary<String, Any>,bookDetail:BookDetail,indexPath:IndexPath?){
if let chapters = bookDetail.book?.chapters {
if chapterIndex < chapters.count {
let qsChapter = chapters[chapterIndex]
qsChapter.content = chapter["body"] as? String ?? ""
bookDetail.book.chapters[chapterIndex] = qsChapter
BookManager.shared.modifyBookshelf(book: bookDetail)
}
}
}
}
| mit | 7d3ac6a80f75890385feb55b3c712dac | 36.866511 | 163 | 0.589832 | 4.597384 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Post/PostDetailContent.swift | 1 | 1719 | //
// PostDetailContent.swift
// RedditOs
//
// Created by Thomas Ricouard on 10/07/2020.
//
import SwiftUI
import Backend
import AVKit
import KingfisherSwiftUI
struct PostDetailContent: View {
let listing: SubredditPost
@Binding var redrawLink: Bool
@ViewBuilder
var body: some View {
if let text = listing.selftext ?? listing.description {
Text(text)
.font(.body)
.fixedSize(horizontal: false, vertical: true)
}
if let video = listing.secureMedia?.video {
HStack {
Spacer()
VideoPlayer(player: AVPlayer(url: video.url))
.frame(width: min(500, CGFloat(video.width)),
height: min(500, CGFloat(video.height)))
Spacer()
}
} else if let url = listing.url, let realURL = URL(string: url) {
if realURL.pathExtension == "jpg" || realURL.pathExtension == "png" {
HStack {
Spacer()
KFImage(realURL)
.resizable()
.aspectRatio(contentMode: .fit)
.background(Color.gray)
.frame(maxHeight: 400)
.padding()
Spacer()
}
} else if listing.selftext == nil || listing.selftext?.isEmpty == true {
LinkPresentationView(url: realURL, redraw: $redrawLink)
}
}
}
}
struct PostDetailContent_Previews: PreviewProvider {
static var previews: some View {
PostDetailContent(listing: static_listing, redrawLink: .constant(false))
}
}
| mit | 15c9375942a6cdf514d78df17404ce81 | 30.254545 | 84 | 0.520652 | 4.842254 | false | false | false | false |
alimysoyang/CommunicationDebugger | CommunicationDebugger/AYHelper.swift | 1 | 19700 | //
// AYHelper.swift
// CommunicationDebugger
//
// Created by alimysoyang on 15/11/23.
// Copyright © 2015年 alimysoyang. All rights reserved.
//
import Foundation
import UIKit
// MARK: - 全局枚举类型
/**
手机屏幕尺寸
- kPST_3_5: 3.5寸,4s以前
- kPST_4: 4寸,5、5c、5s
- kPST_4_7: 4.7寸,6
- kPST_5_5: 5.5寸,6plus
- kPSTUnkown: 其它尺寸
*/
enum PhoneSizeType:Int
{
case kPST_3_5 = 0
case kPST_4
case kPST_4_7
case kPST_5_5
case kPSTUnkown
}
/**
服务类型
- kCMSTServer: 服务端
- kCMSTClient: 客户端
*/
enum ServiceType:Int
{
case kCMSTServer = 0
case kCMSTClient
}
/**
通讯类型
- kCMSTUDP: UDP方式
- kCMSTTCP: TCP方式
*/
enum SocketType:Int
{
case kCMSTUDP = 0
case kCMSTTCP
}
/**
通讯传输的字符集
- kCMSCSGBK: GBK字符集
- kCMSCSUTF8: UTF8字符集
*/
enum SocketCharacetSet:Int
{
case kCMSCSGBK = 0
case kCMSCSUTF8
}
/**
通讯的消息类型
- kCMSMTSend: 发送
- kCMSMTReceived: 接收
- kCMSMTNotification: 通知
- kCMSMTErrorNotification: 错误数据的通知(文字采用红色)
*/
enum SocketMessageType:Int
{
case kCMSMTSend = 0
case kCMSMTReceived
case kCMSMTNotification
case kCMSMTErrorNotification
}
/**
通讯数据状态
- kCMMSuccess: 发送、接收成功
- kCMMSFailed: 发送失败
- kCMMSErrorData: 发送、接收数据无法解析
- kCMMSValideAddress: 发送的无效地址
*/
enum MessageStatus:Int
{
case kCMMSuccess = 0
case kCMMSFailed
case kCMMSErrorData
case kCMMSValideAddress
}
/**
项目助手单元
*/
class AYHelper: NSObject
{
// MARK: - properties
// MARK: - 通讯配置文件名
class var configFileName: String
{
return "cmparams";
}
// MARK: - app配置文件名
class var sconfigFileName: String
{
return "apparams";
}
// MARK: - 屏幕宽度
class var screenWidth:CGFloat
{
return UIScreen.mainScreen().bounds.size.width;
}
class var singleLine:CGFloat
{
return 1.0 / UIScreen.mainScreen().scale;
}
// MARK: - 12号字体
class var p12Font:UIFont
{
return UIFont.systemFontOfSize(12.0);
}
// MARK: - 15号字体
class var p15Font:UIFont
{
return UIFont.systemFontOfSize(15.0);
}
// MARK: - 默认背景色
class var defaultBackgroundColor:UIColor
{
return UIColor(red: 249.0 / 255.0, green: 247.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0);
//return UIColor(red: 235.0 / 255.0 , green: 235.0 / 255.0, blue: 235.0 / 255.0, alpha: 1.0);
}
// MARK: - 默认弹出式的背景色
class var defaultPopBackgroundColor:UIColor
{
return UIColor(red: 249.0 / 255.0, green: 247.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0);
}
class var dateformatter : NSDateFormatter
{
struct sharedInstance
{
static var onceToken:dispatch_once_t = 0;
static var staticInstance:NSDateFormatter? = nil;
}
dispatch_once(&sharedInstance.onceToken, { () -> Void in
sharedInstance.staticInstance = NSDateFormatter();
sharedInstance.staticInstance?.dateFormat = "yyyy-MM-dd HH:mm:ss";
});
return sharedInstance.staticInstance!;
}
// MARK: - life cycle
override init()
{
super.init();
}
deinit
{
}
// MARK: - static methods
// MARK: - 判断当前设备的屏幕类型
class func currentDevicePhoneSizeType()->PhoneSizeType
{
var retVal:PhoneSizeType = .kPSTUnkown;
let currentModeSize:CGSize = UIScreen.mainScreen().currentMode!.size;
var isSame:Bool = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(1242, 2208), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_5_5;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(750, 1334), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_4_7;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(640, 1136), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_4;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(640, 960), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_3_5
}
}
}
}
return retVal;
}
// MARK: - 获取本地IP地址
class func getIPAddress()->String
{
var addresses = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0
{
// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next)
{
let flags = Int32(ptr.memory.ifa_flags)
var addr = ptr.memory.ifa_addr.memory
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)
{
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6)
{
// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0)
{
if let address = String.fromCString(hostname)
{
addresses.append(address)
}
}
}
}
}
freeifaddrs(ifaddr);
}
if (addresses.count > 0)
{
return addresses[0];
}
return NSLocalizedString("UnkownIP", comment: "");
}
// MARK: - 16进制字符转单字节
class func charsToByte(highChar:unichar, lowChar:unichar)->UInt8
{
var highb:unichar;
var lowb:unichar;
var tmpb:unichar;
if (highChar >= 48 && highChar <= 57)
{
tmpb = 48;
}
else if (highChar >= 65 && highChar <= 70)
{
tmpb = 55;
}
else
{
tmpb = 87;
}
highb = (highChar - tmpb) * 16;
if (lowChar >= 48 && lowChar <= 57)
{
tmpb = 48;
}
else if (lowChar >= 65 && lowChar <= 70)
{
tmpb = 55;
}
else
{
tmpb = 87;
}
lowb = lowChar - tmpb;
return UInt8(highb + lowb);
}
class func parseReceivedData(receivedData:NSData)->AYHReceivedData
{
let retVal:AYHReceivedData = AYHReceivedData();
if (AYHCMParams.sharedInstance.rHexData)
{
retVal.receivedMsg = receivedData.toHexString("");
}
else
{
if (AYHCMParams.sharedInstance.rCharacterSet == .kCMSCSGBK)
{
retVal.receivedMsg = NSString(data: receivedData, encoding: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))) as? String;
}
else
{
retVal.receivedMsg = NSString(data: receivedData, encoding: NSUTF8StringEncoding) as? String;
}
}
guard let _ = retVal.receivedMsg else
{
retVal.receivedDataResultType = .kCMMSErrorData;
retVal.receivedMsg = String(format: "%@:\n%@", NSLocalizedString("ReceivedDataUnkown", comment: "ReceivedDataUnkown"), receivedData.toHexString(""));
return retVal;
}
return retVal;
}
}
// MARK: - String扩展
extension String
{
/**
字符串去除空格
- returns: 更新后的字符串
*/
func trim()->String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet());
}
/**
判断当前字符串是不是合法的IP地址
:returns: true,false
*/
func isValideIPAddress()->Bool
{
var retVal:Bool = false;
do
{
let regx:NSRegularExpression = try NSRegularExpression(pattern: "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$", options: NSRegularExpressionOptions.CaseInsensitive);
let nStr:NSString = self as NSString;
let matches = regx.matchesInString(self, options:[], range: NSMakeRange(0, nStr.length));
retVal = matches.count > 0;
} catch let error as NSError
{
retVal = false;
debugPrint("isValideIPAddress:\(error)");
}
return retVal;
}
/**
判断当前字符串是不是一个有效的16进制字符串
:returns: true,false
*/
func isValideHexString()->Bool
{
let compareHex = "01234567890abcdefABCDEF";
let cs:NSCharacterSet = NSCharacterSet(charactersInString: compareHex).invertedSet;
let filtereds:NSArray = self.componentsSeparatedByCharactersInSet(cs) as NSArray;
let filtered:String = filtereds.componentsJoinedByString("");
return self == filtered;
}
/**
将普通字符串或16进制字符串转成NSData
:param: hexData true,false
:param: characterSetType 字符集类型0-GBK,1-UTF8,默认1-UTF8
:returns: NSData
*/
func toNSData(hexData:Bool, characterSetType:Int = 1)->NSData?
{
var retVal:NSData?;
let nStr:NSString = self as NSString;
if (hexData)
{
if (self.isValideHexString())
{
let length:Int = nStr.length / 2;
var values:[UInt8] = [UInt8](count:length, repeatedValue:0);
var i:Int = 0;
var j:Int = 0;
while (i < length * 2)
{
let highChar:unichar = nStr.characterAtIndex(i);
let lowChar:unichar = nStr.characterAtIndex(i + 1);
values[j] = AYHelper.charsToByte(highChar, lowChar: lowChar);
i += 2;
j++;
}
retVal = NSData(bytes: values, length: length);
}
}
else
{
if (characterSetType == 0)//GBK
{
retVal = self.dataUsingEncoding(CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)));
}
else
{
retVal = self.dataUsingEncoding(NSUTF8StringEncoding);
}
}
return retVal;
}
}
// MARK: - NSData扩展
extension NSData
{
/**
NSData转成16进制字符串
:param: seperatorChar 分割字符,可以为空
:returns: 16进制字符串
*/
func toHexString(seperatorChar:String?)->String
{
var retVal:String = "";
let count:Int = self.length / sizeof(UInt8);
var bytes:[UInt8] = [UInt8](count:count, repeatedValue:0);
self.getBytes(&bytes, length: count * sizeof(UInt8));
for index in 0..<count
{
if let sChar = seperatorChar
{
if (index == count - 1)
{
retVal += String(format: "%02X", bytes[index]);
}
else
{
retVal += (String(format: "%02X", bytes[index]) + sChar);
}
}
else
{
retVal += String(format: "%02X", bytes[index]);
}
}
return retVal;
}
}
extension NSDate
{
func currentDateToStartDateAndEndDate()->(startDate:NSDate?, endDate:NSDate?)
{
let calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!;
let compents:NSDateComponents = calendar.components([.NSYearCalendarUnit, .NSMonthCalendarUnit, .NSDayCalendarUnit, .NSHourCalendarUnit, .NSMinuteCalendarUnit, .NSSecondCalendarUnit], fromDate: self);
compents.hour = 0;
compents.minute = 0;
compents.second = 0;
let startDate:NSDate? = calendar.dateFromComponents(compents);
compents.hour = 23;
compents.minute = 59;
compents.second = 59;
let endData:NSDate? = calendar.dateFromComponents(compents);
return (startDate, endData);
}
func anyDateToStartDateAndEndDate(daySpace:Int)->(startDate:NSDate?, endDate:NSDate?)
{
let calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!;
let compents:NSDateComponents = calendar.components([.NSYearCalendarUnit, .NSMonthCalendarUnit, .NSDayCalendarUnit, .NSHourCalendarUnit, .NSMinuteCalendarUnit, .NSSecondCalendarUnit], fromDate: self);
compents.hour = 0;
compents.minute = 0;
compents.second = 0;
var tmpDate:NSDate? = calendar.dateFromComponents(compents);
if let _ = tmpDate
{
tmpDate = tmpDate!.dateByAddingTimeInterval(NSTimeInterval(daySpace * 86400));
return tmpDate!.currentDateToStartDateAndEndDate();
}
return (nil, nil);
}
}
// MARK: - UIColor扩展
extension UIColor
{
/**
16进制字符串颜色值转UIColor
- parameter hexColor: 16进制字符串
- parameter alpha: 透明度,默认1.0
- returns: UIColor
*/
public convenience init?(hexColor:String, alpha:CGFloat = 1.0)
{
var hex = hexColor
if hex.hasPrefix("#")
{
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1));
}
if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil)
{
if hex.characters.count == 3
{
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1));
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2)));
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2));
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex;
}
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2));
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2), end: hex.startIndex.advancedBy(4)));
let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4), end: hex.startIndex.advancedBy(6)));
var redInt: CUnsignedInt = 0;
var greenInt: CUnsignedInt = 0;
var blueInt: CUnsignedInt = 0;
NSScanner(string: redHex).scanHexInt(&redInt);
NSScanner(string: greenHex).scanHexInt(&greenInt);
NSScanner(string: blueHex).scanHexInt(&blueInt);
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: alpha);
}
else
{
self.init();
return nil;
}
}
/**
整型数据转UIColor,可以是16进制整型数据
- parameter rgb: RGB颜色整型值
- parameter alpha: 透明度,默认1.0
- returns: UIColor
*/
public convenience init(rgb:Int,alpha:CGFloat = 1.0)
{
let red:CGFloat = CGFloat((rgb & 0xFF0000) >> 16) / 255.0;
let green:CGFloat = CGFloat((rgb & 0x00FF00) >> 8) / 255.0;
let blue:CGFloat = CGFloat(rgb & 0x0000FF) / 255.0;
self.init(red:red, green:green, blue:blue, alpha:alpha);
}
}
// MARK:- CGSize 扩展
extension CGSize
{
public func isEqualSize(compareSize:CGSize)->Bool
{
if (self.width == compareSize.width && self.height == compareSize.height)
{
return true;
}
return false;
}
}
extension UIView
{
enum AlertViewType:Int
{
case kAVTSuccess = 0
case kAVTFailed
case kAVTNone
}
func alert(msg:String, alertType:AlertViewType)
{
let hud:MBProgressHUD = MBProgressHUD.showHUDAddedTo(self, animated: true);
hud.labelText = msg;
hud.removeFromSuperViewOnHide = true;
if (alertType == .kAVTNone)
{
hud.customView = UIView();
}
else
{
var image:UIImage = UIImage(named: "alertsuccess")!;
if (alertType == .kAVTFailed)
{
image = UIImage(named: "alertfailed")!;
}
hud.customView = UIImageView(image: image);
}
hud.mode = MBProgressHUDMode.CustomView;
self.addSubview(hud);
hud.show(true);
hud.hide(true, afterDelay: 2.0);
}
func showLoadAlert(msg:String)
{
let hud:MBProgressHUD = MBProgressHUD.showHUDAddedTo(self, animated: true);
hud.labelText = msg;
// hud.dimBackground = true;背景加入渐变颜色
//hud.mode = MBProgressHUDMode.Indeterminate;
hud.tag = 1010;
self.addSubview(hud);
self.bringSubviewToFront(hud);
hud.show(true);
}
func hideLoadAlert()
{
self.viewWithTag(1010)?.removeFromSuperview();
MBProgressHUD.hideHUDForView(self, animated: true);
}
}
// MARK:- UIViewController 扩展
extension UIViewController
{
public func showAlertTip(tipMessage:String)
{
if #available(iOS 8.0, *)
{
let alertController:UIAlertController = UIAlertController(title:NSLocalizedString("Information", comment: ""), message: tipMessage, preferredStyle: UIAlertControllerStyle.Alert);
let alertAction:UIAlertAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in
alertController.dismissViewControllerAnimated(true, completion: { () -> Void in
});
});
alertController.addAction(alertAction);
self.presentViewController(alertController, animated: true, completion: nil);
}
else
{
let alertView:UIAlertView = UIAlertView(title: NSLocalizedString("Information", comment: ""), message: tipMessage, delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: ""));
alertView.show();
}
}
} | mit | 1052aecc63aba097f6fa432c4f37a2a2 | 27.790909 | 288 | 0.54955 | 4.225261 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Browser/PasswordHelper.swift | 3 | 12657 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import WebKit
private let SaveButtonTitle = NSLocalizedString("Save", comment: "Button to save the user's password")
private let NotNowButtonTitle = NSLocalizedString("Not now", comment: "Button to not save the user's password")
private let UpdateButtonTitle = NSLocalizedString("Update", comment: "Button to update the user's password")
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Authentication prompt cancel button")
private let LoginButtonTitle = NSLocalizedString("Login", comment: "Authentication prompt login button")
class PasswordHelper: BrowserHelper {
private weak var browser: Browser?
private let profile: Profile
private var snackBar: SnackBar?
private static let MaxAuthenticationAttempts = 3
class func name() -> String {
return "PasswordHelper"
}
required init(browser: Browser, profile: Profile) {
self.browser = browser
self.profile = profile
if let path = NSBundle.mainBundle().pathForResource("PasswordHelper", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "passwordsManagerMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
// println("DEBUG: passwordsManagerMessageHandler message: \(message.body)")
var res = message.body as! [String: String]
let type = res["type"]
if let url = browser?.url {
if type == "request" {
res["username"] = ""
res["password"] = ""
let password = Password.fromScript(url, script: res)
requestPasswords(password, requestId: res["requestId"]!)
} else if type == "submit" {
let password = Password.fromScript(url, script: res)
setPassword(Password.fromScript(url, script: res))
}
}
}
class func replace(base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in enumerate(keys) {
let replace = replacements[index]
let range = string.rangeOfString(key,
options: NSStringCompareOptions.LiteralSearch,
range: nil,
locale: nil)!
string.replaceRange(range, with: replace)
let nsRange = NSMakeRange(distance(string.startIndex, range.startIndex),
count(replace))
ranges.append(nsRange)
}
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 13)
attributes[NSForegroundColorAttributeName] = UIColor.darkGrayColor()
var attr = NSMutableAttributedString(string: string, attributes: attributes)
for (index, range) in enumerate(ranges) {
attr.addAttribute(NSFontAttributeName, value: UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Bold" : "HelveticaNeue-Medium", size: 13)!, range: range)
}
return attr
}
private func setPassword(password: Password) {
profile.passwords.get(QueryOptions(filter: password.hostname), complete: { data in
for i in 0..<data.count {
let savedPassword = data[i] as! Password
if savedPassword.username == password.username {
if savedPassword.password == password.password {
return
}
self.promptUpdate(password)
return
}
}
self.promptSave(password)
})
}
private func promptSave(password: Password) {
let promptStringFormat = NSLocalizedString("Do you want to save the password for %@ on %@?", comment: "Prompt for saving a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
let promptMessage = NSAttributedString(string: String(format: promptStringFormat, password.username, password.hostname))
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: SaveButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.passwords.add(password) { success in
// nop
}
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func promptUpdate(password: Password) {
let promptStringFormat = NSLocalizedString("Do you want to update the password for %@ on %@?", comment: "Prompt for updating a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
let formatted = String(format: promptStringFormat, password.username, password.hostname)
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: UpdateButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.passwords.add(password) { success in
// println("Add password \(success)")
}
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func requestPasswords(password: Password, requestId: String) {
profile.passwords.get(QueryOptions(filter: password.hostname), complete: { (cursor) -> Void in
var logins = [[String: String]]()
for i in 0..<cursor.count {
let password = cursor[i] as! Password
logins.append(password.toDict())
}
let jsonObj: [String: AnyObject] = [
"requestId": requestId,
"name": "RemoteLogins:loginsFound",
"logins": logins
]
let json = JSON(jsonObj)
let src = "window.__firefox__.passwords.inject(\(json.toString()))"
self.browser?.webView.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in
})
})
}
func handleAuthRequest(viewController: UIViewController, challenge: NSURLAuthenticationChallenge, completion: (password: Password?) -> Void) {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= PasswordHelper.MaxAuthenticationAttempts {
completion(password: nil)
return
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
completion(password: Password(credential: credential!, protectionSpace: challenge.protectionSpace))
return
}
} else {
credential = nil
}
}
if let credential = credential {
// If we have some credentials, we'll show a prompt with them.
let password = Password(credential: credential, protectionSpace: challenge.protectionSpace)
promptForUsernamePassword(viewController, password: password, completion: completion)
} else {
// Otherwise, try to look one up
let options = QueryOptions(filter: challenge.protectionSpace.host, filterType: .None, sort: .None)
profile.passwords.get(options, complete: { (cursor) -> Void in
var password = cursor[0] as? Password
if password == nil {
password = Password(credential: nil, protectionSpace: challenge.protectionSpace)
}
self.promptForUsernamePassword(viewController, password: password!, completion: completion)
})
}
}
private func promptForUsernamePassword(viewController: UIViewController, password: Password, completion: (password: Password?) -> Void) {
if password.hostname.isEmpty {
println("Unable to show a password prompt without a hostname")
completion(password: nil)
}
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !password.httpRealm.isEmpty {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg, password.hostname, password.httpRealm) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg, password.hostname) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
}
// Add a login button.
let action = UIAlertAction(title: LoginButtonTitle,
style: UIAlertActionStyle.Default) { (action) -> Void in
let user = (alert.textFields?[0] as! UITextField).text
let pass = (alert.textFields?[1] as! UITextField).text
let credential = NSURLCredential(user: user, password: pass, persistence: .ForSession)
let password = Password(credential: credential, protectionSpace: password.protectionSpace)
completion(password: password)
self.setPassword(password)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: UIAlertActionStyle.Cancel) { (action) -> Void in
completion(password: nil)
return
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = password.username
}
// Add a password textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.secureTextEntry = true
textfield.text = password.password
}
viewController.presentViewController(alert, animated: true) { () -> Void in }
}
} | mpl-2.0 | c23792aa56cbdac7b47fc6d5b8274345 | 45.708487 | 245 | 0.620368 | 5.443871 | false | false | false | false |
SwiftKidz/Slip | Sources/Classes/FlowResultsHandler.swift | 1 | 2609 | /*
MIT License
Copyright (c) 2016 SwiftKidz
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
final class FlowResultsHandler {
fileprivate var rawResults: [FlowOpResult] = []
fileprivate let resultsQueue: DispatchQueue
fileprivate let finishHandler: ([FlowOpResult], Error?) -> Void
fileprivate let numberOfResultsToFinish: Int
fileprivate var stop: Bool = false
init(maxOps: Int = -1, onFinish: @escaping ([FlowOpResult], Error?) -> Void) {
resultsQueue = DispatchQueue(label: "com.slip.flow.flowOperationResultsHandler.resultsQueue")
finishHandler = onFinish
numberOfResultsToFinish = maxOps
}
}
extension FlowResultsHandler {
var currentResults: [FlowOpResult] {
var res: [FlowOpResult]!
resultsQueue.sync { res = rawResults }
res = rawResults
return res
}
}
extension FlowResultsHandler {
func addNewResult(_ result: FlowOpResult) {
resultsQueue.sync {
guard !self.stop else { return }
guard result.error == nil else {
self.finish(result.error)
return
}
self.rawResults.append(result)
guard self.rawResults.count == self.numberOfResultsToFinish else { return }
self.finish()
}
}
}
extension FlowResultsHandler {
func finish(_ error: Error? = nil) {
stop = true
let handler = finishHandler
let results = rawResults
let error = error
DispatchQueue.global().async {
handler(results, error)
}
}
}
| mit | a0afe769524c2a3492dc6354c315ea43 | 32.025316 | 101 | 0.691069 | 4.735027 | false | false | false | false |
SuPair/firefox-ios | Push/PushCrypto.swift | 1 | 14173 | /* 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 FxA
/// Class to wrap ecec which does the encryption, decryption and key generation with OpenSSL.
/// This supports aesgcm and the newer aes128gcm.
/// For each standard of decryption, two methods are supplied: one with Data parameters and return value,
/// and one with a String based one.
class PushCrypto {
// Stateless, we provide a singleton for convenience.
open static var sharedInstance = PushCrypto()
}
// AES128GCM
extension PushCrypto {
func aes128gcm(payload data: String, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let payload = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aes128gcm(payload: payload,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aes128gcm(payload: Data, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
var plaintextLen = ece_aes128gcm_plaintext_max_length(payload.getBytes(), payload.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let err = ece_webpush_aes128gcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
payload.getBytes(), payload.count,
&plaintext, &plaintextLen)
if err != ECE_OK {
throw PushCryptoError.decryptionError(errCode: err)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aes128gcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int = 4096, padLen: Int = 0) throws -> String {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let payloadData = try aes128gcm(plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let payload = payloadData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return payload
}
func aes128gcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int = 4096, padLen: Int = 0) throws -> Data {
let rs = UInt32(rsInt)
// rs needs to be >= 18.
assert(rsInt >= Int(ECE_AES128GCM_MIN_RS))
var payloadLen = ece_aes128gcm_payload_max_length(rs, padLen, plaintext.count) + 1
var payload = [UInt8](repeating: 0, count: payloadLen)
let err = ece_webpush_aes128gcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&payload, &payloadLen)
if err != ECE_OK {
throw PushCryptoError.encryptionError(errCode: err)
}
return Data(bytes: payload, count: payloadLen)
}
}
// AESGCM
extension PushCrypto {
func aesgcm(ciphertext data: String, withHeaders headers: PushCryptoHeaders, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let ciphertext = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aesgcm(ciphertext: ciphertext,
withHeaders: headers,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aesgcm(ciphertext: Data, withHeaders headers: PushCryptoHeaders, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
var rs = UInt32(0)
let paramsErr = ece_webpush_aesgcm_headers_extract_params(
headers.cryptoKey, headers.encryption,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&rs)
if paramsErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: paramsErr)
}
var plaintextLen = ece_aesgcm_plaintext_max_length(rs, ciphertext.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let decryptErr = ece_webpush_aesgcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
&salt, salt.count,
&rawSenderPubKey, rawSenderPubKey.count,
rs,
ciphertext.getBytes(), ciphertext.count,
&plaintext, &plaintextLen)
if decryptErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: decryptErr)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aesgcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, ciphertext: String) {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let (headers, messageData) = try aesgcm(
plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let message = messageData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return (headers, message)
}
func aesgcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, data: Data) {
let rs = UInt32(rsInt)
// rs needs to be >= 3.
assert(rsInt >= Int(ECE_AESGCM_MIN_RS))
var ciphertextLength = ece_aesgcm_ciphertext_max_length(rs, padLen, plaintext.count) + 1
var ciphertext = [UInt8](repeating: 0, count: ciphertextLength)
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
let encryptErr = ece_webpush_aesgcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&ciphertext, &ciphertextLength)
if encryptErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: encryptErr)
}
var cryptoKeyHeaderLength = 0
var encryptionHeaderLength = 0
let paramsSizeErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
nil, &cryptoKeyHeaderLength,
nil, &encryptionHeaderLength)
if paramsSizeErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsSizeErr)
}
var cryptoKeyHeaderBytes = [CChar](repeating: 0, count: cryptoKeyHeaderLength)
var encryptionHeaderBytes = [CChar](repeating: 0, count: encryptionHeaderLength)
let paramsErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
&cryptoKeyHeaderBytes, &cryptoKeyHeaderLength,
&encryptionHeaderBytes, &encryptionHeaderLength)
if paramsErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsErr)
}
guard let cryptoKeyHeader = String(data: Data(bytes: cryptoKeyHeaderBytes, count: cryptoKeyHeaderLength),
encoding: .ascii),
let encryptionHeader = String(data: Data(bytes: encryptionHeaderBytes, count: encryptionHeaderLength),
encoding: .ascii) else {
throw PushCryptoError.base64EncodeError
}
let headers = PushCryptoHeaders(encryption: encryptionHeader, cryptoKey: cryptoKeyHeader)
return (headers, Data(bytes: ciphertext, count: ciphertextLength))
}
}
extension PushCrypto {
func generateKeys() throws -> PushKeys {
// The subscription private key. This key should never be sent to the app
// server. It should be persisted with the endpoint and auth secret, and used
// to decrypt all messages sent to the subscription.
let privateKeyLength = Int(ECE_WEBPUSH_PRIVATE_KEY_LENGTH)
var rawRecvPrivKey = [UInt8](repeating: 0, count: privateKeyLength)
// The subscription public key. This key should be sent to the app server,
// and used to encrypt messages. The Push DOM API exposes the public key via
// `pushSubscription.getKey("p256dh")`.
let publicKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawRecvPubKey = [UInt8](repeating: 0, count: publicKeyLength)
// The shared auth secret. This secret should be persisted with the
// subscription information, and sent to the app server. The DOM API exposes
// the auth secret via `pushSubscription.getKey("auth")`.
let authSecretLength = Int(ECE_WEBPUSH_AUTH_SECRET_LENGTH)
var authSecret = [UInt8](repeating: 0, count: authSecretLength)
let err = ece_webpush_generate_keys(
&rawRecvPrivKey, privateKeyLength,
&rawRecvPubKey, publicKeyLength,
&authSecret, authSecretLength)
if err != ECE_OK {
throw PushCryptoError.keyGenerationError(errCode: err)
}
guard let privKey = Data(bytes: rawRecvPrivKey, count: privateKeyLength).base64urlSafeEncodedString,
let pubKey = Data(bytes: rawRecvPubKey, count: publicKeyLength).base64urlSafeEncodedString,
let authKey = Data(bytes: authSecret, count: authSecretLength).base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return PushKeys(p256dhPrivateKey: privKey, p256dhPublicKey: pubKey, auth: authKey)
}
}
struct PushKeys {
let p256dhPrivateKey: String
let p256dhPublicKey: String
let auth: String
}
enum PushCryptoError: Error {
case base64DecodeError
case base64EncodeError
case decryptionError(errCode: Int32)
case encryptionError(errCode: Int32)
case keyGenerationError(errCode: Int32)
case utf8EncodingError
}
struct PushCryptoHeaders {
let encryption: String
let cryptoKey: String
}
extension String {
/// Returns a base64 url safe decoding of the given string.
/// The string is allowed to be padded
/// What is padding?: http://stackoverflow.com/a/26632221
var base64urlSafeDecodedData: Data? {
// We call this method twice: once with the last two args as nil, 0 – this gets us the length
// of the decoded string.
let length = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
// The second time, we actually decode, and copy it into a made to measure byte array.
var bytes = [UInt8](repeating: 0, count: length)
let checkLength = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return Data(bytes: bytes, count: length)
}
}
extension Data {
/// Returns a base64 url safe encoding of the given data.
var base64urlSafeEncodedString: String? {
let length = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
var bytes = [CChar](repeating: 0, count: length)
let checkLength = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return String(data: Data(bytes: bytes, count: length), encoding: .ascii)
}
}
| mpl-2.0 | bc403860c343b1c79e495a4bd4ac5d37 | 41.301493 | 189 | 0.634324 | 4.487334 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Utilities/ImageManager.swift | 1 | 4012 | //
// ImageManager.swift
// Habitica
//
// Created by Phillip Thelen on 02.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Kingfisher
@objc
class ImageManager: NSObject {
static let baseURL = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/"
private static let formatDictionary = [
"head_special_0": "gif",
"head_special_1": "gif",
"shield_special_0": "gif",
"weapon_special_0": "gif",
"slim_armor_special_0": "gif",
"slim_armor_special_1": "gif",
"broad_armor_special_0": "gif",
"broad_armor_special_1": "gif",
"weapon_special_critical": "gif",
"Pet-Wolf-Cerberus": "gif",
"armor_special_ks2019": "gif",
"slim_armor_special_ks2019": "gif",
"broad_armor_special_ks2019": "gif",
"eyewear_special_ks2019": "gif",
"head_special_ks2019": "gif",
"shield_special_ks2019": "gif",
"weapon_special_ks2019": "gif",
"Pet-Gryphon-Gryphatrice": "gif",
"Mount_Head_Gryphon-Gryphatrice": "gif",
"Mount_Body_Gryphon-Gryphatrice": "gif",
"background_clocktower": "gif",
"background_airship": "gif",
"background_steamworks": "gif",
"Pet_HatchingPotion_Veggie": "gif",
"Pet_HatchingPotion_Dessert": "gif",
"Pet-HatchingPotion-Dessert": "gif",
"quest_windup": "gif",
"Pet-HatchingPotion_Windup": "gif",
"Pet_HatchingPotion_Windup": "gif",
"Pet-HatchingPotion-Windup": "gif"
]
@objc
static func setImage(on imageView: NetworkImageView, name: String, extension fileExtension: String = "", completion: ((UIImage?, NSError?) -> Void)? = nil) {
if imageView.loadedImageName != name {
imageView.image = nil
}
imageView.loadedImageName = name
getImage(name: name, extension: fileExtension) { (image, error) in
if imageView.loadedImageName == name {
imageView.image = image
if let action = completion {
action(image, error)
}
}
}
}
@objc
static func getImage(name: String, extension fileExtension: String = "", completion: @escaping (UIImage?, NSError?) -> Void) {
guard let url = URL(string: "\(baseURL)\(name).\(getFormat(name: name, format: fileExtension))") else {
return
}
KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { (image, error, _, _) in
if let error = error {
print("Image loading error:", name, error.localizedDescription)
}
completion(image, error)
}
}
@objc
static func getImage(url urlString: String, completion: @escaping (UIImage?, NSError?) -> Void) {
guard let url = URL(string: urlString) else {
return
}
KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil) { (image, error, _, _) in
if let error = error {
print("Image loading error:", url, error.localizedDescription)
}
completion(image, error)
}
}
@objc
static func clearImageCache() {
ImageCache.default.clearDiskCache()
ImageCache.default.clearMemoryCache()
}
private static func getFormat(name: String, format: String) -> String {
if (!format.isEmpty) {
return format
}
return formatDictionary[name] ?? "png"
}
private static func substituteSprite(name: String?) -> String? {
for (key, value) in substitutions {
if let keyString = key as? String, name?.contains(keyString) == true {
return value as? String
}
}
return name
}
static var substitutions = ConfigRepository().dictionary(variable: .spriteSubstitutions)
}
| gpl-3.0 | fde0f7d7c45b7eaa586914e308cde8a5 | 33.878261 | 161 | 0.57442 | 4.097038 | false | false | false | false |
jmgc/swift | stdlib/public/core/ArraySlice.swift | 1 | 58650 | //===--- ArraySlice.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// - `ArraySlice<Element>` presents an arbitrary subsequence of some
// contiguous sequence of `Element`s.
//
//===----------------------------------------------------------------------===//
/// A slice of an `Array`, `ContiguousArray`, or `ArraySlice` instance.
///
/// The `ArraySlice` type makes it fast and efficient for you to perform
/// operations on sections of a larger array. Instead of copying over the
/// elements of a slice to new storage, an `ArraySlice` instance presents a
/// view onto the storage of a larger array. And because `ArraySlice`
/// presents the same interface as `Array`, you can generally perform the
/// same operations on a slice as you could on the original array.
///
/// For more information about using arrays, see `Array` and `ContiguousArray`,
/// with which `ArraySlice` shares most properties and methods.
///
/// Slices Are Views onto Arrays
/// ============================
///
/// For example, suppose you have an array holding the number of absences
/// from each class during a session.
///
/// let absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You want to compare the absences in the first half of the session with
/// those in the second half. To do so, start by creating two slices of the
/// `absences` array.
///
/// let midpoint = absences.count / 2
///
/// let firstHalf = absences[..<midpoint]
/// let secondHalf = absences[midpoint...]
///
/// Neither the `firstHalf` nor `secondHalf` slices allocate any new storage
/// of their own. Instead, each presents a view onto the storage of the
/// `absences` array.
///
/// You can call any method on the slices that you might have called on the
/// `absences` array. To learn which half had more absences, use the
/// `reduce(_:_:)` method to calculate each sum.
///
/// let firstHalfSum = firstHalf.reduce(0, +)
/// let secondHalfSum = secondHalf.reduce(0, +)
///
/// if firstHalfSum > secondHalfSum {
/// print("More absences in the first half.")
/// } else {
/// print("More absences in the second half.")
/// }
/// // Prints "More absences in the first half."
///
/// - Important: Long-term storage of `ArraySlice` instances is discouraged. A
/// slice holds a reference to the entire storage of a larger array, not
/// just to the portion it presents, even after the original array's lifetime
/// ends. Long-term storage of a slice may therefore prolong the lifetime of
/// elements that are no longer otherwise accessible, which can appear to be
/// memory and object leakage.
///
/// Slices Maintain Indices
/// =======================
///
/// Unlike `Array` and `ContiguousArray`, the starting index for an
/// `ArraySlice` instance isn't always zero. Slices maintain the same
/// indices of the larger array for the same elements, so the starting
/// index of a slice depends on how it was created, letting you perform
/// index-based operations on either a full array or a slice.
///
/// Sharing indices between collections and their subsequences is an important
/// part of the design of Swift's collection algorithms. Suppose you are
/// tasked with finding the first two days with absences in the session. To
/// find the indices of the two days in question, follow these steps:
///
/// 1) Call `firstIndex(where:)` to find the index of the first element in the
/// `absences` array that is greater than zero.
/// 2) Create a slice of the `absences` array starting after the index found in
/// step 1.
/// 3) Call `firstIndex(where:)` again, this time on the slice created in step
/// 2. Where in some languages you might pass a starting index into an
/// `indexOf` method to find the second day, in Swift you perform the same
/// operation on a slice of the original array.
/// 4) Print the results using the indices found in steps 1 and 3 on the
/// original `absences` array.
///
/// Here's an implementation of those steps:
///
/// if let i = absences.firstIndex(where: { $0 > 0 }) { // 1
/// let absencesAfterFirst = absences[(i + 1)...] // 2
/// if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3
/// print("The first day with absences had \(absences[i]).") // 4
/// print("The second day with absences had \(absences[j]).")
/// }
/// }
/// // Prints "The first day with absences had 2."
/// // Prints "The second day with absences had 4."
///
/// In particular, note that `j`, the index of the second day with absences,
/// was found in a slice of the original array and then used to access a value
/// in the original `absences` array itself.
///
/// - Note: To safely reference the starting and ending indices of a slice,
/// always use the `startIndex` and `endIndex` properties instead of
/// specific values.
@frozen
public struct ArraySlice<Element>: _DestructorSafeContainer {
@usableFromInline
internal typealias _Buffer = _SliceBuffer<Element>
@usableFromInline
internal var _buffer: _Buffer
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@inlinable
internal init(_buffer: _Buffer) {
self._buffer = _buffer
}
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@inlinable
internal init(_buffer buffer: _ContiguousArrayBuffer<Element>) {
self.init(_buffer: _Buffer(_buffer: buffer, shiftedToStartIndex: 0))
}
}
//===--- private helpers---------------------------------------------------===//
extension ArraySlice {
/// Returns `true` if the array is native and does not need a deferred
/// type check. May be hoisted by the optimizer, which means its
/// results may be stale by the time they are used if there is an
/// inout violation in user code.
@inlinable
@_semantics("array.props.isNativeTypeChecked")
public // @testable
func _hoistableIsNativeTypeChecked() -> Bool {
return _buffer.arrayPropertyIsNativeTypeChecked
}
@inlinable
@_semantics("array.get_count")
internal func _getCount() -> Int {
return _buffer.count
}
@inlinable
@_semantics("array.get_capacity")
internal func _getCapacity() -> Int {
return _buffer.capacity
}
@inlinable
@_semantics("array.make_mutable")
internal mutating func _makeMutableAndUnique() {
if _slowPath(!_buffer.beginCOWMutation()) {
_buffer = _Buffer(copying: _buffer)
}
}
/// Marks the end of a mutation.
///
/// After a call to `_endMutation` the buffer must not be mutated until a call
/// to `_makeMutableAndUnique`.
@_alwaysEmitIntoClient
@_semantics("array.end_mutation")
internal mutating func _endMutation() {
_buffer.endCOWMutation()
}
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable
@inline(__always)
internal func _checkSubscript_native(_ index: Int) {
_buffer._checkValidSubscript(index)
}
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable
@_semantics("array.check_subscript")
public // @testable
func _checkSubscript(
_ index: Int, wasNativeTypeChecked: Bool
) -> _DependenceToken {
#if _runtime(_ObjC)
_buffer._checkValidSubscript(index)
#else
_buffer._checkValidSubscript(index)
#endif
return _DependenceToken()
}
/// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.
@inlinable
@_semantics("array.check_index")
internal func _checkIndex(_ index: Int) {
_precondition(index <= endIndex, "ArraySlice index is out of range")
_precondition(index >= startIndex, "ArraySlice index is out of range (before startIndex)")
}
@_semantics("array.get_element")
@inlinable // FIXME(inline-always)
@inline(__always)
public // @testable
func _getElement(
_ index: Int,
wasNativeTypeChecked: Bool,
matchingSubscriptCheck: _DependenceToken
) -> Element {
#if false
return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked)
#else
return _buffer.getElement(index)
#endif
}
@inlinable
@_semantics("array.get_element_address")
internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {
return _buffer.subscriptBaseAddress + index
}
}
extension ArraySlice: _ArrayProtocol {
/// The total number of elements that the array can contain without
/// allocating new storage.
///
/// Every array reserves a specific amount of memory to hold its contents.
/// When you add elements to an array and that array begins to exceed its
/// reserved capacity, the array allocates a larger region of memory and
/// copies its elements into the new storage. The new storage is a multiple
/// of the old storage's size. This exponential growth strategy means that
/// appending an element happens in constant time, averaging the performance
/// of many append operations. Append operations that trigger reallocation
/// have a performance cost, but they occur less and less often as the array
/// grows larger.
///
/// The following example creates an array of integers from an array literal,
/// then appends the elements of another collection. Before appending, the
/// array allocates new storage that is large enough store the resulting
/// elements.
///
/// var numbers = [10, 20, 30, 40, 50]
/// // numbers.count == 5
/// // numbers.capacity == 5
///
/// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
/// // numbers.count == 10
/// // numbers.capacity == 10
@inlinable
public var capacity: Int {
return _getCapacity()
}
/// An object that guarantees the lifetime of this array's elements.
@inlinable
public // @testable
var _owner: AnyObject? {
return _buffer.owner
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
@inlinable
public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {
@inline(__always) // FIXME(TODO: JIRA): Hack around test failure
get { return _buffer.firstElementAddressIfContiguous }
}
@inlinable
internal var _baseAddress: UnsafeMutablePointer<Element> {
return _buffer.firstElementAddress
}
}
extension ArraySlice: RandomAccessCollection, MutableCollection {
/// The index type for arrays, `Int`.
///
/// `ArraySlice` instances are not always indexed from zero. Use `startIndex`
/// and `endIndex` as the bounds for any element access, instead of `0` and
/// `count`.
public typealias Index = Int
/// The type that represents the indices that are valid for subscripting an
/// array, in ascending order.
public typealias Indices = Range<Int>
/// The type that allows iteration over an array's elements.
public typealias Iterator = IndexingIterator<ArraySlice>
/// The position of the first element in a nonempty array.
///
/// `ArraySlice` instances are not always indexed from zero. Use `startIndex`
/// and `endIndex` as the bounds for any element access, instead of `0` and
/// `count`.
///
/// If the array is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Int {
return _buffer.startIndex
}
/// The array's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// When you need a range that includes the last element of an array, use the
/// half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.firstIndex(of: 30) {
/// print(numbers[i ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the array is empty, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Int {
return _buffer.endIndex
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index immediately after `i`.
@inlinable
public func index(after i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i + 1
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inlinable
public func formIndex(after i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
i += 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index immediately before `i`.
@inlinable
public func index(before i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i - 1
}
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
@inlinable
public func formIndex(before i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
i -= 1
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If
/// `distance` is positive, this is the same value as the result of
/// `distance` calls to `index(after:)`. If `distance` is negative, this
/// is the same value as the result of `abs(distance)` calls to
/// `index(before:)`.
@inlinable
public func index(_ i: Int, offsetBy distance: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return i + distance
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.index(numbers.startIndex,
/// offsetBy: 4,
/// limitedBy: numbers.endIndex) {
/// print(numbers[i])
/// }
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the
/// index passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If
/// `distance > 0`, `limit` has no effect if it is less than `i`.
/// Likewise, if `distance < 0`, `limit` has no effect if it is greater
/// than `i`.
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(1)
@inlinable
public func index(
_ i: Int, offsetBy distance: Int, limitedBy limit: Int
) -> Int? {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
let l = limit - i
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
return nil
}
return i + distance
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
@inlinable
public func distance(from start: Int, to end: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
// capable of creating partial specializations yet.
// NOTE: Range checks are not performed here, because it is done later by
// the subscript function.
return end - start
}
@inlinable
public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
@inlinable
public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
/// Accesses the element at the specified position.
///
/// The following example uses indexed subscripting to update an array's
/// second element. After assigning the new value (`"Butler"`) at a specific
/// position, that value is immediately available at that same position.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// - Parameter index: The position of the element to access. `index` must be
/// greater than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from an array is O(1). Writing is O(1)
/// unless the array's storage is shared with another array or uses a
/// bridged `NSArray` instance as its storage, in which case writing is
/// O(*n*), where *n* is the length of the array.
@inlinable
public subscript(index: Int) -> Element {
get {
// This call may be hoisted or eliminated by the optimizer. If
// there is an inout violation, this value may be stale so needs to be
// checked again below.
let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()
// Make sure the index is in range and wasNativeTypeChecked is
// still valid.
let token = _checkSubscript(
index, wasNativeTypeChecked: wasNativeTypeChecked)
return _getElement(
index, wasNativeTypeChecked: wasNativeTypeChecked,
matchingSubscriptCheck: token)
}
_modify {
_makeMutableAndUnique() // makes the array native, too
_checkSubscript_native(index)
let address = _buffer.subscriptBaseAddress + index
yield &address.pointee
_endMutation();
}
}
/// Accesses a contiguous subrange of the array's elements.
///
/// The returned `ArraySlice` instance uses the same indices for the same
/// elements as the original array. In particular, that slice, unlike an
/// array, may have a nonzero `startIndex` and an `endIndex` that is not
/// equal to `count`. Always use the slice's `startIndex` and `endIndex`
/// properties instead of assuming that its indices start or end at a
/// particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let i = streetsSlice.firstIndex(of: "Evarts") // 4
/// print(streets[i!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of integers. The bounds of the range must be
/// valid indices of the array.
@inlinable
public subscript(bounds: Range<Int>) -> ArraySlice<Element> {
get {
_checkIndex(bounds.lowerBound)
_checkIndex(bounds.upperBound)
return ArraySlice(_buffer: _buffer[bounds])
}
set(rhs) {
_checkIndex(bounds.lowerBound)
_checkIndex(bounds.upperBound)
// If the replacement buffer has same identity, and the ranges match,
// then this was a pinned in-place modification, nothing further needed.
if self[bounds]._buffer.identity != rhs._buffer.identity
|| bounds != rhs.startIndex..<rhs.endIndex {
self.replaceSubrange(bounds, with: rhs)
}
}
}
/// The number of elements in the array.
@inlinable
public var count: Int {
return _getCount()
}
}
extension ArraySlice: ExpressibleByArrayLiteral {
/// Creates an array from the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new array by using an array
/// literal as its value. To do this, enclose a comma-separated list of
/// values in square brackets.
///
/// Here, an array of strings is created from an array literal holding only
/// strings:
///
/// let ingredients: ArraySlice =
/// ["cocoa beans", "sugar", "cocoa butter", "salt"]
///
/// - Parameter elements: A variadic list of elements of the new array.
@inlinable
public init(arrayLiteral elements: Element...) {
self.init(_buffer: ContiguousArray(elements)._buffer)
}
}
extension ArraySlice: RangeReplaceableCollection {
/// Creates a new, empty array.
///
/// This is equivalent to initializing with an empty array literal.
/// For example:
///
/// var emptyArray = Array<Int>()
/// print(emptyArray.isEmpty)
/// // Prints "true"
///
/// emptyArray = []
/// print(emptyArray.isEmpty)
/// // Prints "true"
@inlinable
@_semantics("array.init.empty")
public init() {
_buffer = _Buffer()
}
/// Creates an array containing the elements of a sequence.
///
/// You can use this initializer to create an array from any other type that
/// conforms to the `Sequence` protocol. For example, you might want to
/// create an array with the integers from 1 through 7. Use this initializer
/// around a range instead of typing all those numbers in an array literal.
///
/// let numbers = Array(1...7)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7]"
///
/// You can also use this initializer to convert a complex sequence or
/// collection type back to an array. For example, the `keys` property of
/// a dictionary isn't an array with its own storage, it's a collection
/// that maps its elements from the dictionary only when they're
/// accessed, saving the time and space needed to allocate an array. If
/// you need to pass those keys to a method that takes an array, however,
/// use this initializer to convert that list from its type of
/// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple
/// `[String]`.
///
/// func cacheImagesWithNames(names: [String]) {
/// // custom image loading and caching
/// }
///
/// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
/// "Gold": 50, "Cerise": 320]
/// let colorNames = Array(namedHues.keys)
/// cacheImagesWithNames(colorNames)
///
/// print(colorNames)
/// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
///
/// - Parameter s: The sequence of elements to turn into an array.
@inlinable
public init<S: Sequence>(_ s: S)
where S.Element == Element {
self.init(_buffer: s._copyToContiguousArray()._buffer)
}
/// Creates a new array containing the specified number of a single, repeated
/// value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@inlinable
@_semantics("array.init")
public init(repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Can't construct ArraySlice with count < 0")
if count > 0 {
_buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)
_buffer.count = count
var p = _buffer.firstElementAddress
for _ in 0..<count {
p.initialize(to: repeatedValue)
p += 1
}
} else {
_buffer = _Buffer()
}
_endMutation()
}
@inline(never)
@usableFromInline
internal static func _allocateBufferUninitialized(
minimumCapacity: Int
) -> _Buffer {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: 0, minimumCapacity: minimumCapacity)
return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0)
}
/// Construct a ArraySlice of `count` uninitialized elements.
@inlinable
@_semantics("array.init")
internal init(_uninitializedCount count: Int) {
_precondition(count >= 0, "Can't construct ArraySlice with count < 0")
// Note: Sinking this constructor into an else branch below causes an extra
// Retain/Release.
_buffer = _Buffer()
if count > 0 {
// Creating a buffer instead of calling reserveCapacity saves doing an
// unnecessary uniqueness check. We disable inlining here to curb code
// growth.
_buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)
_buffer.count = count
}
// Can't store count here because the buffer might be pointing to the
// shared empty array.
_endMutation()
}
/// Entry point for `Array` literal construction; builds and returns
/// a ArraySlice of `count` uninitialized elements.
@inlinable
@_semantics("array.uninitialized")
internal static func _allocateUninitialized(
_ count: Int
) -> (ArraySlice, UnsafeMutablePointer<Element>) {
let result = ArraySlice(_uninitializedCount: count)
return (result, result._buffer.firstElementAddress)
}
//===--- basic mutations ------------------------------------------------===//
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to an array, use this method
/// to avoid multiple reallocations. This method ensures that the array has
/// unique, mutable, contiguous storage, with space allocated for at least
/// the requested number of elements.
///
/// Calling the `reserveCapacity(_:)` method on an array with bridged storage
/// triggers a copy to contiguous storage even if the existing storage
/// has room to store `minimumCapacity` elements.
///
/// For performance reasons, the size of the newly allocated storage might be
/// greater than the requested capacity. Use the array's `capacity` property
/// to determine the size of the new storage.
///
/// Preserving an Array's Geometric Growth Strategy
/// ===============================================
///
/// If you implement a custom data structure backed by an array that grows
/// dynamically, naively calling the `reserveCapacity(_:)` method can lead
/// to worse than expected performance. Arrays need to follow a geometric
/// allocation pattern for appending elements to achieve amortized
/// constant-time performance. The `Array` type's `append(_:)` and
/// `append(contentsOf:)` methods take care of this detail for you, but
/// `reserveCapacity(_:)` allocates only as much space as you tell it to
/// (padded to a round value), and no more. This avoids over-allocation, but
/// can result in insertion not having amortized constant-time performance.
///
/// The following code declares `values`, an array of integers, and the
/// `addTenQuadratic()` function, which adds ten more values to the `values`
/// array on each call.
///
/// var values: [Int] = [0, 1, 2, 3]
///
/// // Don't use 'reserveCapacity(_:)' like this
/// func addTenQuadratic() {
/// let newCount = values.count + 10
/// values.reserveCapacity(newCount)
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// The call to `reserveCapacity(_:)` increases the `values` array's capacity
/// by exactly 10 elements on each pass through `addTenQuadratic()`, which
/// is linear growth. Instead of having constant time when averaged over
/// many calls, the function may decay to performance that is linear in
/// `values.count`. This is almost certainly not what you want.
///
/// In cases like this, the simplest fix is often to simply remove the call
/// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array
/// for you.
///
/// func addTen() {
/// let newCount = values.count + 10
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// If you need more control over the capacity of your array, implement your
/// own geometric growth strategy, passing the size you compute to
/// `reserveCapacity(_:)`.
///
/// - Parameter minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the array.
@inlinable
@_semantics("array.mutate_unknown")
public mutating func reserveCapacity(_ minimumCapacity: Int) {
if !_buffer.beginCOWMutation() || _buffer.capacity < minimumCapacity {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: count, minimumCapacity: minimumCapacity)
_buffer._copyContents(
subRange: _buffer.indices,
initializing: newBuffer.firstElementAddress)
_buffer = _Buffer(
_buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex)
}
_internalInvariant(capacity >= minimumCapacity)
_endMutation()
}
/// Copy the contents of the current buffer to a new unique mutable buffer.
/// The count of the new buffer is set to `oldCount`, the capacity of the
/// new buffer is big enough to hold 'oldCount' + 1 elements.
@inline(never)
@inlinable // @specializable
internal mutating func _copyToNewBuffer(oldCount: Int) {
let newCount = oldCount + 1
var newBuffer = _buffer._forceCreateUniqueMutableBuffer(
countForNewBuffer: oldCount, minNewCapacity: newCount)
_buffer._arrayOutOfPlaceUpdate(
&newBuffer, oldCount, 0)
}
@inlinable
@_semantics("array.make_mutable")
internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {
if _slowPath(!_buffer.beginCOWMutation()) {
_copyToNewBuffer(oldCount: _buffer.count)
}
}
@inlinable
@_semantics("array.mutate_unknown")
internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {
// Due to make_mutable hoisting the situation can arise where we hoist
// _makeMutableAndUnique out of loop and use it to replace
// _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the
// array was empty _makeMutableAndUnique does not replace the empty array
// buffer by a unique buffer (it just replaces it by the empty array
// singleton).
// This specific case is okay because we will make the buffer unique in this
// function because we request a capacity > 0 and therefore _copyToNewBuffer
// will be called creating a new buffer.
let capacity = _buffer.capacity
_internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced())
if _slowPath(oldCount + 1 > capacity) {
_copyToNewBuffer(oldCount: oldCount)
}
}
@inlinable
@_semantics("array.mutate_unknown")
internal mutating func _appendElementAssumeUniqueAndCapacity(
_ oldCount: Int,
newElement: __owned Element
) {
_internalInvariant(_buffer.isMutableAndUniquelyReferenced())
_internalInvariant(_buffer.capacity >= _buffer.count + 1)
_buffer.count = oldCount + 1
(_buffer.firstElementAddress + oldCount).initialize(to: newElement)
}
/// Adds a new element at the end of the array.
///
/// Use this method to append a single element to the end of a mutable array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// Because arrays increase their allocated capacity using an exponential
/// strategy, appending a single element to an array is an O(1) operation
/// when averaged over many calls to the `append(_:)` method. When an array
/// has additional capacity and is not sharing its storage with another
/// instance, appending an element is O(1). When an array needs to
/// reallocate storage before appending or its storage is shared with
/// another copy, appending is O(*n*), where *n* is the length of the array.
///
/// - Parameter newElement: The element to append to the array.
///
/// - Complexity: O(1) on average, over many calls to `append(_:)` on the
/// same array.
@inlinable
@_semantics("array.append_element")
public mutating func append(_ newElement: __owned Element) {
_makeUniqueAndReserveCapacityIfNotUnique()
let oldCount = _getCount()
_reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)
_appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement)
_endMutation()
}
/// Adds the elements of a sequence to the end of the array.
///
/// Use this method to append the elements of a sequence to the end of this
/// array. This example appends the elements of a `Range<Int>` instance
/// to an array of integers.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the array.
///
/// - Complexity: O(*m*) on average, where *m* is the length of
/// `newElements`, over many calls to `append(contentsOf:)` on the same
/// array.
@inlinable
@_semantics("array.append_contentsOf")
public mutating func append<S: Sequence>(contentsOf newElements: __owned S)
where S.Element == Element {
let newElementsCount = newElements.underestimatedCount
reserveCapacityForAppend(newElementsCount: newElementsCount)
_ = _buffer.beginCOWMutation()
let oldCount = self.count
let startNewElements = _buffer.firstElementAddress + oldCount
let buf = UnsafeMutableBufferPointer(
start: startNewElements,
count: self.capacity - oldCount)
let (remainder,writtenUpTo) = buf.initialize(from: newElements)
// trap on underflow from the sequence's underestimate:
let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo)
_precondition(newElementsCount <= writtenCount,
"newElements.underestimatedCount was an overestimate")
// can't check for overflow as sequences can underestimate
// This check prevents a data race writing to _swiftEmptyArrayStorage
if writtenCount > 0 {
_buffer.count += writtenCount
}
if writtenUpTo == buf.endIndex {
// there may be elements that didn't fit in the existing buffer,
// append them in slow sequence-only mode
_buffer._arrayAppendSequence(IteratorSequence(remainder))
}
_endMutation()
}
@inlinable
@_semantics("array.reserve_capacity_for_append")
internal mutating func reserveCapacityForAppend(newElementsCount: Int) {
let oldCount = self.count
let oldCapacity = self.capacity
let newCount = oldCount + newElementsCount
// Ensure uniqueness, mutability, and sufficient storage. Note that
// for consistency, we need unique self even if newElements is empty.
self.reserveCapacity(
newCount > oldCapacity ?
Swift.max(newCount, _growArrayCapacity(oldCapacity))
: newCount)
}
@inlinable
public mutating func _customRemoveLast() -> Element? {
_precondition(count > 0, "Can't removeLast from an empty ArraySlice")
// FIXME(performance): if `self` is uniquely referenced, we should remove
// the element as shown below (this will deallocate the element and
// decrease memory use). If `self` is not uniquely referenced, the code
// below will make a copy of the storage, which is wasteful. Instead, we
// should just shrink the view without allocating new storage.
let i = endIndex
// We don't check for overflow in `i - 1` because `i` is known to be
// positive.
let result = self[i &- 1]
self.replaceSubrange((i &- 1)..<i, with: EmptyCollection())
return result
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved up to
/// close the gap.
///
/// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"
///
/// - Parameter index: The position of the element to remove. `index` must
/// be a valid index of the array.
/// - Returns: The element at the specified index.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@inlinable
@discardableResult
public mutating func remove(at index: Int) -> Element {
let result = self[index]
self.replaceSubrange(index..<(index + 1), with: EmptyCollection())
return result
}
/// Inserts a new element at the specified position.
///
/// The new element is inserted before the element currently at the specified
/// index. If you pass the array's `endIndex` property as the `index`
/// parameter, the new element is appended to the array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// - Parameter newElement: The new element to insert into the array.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index of the array or equal to its `endIndex`
/// property.
///
/// - Complexity: O(*n*), where *n* is the length of the array. If
/// `i == endIndex`, this method is equivalent to `append(_:)`.
@inlinable
public mutating func insert(_ newElement: __owned Element, at i: Int) {
_checkIndex(i)
self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}
/// Removes all elements from the array.
///
/// - Parameter keepCapacity: Pass `true` to keep the existing capacity of
/// the array after removing its elements. The default value is
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
}
else {
self.replaceSubrange(indices, with: EmptyCollection())
}
}
//===--- algorithms -----------------------------------------------------===//
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeMutableBufferPointer {
(bufferPointer) -> R in
return try body(&bufferPointer)
}
}
@inlinable
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeMutableBufferPointer {
(bufferPointer) -> R in
return try body(&bufferPointer)
}
}
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withUnsafeBufferPointer {
(bufferPointer) -> R in
return try body(bufferPointer)
}
}
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
if let n = _buffer.requestNativeBuffer() {
return ContiguousArray(_buffer: n)
}
return _copyCollectionToContiguousArray(self)
}
}
extension ArraySlice: CustomReflectable {
/// A mirror that reflects the array.
public var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: self,
displayStyle: .collection)
}
}
extension ArraySlice: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the array and its elements.
public var description: String {
return _makeCollectionDescription()
}
/// A textual representation of the array and its elements, suitable for
/// debugging.
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "ArraySlice")
}
}
extension ArraySlice {
@usableFromInline @_transparent
internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) {
let p = _baseAddressIfContiguous
if _fastPath(p != nil || isEmpty) {
return (_owner, UnsafeRawPointer(p))
}
let n = ContiguousArray(self._buffer)._buffer
return (n.owner, UnsafeRawPointer(n.firstElementAddress))
}
}
extension ArraySlice {
/// Calls a closure with a pointer to the array's contiguous storage.
///
/// Often, the optimizer can eliminate bounds checks within an array
/// algorithm, but when that fails, invoking the same algorithm on the
/// buffer pointer passed into your closure lets you trade safety for speed.
///
/// The following example shows how you can iterate over the contents of the
/// buffer pointer:
///
/// let numbers = [1, 2, 3, 4, 5]
/// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
/// var result = 0
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
/// result += buffer[i]
/// }
/// return result
/// }
/// // 'sum' == 9
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that
/// points to the contiguous storage for the array. If
/// `body` has a return value, that value is also used as the return value
/// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is
/// valid only for the duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
return try _buffer.withUnsafeBufferPointer(body)
}
/// Calls the given closure with a pointer to the array's mutable contiguous
/// storage.
///
/// Often, the optimizer can eliminate bounds checks within an array
/// algorithm, but when that fails, invoking the same algorithm on the
/// buffer pointer passed into your closure lets you trade safety for speed.
///
/// The following example shows how modifying the contents of the
/// `UnsafeMutableBufferPointer` argument to `body` alters the contents of
/// the array:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.withUnsafeMutableBufferPointer { buffer in
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {
/// buffer.swapAt(i, i + 1)
/// }
/// }
/// print(numbers)
/// // Prints "[2, 1, 4, 3, 5]"
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or
/// return the pointer for later use.
///
/// - Warning: Do not rely on anything about the array that is the target of
/// this method during execution of the `body` closure; it might not
/// appear to have its correct value. Instead, use only the
/// `UnsafeMutableBufferPointer` argument to `body`.
///
/// - Parameter body: A closure with an `UnsafeMutableBufferPointer`
/// parameter that points to the contiguous storage for the array.
/// If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeMutableBufferPointer(_:)`
/// method. The pointer argument is valid only for the duration of the
/// method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@_semantics("array.withUnsafeMutableBufferPointer")
@inlinable // FIXME(inline-always)
@inline(__always) // Performance: This method should get inlined into the
// caller such that we can combine the partial apply with the apply in this
// function saving on allocating a closure context. This becomes unnecessary
// once we allocate noescape closures on the stack.
public mutating func withUnsafeMutableBufferPointer<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
let count = self.count
// Ensure unique storage
_makeMutableAndUnique()
// Ensure that body can't invalidate the storage or its bounds by
// moving self into a temporary working array.
// NOTE: The stack promotion optimization that keys of the
// "array.withUnsafeMutableBufferPointer" semantics annotation relies on the
// array buffer not being able to escape in the closure. It can do this
// because we swap the array buffer in self with an empty buffer here. Any
// escape via the address of self in the closure will therefore escape the
// empty array.
var work = ArraySlice()
(work, self) = (self, work)
// Create an UnsafeBufferPointer over work that we can pass to body
let pointer = work._buffer.firstElementAddress
var inoutBufferPointer = UnsafeMutableBufferPointer(
start: pointer, count: count)
// Put the working array back before returning.
defer {
_precondition(
inoutBufferPointer.baseAddress == pointer &&
inoutBufferPointer.count == count,
"ArraySlice withUnsafeMutableBufferPointer: replacing the buffer is not allowed")
(work, self) = (self, work)
_endMutation()
}
// Invoke the body.
return try body(&inoutBufferPointer)
}
@inlinable
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) }
// It is not OK for there to be no pointer/not enough space, as this is
// a precondition and Array never lies about its count.
guard var p = buffer.baseAddress
else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") }
_precondition(self.count <= buffer.count,
"Insufficient space allocated to copy array contents")
if let s = _baseAddressIfContiguous {
p.initialize(from: s, count: self.count)
// Need a _fixLifetime bracketing the _baseAddressIfContiguous getter
// and all uses of the pointer it returns:
_fixLifetime(self._owner)
} else {
for x in self {
p.initialize(to: x)
p += 1
}
}
var it = IndexingIterator(_elements: self)
it._position = endIndex
return (it,buffer.index(buffer.startIndex, offsetBy: self.count))
}
}
extension ArraySlice {
/// Replaces a range of elements with the elements in the specified
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements at the same location. The
/// number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The start and end of
/// a subrange must be valid indices of the array.
/// - newElements: The new elements to add to the array.
///
/// - Complexity: O(*n* + *m*), where *n* is length of the array and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the array, this method is
/// equivalent to `append(contentsOf:)`.
@inlinable
@_semantics("array.mutate_unknown")
public mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newElements: __owned C
) where C: Collection, C.Element == Element {
_precondition(subrange.lowerBound >= _buffer.startIndex,
"ArraySlice replace: subrange start is before the startIndex")
_precondition(subrange.upperBound <= _buffer.endIndex,
"ArraySlice replace: subrange extends past the end")
let oldCount = _buffer.count
let eraseCount = subrange.count
let insertCount = newElements.count
let growth = insertCount - eraseCount
if _buffer.beginCOWMutation() && _buffer.capacity >= oldCount + growth {
_buffer.replaceSubrange(
subrange, with: insertCount, elementsOf: newElements)
} else {
_buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount)
}
_endMutation()
}
}
extension ArraySlice: Equatable where Element: Equatable {
/// Returns a Boolean value indicating whether two arrays contain the same
/// elements in the same order.
///
/// You can use the equal-to operator (`==`) to compare any two arrays
/// that store the same, `Equatable`-conforming element type.
///
/// - Parameters:
/// - lhs: An array to compare.
/// - rhs: Another array to compare.
@inlinable
public static func ==(lhs: ArraySlice<Element>, rhs: ArraySlice<Element>) -> Bool {
let lhsCount = lhs.count
if lhsCount != rhs.count {
return false
}
// Test referential equality.
if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity {
return true
}
var streamLHS = lhs.makeIterator()
var streamRHS = rhs.makeIterator()
var nextLHS = streamLHS.next()
while nextLHS != nil {
let nextRHS = streamRHS.next()
if nextLHS != nextRHS {
return false
}
nextLHS = streamLHS.next()
}
return true
}
}
extension ArraySlice: Hashable where Element: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(count) // discriminator
for element in self {
hasher.combine(element)
}
}
}
extension ArraySlice {
/// Calls the given closure with a pointer to the underlying bytes of the
/// array's mutable contiguous storage.
///
/// The array's `Element` type must be a *trivial type*, which can be copied
/// with just a bit-for-bit copy without any indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references are trivial, as are imported C structs
/// and enums.
///
/// The following example copies bytes from the `byteValues` array into
/// `numbers`, an array of `Int32`:
///
/// var numbers: [Int32] = [0, 0]
/// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]
///
/// numbers.withUnsafeMutableBytes { destBytes in
/// byteValues.withUnsafeBytes { srcBytes in
/// destBytes.copyBytes(from: srcBytes)
/// }
/// }
/// // numbers == [1, 2]
///
/// - Note: This example shows the behavior on a little-endian platform.
///
/// The pointer passed as an argument to `body` is valid only for the
/// lifetime of the closure. Do not escape it from the closure for later
/// use.
///
/// - Warning: Do not rely on anything about the array that is the target of
/// this method during execution of the `body` closure; it might not
/// appear to have its correct value. Instead, use only the
/// `UnsafeMutableRawBufferPointer` argument to `body`.
///
/// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer`
/// parameter that points to the contiguous storage for the array.
/// If no such storage exists, it is created. If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeMutableBytes(_:)` method.
/// The argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public mutating func withUnsafeMutableBytes<R>(
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
return try self.withUnsafeMutableBufferPointer {
return try body(UnsafeMutableRawBufferPointer($0))
}
}
/// Calls the given closure with a pointer to the underlying bytes of the
/// array's contiguous storage.
///
/// The array's `Element` type must be a *trivial type*, which can be copied
/// with just a bit-for-bit copy without any indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references are trivial, as are imported C structs
/// and enums.
///
/// The following example copies the bytes of the `numbers` array into a
/// buffer of `UInt8`:
///
/// var numbers: [Int32] = [1, 2, 3]
/// var byteBuffer: [UInt8] = []
/// numbers.withUnsafeBytes {
/// byteBuffer.append(contentsOf: $0)
/// }
/// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
///
/// - Note: This example shows the behavior on a little-endian platform.
///
/// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter
/// that points to the contiguous storage for the array.
/// If no such storage exists, it is created. If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeBytes(_:)` method. The
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
return try self.withUnsafeBufferPointer {
try body(UnsafeRawBufferPointer($0))
}
}
}
extension ArraySlice {
@inlinable
public // @testable
init(_startIndex: Int) {
self.init(
_buffer: _Buffer(
_buffer: ContiguousArray()._buffer,
shiftedToStartIndex: _startIndex))
}
}
| apache-2.0 | 1fd89816d3ad16142cd315f48ebd31d8 | 37.631094 | 99 | 0.658658 | 4.396282 | false | false | false | false |
UsabilityEtc/nscolor-components | Sources/NSColor+Components.swift | 1 | 2528 | //
// NSColor+Components.swift
// NSColorComponents
//
// Created by Jeffrey Morgan on 28/02/2016.
// Copyright © 2016 Jeffrey Morgan under the MIT License.
//
import Cocoa
public extension NSColor {
/**
A tuple of the red, green, blue and alpha components of this NSColor calibrated
in the RGB color space. Each tuple value is a CGFloat between 0 and 1.
*/
var CGFloatRGB: (red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat)? {
if let calibratedColor = colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
calibratedColor.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent)
return (redComponent, greenComponent, blueComponent, alphaComponent)
}
return nil
}
/**
A tuple of the red, green, blue and alpha components of this NSColor calibrated
in the RGB color space. Each tuple value is an Int between 0 and 255.
*/
var IntRGB: (red:Int, green:Int, blue:Int, alpha:Int)? {
if let (red, green, blue, alpha) = CGFloatRGB {
return (Int(red*255), Int(green*255), Int(blue*255), Int(alpha*255))
}
return nil
}
}
public extension NSColor {
/**
A tuple of the hue, saturation, brightness and alpha components of this NSColor
calibrated in the RGB color space. Each tuple value is a CGFloat between 0 and 1.
*/
var CGFloatHSB: (hue:CGFloat, saturation:CGFloat, brightness:CGFloat, alpha:CGFloat)? {
if let calibratedColor = colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
var hueComponent: CGFloat = 0
var saturationComponent: CGFloat = 0
var brightnessComponent: CGFloat = 0
var alphaFloatValue: CGFloat = 0
calibratedColor.getHue(&hueComponent, saturation: &saturationComponent, brightness: &brightnessComponent, alpha: &alphaFloatValue)
return (hueComponent, saturationComponent, brightnessComponent, alphaFloatValue)
}
return nil
}
/**
A tuple of the hue, saturation, brightness and alpha components of this NSColor
calibrated in the RGB color space. Each tuple value is an Int between 0 and 255.
*/
var IntHSB: (hue:Int, saturation:Int, brightness:Int, alpha:Int)? {
if let (hue, saturation, brightness, alpha) = CGFloatHSB {
return (Int(hue*255), Int(saturation*255), Int(brightness*255), Int(alpha*255))
}
return nil
}
}
| mit | 305d0f6a9bb100a5d4990b88f32bc62b | 34.591549 | 136 | 0.698457 | 4.15625 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/ScreenNavigationModel.swift | 1 | 992 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct ScreenNavigationModel {
public let leadingButton: Screen.Style.LeadingButton
public let trailingButton: Screen.Style.TrailingButton
public let barStyle: Screen.Style.Bar
public let titleViewStyle: Screen.Style.TitleView
public init(
leadingButton: Screen.Style.LeadingButton,
trailingButton: Screen.Style.TrailingButton,
titleViewStyle: Screen.Style.TitleView,
barStyle: Screen.Style.Bar
) {
self.leadingButton = leadingButton
self.trailingButton = trailingButton
self.titleViewStyle = titleViewStyle
self.barStyle = barStyle
}
}
extension ScreenNavigationModel {
public static let noneDark = ScreenNavigationModel(
leadingButton: .none,
trailingButton: .none,
titleViewStyle: .none,
barStyle: .darkContent()
)
}
extension ScreenNavigationModel: Equatable {}
| lgpl-3.0 | 27cdf20d06f70f1873400a17ab5be87f | 29.030303 | 62 | 0.712412 | 4.696682 | false | false | false | false |
randallli/material-components-ios | components/Cards/tests/unit/MDCCardColorThemerTests.swift | 1 | 1538 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
import MaterialComponents.MaterialCards
import MaterialComponents.MaterialCards_ColorThemer
class CardColorThemerTests: XCTestCase {
func testCardColorThemer() {
// Given
let colorScheme = MDCSemanticColorScheme()
let card = MDCCard()
colorScheme.surfaceColor = .red
card.backgroundColor = .white
// When
MDCCardsColorThemer.applySemanticColorScheme(colorScheme, to: card)
// Then
XCTAssertEqual(card.backgroundColor, colorScheme.surfaceColor)
}
func testCardCollectionCellColorThemer() {
// Given
let colorScheme = MDCSemanticColorScheme()
let cardCell = MDCCardCollectionCell()
colorScheme.surfaceColor = .red
cardCell.backgroundColor = .white
// When
MDCCardsColorThemer.applySemanticColorScheme(colorScheme, toCardCell: cardCell)
// Then
XCTAssertEqual(cardCell.backgroundColor, colorScheme.surfaceColor)
}
}
| apache-2.0 | 1f20fe3cd87259ebc95f769867c5b345 | 29.76 | 85 | 0.763979 | 4.776398 | false | true | false | false |
Poligun/NihonngoSwift | Nihonngo/LoadingCell.swift | 1 | 1621 | //
// LoadingCell.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/13.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class LoadingCell: BaseCell {
private let label = UILabel()
private let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
override class var defaultReuseIdentifier: String {
return "LoadingCell"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont.systemFontOfSize(15.0)
label.textColor = UIColor.blackColor()
label.textAlignment = .Center
self.contentView.addSubview(label)
indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
indicator.startAnimating()
self.contentView.addSubview(indicator)
self.contentView.addConstraints(NSLayoutConstraint.constraints(
views: ["label": label, "indicator": indicator],
formats: "V:|-8-[label]-8-|",
"V:|-8-[indicator]-8-|",
"H:|-8-[label]-8-|",
"H:[indicator]-8-|"))
}
func setLoadingText(text: String, animating: Bool) {
label.text = text
if animating {
indicator.startAnimating()
} else {
indicator.stopAnimating()
}
}
}
| mit | 119279a4af9c3067025f1b5b6b1f2b5c | 28.981481 | 110 | 0.620136 | 4.996914 | false | false | false | false |
zdima/ZDMatrixPopover | src/ZDMatrixPopover.swift | 1 | 3337 | //
// ZDMatrixPopover.swift
// ZDMatrixPopover
//
// Created by Dmitriy Zakharkin on 1/7/17.
// Copyright © 2017 Dmitriy Zakharkin. All rights reserved.
//
import Cocoa
@objc public protocol ZDMatrixPopoverDelegate {
/// getColumnFormatter return an optional Formatter object to be use for specified column.
/// This method is called when popup is constructed first time or when data size has changed since last call.
/// This method can return nil if there is no formatter to be used.
/// When attributedString is called, the withDefaultAttributes include following information:
/// "column" : NSNumber()
/// "row" : NSNumber
/// "alignment" : NSTextAlignment
func getColumnFormatter(column: Int) -> Formatter?
/// getColumnAlignment return an optional alignment attribute for specified column.
/// This method is called when popup is constructed first time or when data size has changed since last call.
/// This method can return nil if there is no special aligment needed.
/// By default all count will be aligned to NSTextAlignment.left
func getColumnAlignment(column: Int) -> NSTextAlignment
/// getColumnWidth return width of the column.
/// The width will be calculated based on content when getColumnWidth return -1.
/// By default getColumnWidth will return -1.
func getColumnWidth(column: Int) -> Int
}
@objc(ZDMatrixPopover)
@IBDesignable public class ZDMatrixPopover: NSObject {
internal var controller: ZDMatrixPopoverController!
public required override init() {
super.init()
controller = ZDMatrixPopoverController(owner:self)
}
public override func prepareForInterfaceBuilder() {
titleFontSize = NSFont.systemFontSize(for: NSControlSize.regular)
}
/// Delegate object of type ZDMatrixPopoverDelegate
/// Due to storyboard limitation we have to use AnyObject as type to allow storyboard binding.
///
/// Interface Builder
///
/// Interface Builder does not support connecting to an outlet in a Swift file
/// when the outlet’s type is a protocol. Declare the outlet's type as AnyObject
/// or NSObject, connect objects to the outlet using Interface Builder, then change
/// the outlet's type back to the protocol. (17023935)
///
@IBOutlet public weak var delegate: AnyObject? {
set {
if let newDelegate = newValue as? ZDMatrixPopoverDelegate {
self.controller.m_delegate = newDelegate
}
}
get {
return self.controller.m_delegate
}
}
@IBInspectable public var titleFontSize: CGFloat = NSFont.systemFontSize(for: NSControlSize.regular)
@IBInspectable public var dataFontSize: CGFloat = NSFont.systemFontSize(for: NSControlSize.regular)
public func show(
data: [[Any]],
title: String,
relativeTo rect: NSRect,
of view: NSView,
preferredEdge: NSRectEdge) throws {
try controller.show(data: data, title: title, relativeTo: rect, of: view, preferredEdge: preferredEdge)
}
public func close() throws {
try controller.close()
}
public private(set) var isShown: Bool {
get {
return controller.isShown
}
set {
}
}
}
| mit | 87d806b962710c0083480021e450ffb4 | 36.886364 | 113 | 0.678164 | 4.895742 | false | false | false | false |
bradleypj823/ParseAndCoreImage | ParseCoreImage/GalleryViewController.swift | 1 | 3070 | //
// GalleryViewController.swift
// ParseCoreImage
//
// Created by Bradley Johnson on 3/5/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import UIKit
import Photos
protocol GalleryDelegate: class {
func userDidSelectImage(image : UIImage)
}
class GalleryViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
weak var delegate : GalleryDelegate!
var scale : CGFloat = 1.0
//photos framework properties
var assetsFetchResults : PHFetchResult!
var assetCollection : PHAssetCollection!
var imageManager = PHCachingImageManager()
var destinationImageSize : CGSize!
var flowLayout : UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
self.imageManager = PHCachingImageManager()
self.assetsFetchResults = PHAsset.fetchAssetsWithOptions(nil)
self.collectionView.dataSource = self
self.collectionView.delegate = self
let pinch = UIPinchGestureRecognizer(target: self, action: "pinchRecognized:")
self.collectionView.addGestureRecognizer(pinch)
self.flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// Do any additional setup after loading the view.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.assetsFetchResults.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GalleryCell", forIndexPath: indexPath) as! GalleryCell
let asset = self.assetsFetchResults[indexPath.row] as! PHAsset
self.imageManager.requestImageForAsset(asset, targetSize: self.flowLayout.itemSize, contentMode: PHImageContentMode.AspectFill, options: nil) { (requestedImage, info) -> Void in
cell.imageView.image = requestedImage
}
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(75 * self.scale, 75 * self.scale)
}
func pinchRecognized(sender : UIPinchGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Changed {
self.scale = sender.scale
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let asset = self.assetsFetchResults[indexPath.row] as! PHAsset
self.imageManager.requestImageForAsset(asset, targetSize: CGSize(width: 300, height: 400), contentMode: PHImageContentMode.AspectFill, options: nil) { (requestedImage, info) -> Void in
self.delegate?.userDidSelectImage(requestedImage)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
| mit | 9dc05136fc5b6f7f978415e3f44efcab | 33.494382 | 188 | 0.751792 | 5.551537 | false | false | false | false |
bvic23/VinceRP | VinceRP/Common/Util/WeakSet.swift | 1 | 1668 | //
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
// https://github.com/scala/scala/blob/2.11.x/src/library/scala/ref/WeakReference.scala
class WeakReference<T: AnyObject where T: Hashable>: Hashable {
weak var value: T?
init(_ value: T) {
self.value = value
}
var hashValue: Int {
guard let v = self.value else {
return 0
}
return v.hashValue
}
}
func ==<T>(lhs: WeakReference<T>, rhs: WeakReference<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public class WeakSet<T: Hashable where T: AnyObject> {
private var _array: [WeakReference<T>]
public init() {
_array = Array()
}
public init(_ array: [T]) {
_array = array.map {
WeakReference($0)
}
}
public var set: Set<T> {
return Set(self.array())
}
public func insert(member: T) {
for e in _array {
if e.hashValue == member.hashValue {
return
}
}
_array.append(WeakReference(member))
}
public func filter(@noescape includeElement: (T) -> Bool) -> WeakSet<T> {
return WeakSet(self.array().filter(includeElement))
}
public func hasElementPassingTest(@noescape filterFunc: (T) -> Bool) -> Bool {
return self.array().hasElementPassingTest(filterFunc)
}
private func array() -> Array<T> {
var result = Array<T>()
for item in _array {
if let v = item.value {
result.append(v)
}
}
return result
}
}
| mit | 6954b87877d5f1d64d9d9d498892ad48 | 22.828571 | 87 | 0.550959 | 3.952607 | false | false | false | false |
LFL2018/swiftSmpleCode | RxSwiftDemo/RxSwiftDemo/ViewController.swift | 1 | 2091 | //
// ViewController.swift
// RxSwiftDemo
//
// Created by DragonLi on 2017/8/31.
// Copyright © 2017年 XiTu Inc. All rights reserved.
//
import UIKit
private let cellIDString = "cellIDString"
class ViewController: UIViewController {
lazy var sourceDatas : [String] = {
let sourceDatas = ["UIBaseUserPartOne"]
return sourceDatas
}()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "RxSwiftDemo"
view.backgroundColor = UIColor.gray
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellIDString)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
}
// MARK: - Delegate
extension ViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return sourceDatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: cellIDString, for: indexPath)
cell.textLabel?.text = "\(sourceDatas[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
pushToVC(stringVC: sourceDatas[indexPath.row])
}
}
// MARK: - handle push VC
extension ViewController {
fileprivate func pushToVC(stringVC:String){
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleName"] as? String else {
return
}
guard let VC_Class = NSClassFromString(nameSpace + "." + stringVC) else {
return
}
guard let VC_Type = VC_Class as? UIViewController.Type else {
return
}
let pushVC = VC_Type.init()
pushVC.view.backgroundColor = UIColor.white
self.navigationController!.pushViewController(pushVC, animated: true)
}
}
| mit | a4292fb8c572c9be0decc282e7f6f035 | 28.828571 | 99 | 0.665709 | 4.867133 | false | false | false | false |
bppr/Swiftest | src/Swiftest/Client/ExpectationDSL.swift | 1 | 1759 | private func __add<T:Expectable>(ex: T) -> T {
context.currentExample.addExpectation(ex.result)
return ex
}
public func expect<T:Equatable>(
subject: [T]?,
file: String = #file,
line: UInt = #line
) -> ArrayExpectation<T> {
return __add(
ArrayExpectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<K:Hashable,V:Equatable>(
subject: [K:V],
file: String = #file,
line: UInt = #line
) -> DictionaryExpectation<K, V> {
return __add(
DictionaryExpectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<T:Equatable>(
subject: T?,
file: String = #file,
line: UInt = #line
) -> Expectation<T, EquatableMatcher<T>> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect<T:Comparable>(
subject: T?,
file: String = #file,
line: UInt = #line
) -> Expectation<T, ComparableMatcher<T>> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
file: String = #file,
line: UInt = #line,
subject: Void throws -> Void
) -> Expectation<Void throws -> Void, ThrowableVoidMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
file: String = #file,
line: UInt = #line,
subject: VoidBlk?
) -> Expectation<VoidBlk, VoidMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
public func expect(
subject: String?,
file: String = #file,
line: UInt = #line
) -> Expectation<String, StringMatcher> {
return __add(
Expectation(subject: subject, cursor: Cursor(file: file, line: line))
)
}
| mit | f7aab51db6221730aecd668b30f38199 | 22.77027 | 83 | 0.65776 | 3.312618 | false | false | false | false |
hirohitokato/DetailScrubber | DetailScrubber/MovieSlider.swift | 1 | 12395 | //
// MovieSlider.swift
//
// Copyright (c) 2017 Hirohito Kato. MIT License.
//
import UIKit
import QuartzCore
public enum StackState {
case inactive
case active
var stackColor: UIColor {
switch self {
case .inactive: return .black
case .active: return .darkGray
}
}
}
private struct Stack {
let view: UIView
var state: StackState
}
@objc public protocol MovieSliderDelegate {
/**
Called whenever the slider's current stack changes.
This is called when a stack mode is on. It's optinal method.
- parameter slider: An object representing the movie slider notifying this information.
- parameter index: The stack index starts from 0(most left side)
*/
func movieSlider(_ slider: MovieSlider, didChangeStackIndex index:Int)
}
extension MovieSliderDelegate {
func movieSlider(_ slider: MovieSlider, didChangeStackIndex index:Int) {}
}
open class MovieSlider : DetailScrubber {
private let kThumbImageSize : CGFloat = 20.0
private let kThumbImageMargin : CGFloat = 10.0
private let kThumbSize : CGFloat = 15.0
private let kTrackHeight : CGFloat = 3.0
private let kFrameGap: CGFloat = 2
private var kFrameHeight: CGFloat {
return minimumTrackImage(for: UIControl.State())!.size.height
}
public var stackMode: Bool = false {
didSet {
if stackMode != oldValue {
showStacks(stackMode)
_index = currentIndex
if stackMode {
_value = value
setValue(0.5, animated: true)
} else {
setValue(_value, animated: true)
}
}
}
}
private var _stacks = [Stack]()
private var _index: Int = 0
private var _value: Float = 0.0
public var numberOfStacks = 30 {
didSet {
guard stackMode == false else {
print("Cannot change number of stacks during stack mode.")
numberOfStacks = oldValue
return
}
}
}
public weak var movieSliderDelegate: MovieSliderDelegate? = nil
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_setupStacking()
_setupAppearance()
_value = value
}
override public init(frame: CGRect) {
super.init(frame: frame)
_setupStacking()
_setupAppearance()
_value = value
}
}
private typealias MovieSlider_Appearance = MovieSlider
private extension MovieSlider_Appearance {
func _setupAppearance() {
tintColor = UIColor.white
// thumb image
setThumbImage(_imageForThumb(), for: UIControl.State())
// track image
let tracks = _imagesForTrack()
setMinimumTrackImage(tracks.minImage, for: UIControl.State())
setMaximumTrackImage(tracks.maxImage, for: UIControl.State())
}
func _imageForThumb() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kThumbImageSize,
height: kThumbImageSize+kThumbImageMargin*3.0), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.white.cgColor)
ctx!.setLineWidth(0.25)
ctx!.addEllipse(in: CGRect(x: (kThumbImageSize-kThumbSize)/2.0,
y: (kThumbImageSize+kThumbSize)/2.0,
width: kThumbSize, height: kThumbSize))
let shadowColor = UIColor.darkGray.cgColor
let shadowOffset = CGSize(width: 0, height: 0.5)
let shadowBlur : CGFloat = 1.0
ctx!.setShadow(offset: shadowOffset, blur: shadowBlur, color: shadowColor);
ctx!.drawPath(using: .fill)
return UIGraphicsGetImageFromCurrentImageContext()
}
func _imagesForTrack() -> (minImage: UIImage, maxImage: UIImage) {
let minTrack: UIImage
let maxTrack: UIImage
// minimum track image
do {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kTrackHeight, height: kTrackHeight), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.white.cgColor)
ctx!.setLineWidth(0.25)
ctx!.addArc(center: CGPoint(x:kTrackHeight/2, y:kTrackHeight/2), radius: kTrackHeight/2,
startAngle: _DEG2RAD(90), endAngle: _DEG2RAD(270), clockwise: false)
ctx!.addLine(to: CGPoint(x: kTrackHeight, y: 0))
ctx!.addLine(to: CGPoint(x: kTrackHeight, y: kTrackHeight))
ctx!.addLine(to: CGPoint(x: kTrackHeight/2, y: kTrackHeight))
ctx!.closePath()
ctx!.drawPath(using: .fillStroke)
let tmpImage = UIGraphicsGetImageFromCurrentImageContext()
minTrack = tmpImage!.resizableImage(
withCapInsets: UIEdgeInsets(top: 1, left: kTrackHeight/2, bottom: 1, right: 1),
resizingMode: .tile)
}
// maximum track image
do {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: kTrackHeight, height: kTrackHeight), false, 2.0)
defer { UIGraphicsEndImageContext() }
let ctx = UIGraphicsGetCurrentContext()
ctx!.setFillColor(UIColor.black.cgColor)
ctx!.addArc(center: CGPoint(x:kTrackHeight/2, y:kTrackHeight/2), radius: kTrackHeight/2,
startAngle: _DEG2RAD(90), endAngle: _DEG2RAD(270), clockwise: true)
ctx!.addLine(to: CGPoint(x: 0, y: 0))
ctx!.addLine(to: CGPoint(x: 0, y: kTrackHeight))
ctx!.addLine(to: CGPoint(x: kTrackHeight/2, y: kTrackHeight))
ctx!.closePath()
ctx!.drawPath(using: .fill)
let tmpImage = UIGraphicsGetImageFromCurrentImageContext()
maxTrack = tmpImage!.resizableImage(
withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: kTrackHeight/2),
resizingMode: .tile)
}
return (minTrack, maxTrack)
}
}
private typealias MovieSlider_UISliderMethods = MovieSlider
extension MovieSlider_UISliderMethods {
open override func trackRect(forBounds bounds: CGRect) -> CGRect {
var rect = CGRect.zero
let dx : CGFloat = 2.0
rect.origin.x = bounds.origin.x + dx
rect.origin.y = bounds.origin.y + (bounds.size.height - kTrackHeight) / 2.0
rect.size.width = bounds.size.width - (dx * 2.0)
rect.size.height = kTrackHeight
return rect
}
open override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
var thumbRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let thumbCenter = CGPoint(x: thumbRect.midX, y: thumbRect.midY)
thumbRect.origin.x = thumbCenter.x - thumbRect.size.width/2;
thumbRect.origin.y = thumbCenter.y - thumbRect.size.height/2;
return thumbRect
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if view == self {
// Only handle the point is on the thumb rect
let trackRect = self.trackRect(forBounds: bounds)
var thumbRect = self.thumbRect(forBounds: bounds, trackRect:trackRect, value:value)
// The area of handle point is greater than the size of thumb
thumbRect.origin.x -= thumbRect.size.width
thumbRect.size.width += 2 * thumbRect.size.width
if !thumbRect.contains(point) {
return nil
}
}
return view
}
}
// MARK: - Long Press Event
private typealias MovieSlider_StackingMode = MovieSlider
extension MovieSlider_StackingMode {
fileprivate func _setupStacking() {
}
fileprivate func showStacks(_ isOn: Bool) {
if !isOn {
_stacks.forEach{ $0.view.removeFromSuperview() }
_stacks.removeAll()
UIView.animate(withDuration: 0.15, animations: {
self.subviews[0].alpha = 1.0
self.subviews[1].alpha = 1.0
})
return
}
(0..<numberOfStacks).forEach { _ in
let state = StackState.inactive
let v = UIView(frame: CGRect.zero)
v.backgroundColor = state.stackColor
v.layer.borderWidth = 0.5
v.layer.borderColor = UIColor.lightGray.cgColor
let stack = Stack(view: v, state: state)
_stacks.append(stack)
}
let thumbImage = self.thumbImage(for: UIControl.State())
let minTrackIndex = subviews.firstIndex { v -> Bool in
if let imageView = v as? UIImageView {
return imageView.image == thumbImage
} else {
return false
}
}
let trackRect = self.trackRect(forBounds: bounds)
let thumbRect = self.thumbRect(forBounds: bounds, trackRect:trackRect, value:value)
var x: CGFloat = thumbRect.midX
let y: CGFloat = (frame.height-kFrameHeight)/2
let width: CGFloat = (frame.width - kFrameGap*(CGFloat(numberOfStacks-1))) / CGFloat(numberOfStacks)
let height: CGFloat = kFrameHeight
_stacks.forEach{
insertSubview($0.view, at: minTrackIndex!)
$0.view.frame = CGRect(x: x, y: y, width: width, height: height)
}
x = 0.0
UIView.animate(withDuration: 0.2, animations: {
self.subviews[0].alpha = 0.0
self.subviews[1].alpha = 0.0
self._stacks.forEach {
$0.view.frame = CGRect(x: x, y: y, width: width, height: height)
x += width + self.kFrameGap
}
})
updateStack()
}
open var currentIndex: Int {
get {
guard stackMode == true else { return -1 }
let valueRange = maximumValue - minimumValue
let range = Int(((value - minimumValue)/valueRange) * Float(numberOfStacks))
let currentIndex = min(range, numberOfStacks-1)
return currentIndex
}
set {
guard stackMode == true else { return }
let valueRange = maximumValue - minimumValue
value = (valueRange / Float(numberOfStacks * 2)) * (Float(newValue) * 2 + 1) + minimumValue
}
}
open func setStackState(_ state: StackState, at index: Int) {
guard index >= 0 && index < numberOfStacks else {
print("invalid index\(index) is set")
return
}
_stacks[index].state = state
updateStack()
}
fileprivate func updateStack() {
if stackMode {
for (i, stack) in _stacks.enumerated() {
stack.view.backgroundColor =
(i == currentIndex) ? .white : stack.state.stackColor
}
}
}
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let beginTracking = super.beginTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
return beginTracking
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let continueTracking = super.continueTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
return continueTracking
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
notifyIndexIfNeeded()
updateStack()
}
open override func sendActions(for controlEvents: UIControl.Event) {
if !stackMode {
super.sendActions(for: controlEvents)
}
}
fileprivate func notifyIndexIfNeeded() {
if stackMode && _index != currentIndex {
_index = currentIndex
movieSliderDelegate?.movieSlider(self, didChangeStackIndex: currentIndex)
}
}
}
private func _DEG2RAD(_ deg: CGFloat) -> CGFloat {
return deg * CGFloat.pi / 180.0
}
| mit | 6ea35c9cab20ce1e5c5dfc634d4a7a35 | 32.958904 | 108 | 0.59282 | 4.570428 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Common/TableViewController.swift | 1 | 3461 | //
// TableViewController.swift
// SwiftHub
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import KafkaRefresh
class TableViewController: ViewController, UIScrollViewDelegate {
let headerRefreshTrigger = PublishSubject<Void>()
let footerRefreshTrigger = PublishSubject<Void>()
let isHeaderLoading = BehaviorRelay(value: false)
let isFooterLoading = BehaviorRelay(value: false)
lazy var tableView: TableView = {
let view = TableView(frame: CGRect(), style: .plain)
view.emptyDataSetSource = self
view.emptyDataSetDelegate = self
view.rx.setDelegate(self).disposed(by: rx.disposeBag)
return view
}()
var clearsSelectionOnViewWillAppear = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if clearsSelectionOnViewWillAppear == true {
deselectSelectedRow()
}
}
override func makeUI() {
super.makeUI()
stackView.spacing = 0
stackView.insertArrangedSubview(tableView, at: 0)
tableView.bindGlobalStyle(forHeadRefreshHandler: { [weak self] in
self?.headerRefreshTrigger.onNext(())
})
tableView.bindGlobalStyle(forFootRefreshHandler: { [weak self] in
self?.footerRefreshTrigger.onNext(())
})
isHeaderLoading.bind(to: tableView.headRefreshControl.rx.isAnimating).disposed(by: rx.disposeBag)
isFooterLoading.bind(to: tableView.footRefreshControl.rx.isAnimating).disposed(by: rx.disposeBag)
tableView.footRefreshControl.autoRefreshOnFoot = true
error.subscribe(onNext: { [weak self] (error) in
self?.tableView.makeToast(error.description, title: error.title, image: R.image.icon_toast_warning())
}).disposed(by: rx.disposeBag)
}
override func updateUI() {
super.updateUI()
}
override func bindViewModel() {
super.bindViewModel()
viewModel?.headerLoading.asObservable().bind(to: isHeaderLoading).disposed(by: rx.disposeBag)
viewModel?.footerLoading.asObservable().bind(to: isFooterLoading).disposed(by: rx.disposeBag)
let updateEmptyDataSet = Observable.of(isLoading.mapToVoid().asObservable(), emptyDataSetImageTintColor.mapToVoid(), languageChanged.asObservable()).merge()
updateEmptyDataSet.subscribe(onNext: { [weak self] () in
self?.tableView.reloadEmptyDataSet()
}).disposed(by: rx.disposeBag)
}
}
extension TableViewController {
func deselectSelectedRow() {
if let selectedIndexPaths = tableView.indexPathsForSelectedRows {
selectedIndexPaths.forEach({ (indexPath) in
tableView.deselectRow(at: indexPath, animated: false)
})
}
}
}
extension TableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView, let textLabel = view.textLabel {
textLabel.font = UIFont.systemFont(ofSize: 15)
textLabel.theme.textColor = themeService.attribute { $0.text }
view.contentView.theme.backgroundColor = themeService.attribute { $0.primaryDark }
}
}
}
| mit | 20f4422269f2bcb72e2cae1a79b747e7 | 31.952381 | 164 | 0.680925 | 4.859551 | false | false | false | false |
Brightify/DataMapper | Source/Core/Transformation/Transformations/Date/CustomDateFormatTransformation.swift | 1 | 662 | //
// CustomDateFormatTransformation.swift
// DataMapper
//
// Created by Tadeas Kriz on 16/07/15.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
public struct CustomDateFormatTransformation: DelegatedTransformation {
public typealias Object = Date
public let transformationDelegate: AnyTransformation<Date>
public init(formatString: String) {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = formatString
transformationDelegate = DateFormatterTransformation(dateFormatter: formatter).typeErased()
}
}
| mit | 62042defcfa086d852f660af45bf8ddf | 26.541667 | 99 | 0.717095 | 5.045802 | false | false | false | false |
kaltura/developer-platform | test/golden/implicit_object_type/swift.swift | 1 | 612 | var searchParams = ESearchEntryParams()
searchParams.searchOperator = ESearchEntryOperator()
searchParams.searchOperator.operator = ESearchOperatorType.AND_OP
searchParams.searchOperator.searchItems = []
searchParams.searchOperator.searchItems[0] = ESearchCaptionItem()
searchParams.searchOperator.searchItems[0].searchTerm = "asdf"
var pager = Pager()
let requestBuilder = ESearchService.searchEntry(searchParams: searchParams, pager: pager)
requestBuilder.set(completion: {(result: ESearchEntryResponse?, error: ApiException?) in
print(result!)
done()
})
executor.send(request: requestBuilder.build(client)) | agpl-3.0 | 064a74126b25e868a5e72a49ce124532 | 42.785714 | 89 | 0.820261 | 4.05298 | false | false | false | false |
ckhsponge/iairportsdb | iAirportsDB/Classes/IADBNavigationAid.swift | 1 | 2967 | //
// IADBNavigationAid.swift
// iAirportsDB
//
// Created by Christopher Hobbs on 8/21/16.
// Copyright © 2016 Toonsy Net. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
@objc(IADBNavigationAid)
open class IADBNavigationAid: IADBLocation {
@NSManaged open var dmeKhz: Int32
@NSManaged open var elevationFeet: NSNumber?
@NSManaged open var khz: Int32
@NSManaged open var name: String
@NSManaged open var type: String
open lazy var mhz:Double = {
return Double(self.khz) / 1000.0
}()
override open func setCsvValues( _ values: [String: String] ) {
//"id","filename","ident","name","type","frequency_khz","latitude_deg","longitude_deg","elevation_ft","iso_country","dme_frequency_khz","dme_channel","dme_latitude_deg","dme_longitude_deg","dme_elevation_ft","slaved_variation_deg","magnetic_variation_deg","usageType","power","associated_airport",
//print(values)
self.dmeKhz = Int32(values["dme_frequency_khz"]!) ?? -1
self.elevationFeet = IADBModel.parseIntNumber(text:values["elevation_ft"])
self.identifier = values["ident"] ?? ""
self.khz = Int32(values["frequency_khz"]!) ?? -1
self.latitude = Double(values["latitude_deg"]!)!
self.longitude = Double(values["longitude_deg"]!)!
self.name = values["name"] ?? ""
self.type = values["type"] ?? ""
}
//begin convenience functions for type casting
open override class func findNear(_ location: CLLocation, withinNM distance: CLLocationDistance) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findNear(location, withinNM: distance))
}
open override class func find(identifier: String) -> IADBNavigationAid? {
let model = super.find(identifier:identifier)
guard let typed = model as? IADBNavigationAid else {
print("Invalid type found \(String(describing: model))")
return nil
}
return typed
}
open override class func findAll(identifier: String) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifier:identifier))
}
open override class func findAll(identifier: String, types: [String]?) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifier:identifier, types: types))
}
open override class func findAll(identifiers: [String], types: [String]?) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(identifiers:identifiers, types: types))
}
open override class func findAll(predicate: NSPredicate) -> IADBCenteredArrayNavigationAids {
return IADBCenteredArrayNavigationAids(centeredArray: super.findAll(predicate:predicate))
}
//end convenience functions
}
| mit | 07bf50fb1183d587aa8fd5d8ec3fb566 | 43.939394 | 305 | 0.695887 | 3.997305 | false | false | false | false |
tzef/BmoImageLoader | BmoImageLoader/Classes/BmoPathExtension.swift | 1 | 767 | //
// BmoPathExtention.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/6.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
extension CGPath {
func insetPath(_ percent: CGFloat) -> CGPath {
let path = UIBezierPath(cgPath: self)
let translatePoint = CGPoint(x: path.bounds.width * percent / 2 + path.bounds.origin.x * percent,
y: path.bounds.height * percent / 2 + path.bounds.origin.y * percent)
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translatePoint.x, y: translatePoint.y)
transform = transform.scaledBy(x: 1 - percent, y: 1 - percent)
path.apply(transform)
return path.cgPath
}
}
| mit | c1dd2607c08aef7053df027760ff9dcb | 32.217391 | 106 | 0.633508 | 3.878173 | false | false | false | false |
Archerlly/ACRouter | ACRouter/Classes/ACRouter.swift | 1 | 5356 | //
// ACRouter.swift
// ACRouter
//
// Created by SnowCheng on 11/03/2017.
// Copyright © 2017 Archerlly. All rights reserved.
//
import Foundation
public class ACRouter: ACRouterParser {
// MARK: - Constants
public typealias FailedHandleBlock = ([String: AnyObject]) -> Void
public typealias RelocationHandleBlock = (String) -> String?
public typealias RouteResponse = (pattern: ACRouterPattern?, queries: [String: AnyObject])
public typealias MatchResult = (matched: Bool, queries: [String: AnyObject])
// MARK: - Private property
private var patterns = [ACRouterPattern]()
private var interceptors = [ACRouterInterceptor]()
private var relocationHandle: RelocationHandleBlock?
private var matchFailedHandle: FailedHandleBlock?
// MARK: - Public property
static let shareInstance = ACRouter()
// MARK: - Public method
func addRouter(_ patternString: String,
priority: uint = 0,
handle: @escaping ACRouterPattern.HandleBlock) {
let pattern = ACRouterPattern.init(patternString, priority: priority, handle: handle)
patterns.append(pattern)
patterns.sort { $0.priority > $1.priority }
}
func addInterceptor(_ whiteList: [String] = [String](),
priority: uint = 0,
handle: @escaping ACRouterInterceptor.InterceptorHandleBlock) {
let interceptor = ACRouterInterceptor.init(whiteList, priority: priority, handle: handle)
interceptors.append(interceptor)
interceptors.sort { $0.priority > $1.priority }
}
func addGlobalMatchFailedHandel(_ handel: @escaping FailedHandleBlock) {
matchFailedHandle = handel
}
func addRelocationHandle(_ handel: @escaping RelocationHandleBlock) {
relocationHandle = handel
}
func removeRouter(_ patternString: String) {
patterns = patterns.filter{ $0.patternString != patternString }
}
func canOpenURL(_ urlString: String) -> Bool {
return ac_matchURL(urlString).pattern != nil
}
func requestURL(_ urlString: String, userInfo: [String: AnyObject] = [String: AnyObject]()) -> RouteResponse {
return ac_matchURL(urlString, userInfo: userInfo)
}
// MARK: - Private method
private func ac_matchURL(_ urlString: String, userInfo: [String: AnyObject] = [String: AnyObject]()) -> RouteResponse {
let request = ACRouterRequest.init(urlString)
var queries = request.queries
var matched: ACRouterPattern?
if let patternString = relocationHandle?(urlString),
let firstMatched = patterns.filter({ $0.patternString == patternString }).first {
//relocation
matched = firstMatched
} else {
//filter the scheme and the count of paths not matched
let matchedPatterns = patterns.filter{ $0.sheme == request.sheme && $0.patternPaths.count == request.paths.count }
for pattern in matchedPatterns {
let result = ac_matchPattern(request, pattern: pattern)
if result.matched {
matched = pattern
queries.ac_combine(result.queries)
break
}
}
}
guard let currentPattern = matched else {
//not matched
var info = [ACRouter.matchFailedKey : urlString as AnyObject]
info.ac_combine(userInfo)
matchFailedHandle?(info)
print("not matched: \(urlString)")
return (nil, [String: AnyObject]())
}
guard ac_intercept(currentPattern.patternString, queries: queries) else {
print("interceped: \(urlString)")
return (nil, [String: AnyObject]())
}
queries.ac_combine([ACRouter.requestURLKey : urlString as AnyObject])
queries.ac_combine(userInfo)
return (currentPattern, queries)
}
private func ac_matchPattern(_ request: ACRouterRequest, pattern: ACRouterPattern) -> MatchResult {
var requestPaths = request.paths
var pathQuery = [String: AnyObject]()
//replace params
pattern.paramsMatchDict.forEach({ (name, index) in
let requestPathQueryValue = requestPaths[index] as AnyObject
pathQuery[name] = requestPathQueryValue
requestPaths[index] = ACRouterPattern.PatternPlaceHolder
})
let matchString = requestPaths.joined(separator: "/")
if matchString == pattern.matchString {
return (true, pathQuery)
} else {
return (false, [String: AnyObject]())
}
}
//Intercep the request and return whether should continue
private func ac_intercept(_ matchedPatternString: String, queries: [String: AnyObject]) -> Bool {
for interceptor in self.interceptors where !interceptor.whiteList.contains(matchedPatternString) {
if !interceptor.handle(queries) {
//interceptor handle return true will continue interceptor
return false
}
}
return true
}
}
| mit | 7715aa823532ed2d7ff3ef1422ce054b | 35.182432 | 126 | 0.607283 | 4.89936 | false | false | false | false |
karstengresch/layout_studies | countidon/countidon/ShapeButton.swift | 1 | 2405 | //
// ShapeButton.swift
// countidon
//
// Created by Karsten Gresch on 15.10.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
@IBDesignable
class ShapeButton: UIControl {
// source: http://stackoverflow.com/questions/27432736/how-to-create-an-ibinspectable-of-type-enum?rq=1
enum CornerType: String {
case Rounded = "rounded"
case Circle = "circle"
}
var cornerType = CornerType.Rounded
var labelText = "ShapeButton"
var segueIdentifier = ""
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'cornerType' instead.")
@IBInspectable var cornerTypeName: String? {
willSet {
if let newCornerType = CornerType(rawValue: newValue?.lowercased() ?? "") {
cornerType = newCornerType
}
}
}
@IBInspectable var radiusWidth: CGFloat = 30
@IBInspectable var radiusHeight: CGFloat = 30
@IBInspectable let shapeButtonLabel: UILabel = UILabel(frame: CGRect(x: 20.0, y: 30.0, width: 300.0, height: 30.0))
override func layoutSubviews() {
let shapeLayer = CAShapeLayer()
switch cornerType {
case .Rounded:
shapeLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.topRight, UIRectCorner.bottomLeft, UIRectCorner.bottomRight], cornerRadii: CGSize(width: 30, height: 30)).cgPath
case .Circle:
shapeLayer.path = UIBezierPath(ovalIn: self.bounds).cgPath
}
layer.mask = shapeLayer
setupLabels()
}
func setupLabels() {
shapeButtonLabel.numberOfLines = 1;
shapeButtonLabel.baselineAdjustment = UIBaselineAdjustment.alignBaselines
shapeButtonLabel.adjustsFontSizeToFitWidth = true
shapeButtonLabel.frame = self.bounds
shapeButtonLabel.backgroundColor = UIColor.clear
shapeButtonLabel.text = self.labelText
shapeButtonLabel.textColor = UIColor.white
shapeButtonLabel.font = UIFont.systemFont(ofSize: 28.0)
shapeButtonLabel.textAlignment = .center
shapeButtonLabel.drawText(in: self.bounds)
self.addSubview(shapeButtonLabel)
self.setNeedsDisplay()
}
}
import UIKit.UIGestureRecognizerSubclass
private class TapRecognizer: UITapGestureRecognizer {
func handleTap(sender: UITapGestureRecognizer) {
print("Tapped!")
if sender.state == .ended {
// handling code
print("Tap ended!")
}
}
}
| unlicense | a07bbac01161c8ffe482a2985a55e1d8 | 27.282353 | 226 | 0.710899 | 4.394881 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Common/Spinnerable/SpinnerNib.swift | 1 | 1831 | //
// SpinnerNib.swift
// MEGameTracker
//
// Created by Emily Ivie on 5/14/2016.
// Copyright © 2016 urdnot. All rights reserved.
//
import UIKit
final public class SpinnerNib: UIView {
@IBOutlet weak var spinner: UIActivityIndicatorView?
@IBOutlet weak var spinnerLabel: MarkupLabel?
@IBOutlet weak var spacerView: UIView?
@IBOutlet public weak var progressView: UIProgressView?
var title: String? {
didSet {
if oldValue != title {
setupTitle()
}
}
}
var isShowProgress: Bool = false {
didSet {
if oldValue != isShowProgress {
setupProgress()
}
}
}
public func setup() {
setupTitle()
setupProgress()
}
public func setupTitle() {
spinnerLabel?.text = title
spinnerLabel?.isHidden = !(title?.isEmpty == false)
layoutIfNeeded()
}
public func setupProgress() {
spacerView?.isHidden = !isShowProgress
progressView?.isHidden = !isShowProgress
layoutIfNeeded()
}
public func start() {
setupProgress()
progressView?.progress = 0.0
spinner?.startAnimating()
isHidden = false
}
public func startSpinning() {
spinner?.startAnimating()
progressView?.progress = 0.0
}
public func stop() {
spinner?.stopAnimating()
isHidden = true
}
public func updateProgress(percentCompleted: Int) {
let decimalCompleted = Float(percentCompleted) / 100.0
progressView?.setProgress(decimalCompleted, animated: true)
}
public func changeMessage(_ title: String) {
spinnerLabel?.text = title
}
public class func loadNib(title: String? = nil) -> SpinnerNib? {
let bundle = Bundle(for: SpinnerNib.self)
if let view = bundle.loadNibNamed("SpinnerNib", owner: self, options: nil)?.first as? SpinnerNib {
// view.spinner?.color = Styles.colors.tint // Styles.colors.tint
view.title = title
return view
}
return nil
}
}
| mit | e283baefbfc21b45468bf89668611a0b | 20.529412 | 100 | 0.690164 | 3.581213 | false | false | false | false |
DungntVccorp/Game | P/Sources/P/ConcurrentOperation.swift | 1 | 2623 | //
// BaseOperation.swift
// P
//
// Created by Nguyen Dung on 4/27/17.
//
//
import Foundation
protocol ConcurrentOperationDelegate {
func finishOperation(_ type : Int,_ replyMsg : GSProtocolMessage?,_ client : TcpClient)
}
open class ConcurrentOperation : Operation{
enum State {
case ready
case executing
case finished
func asKeyPath() -> String {
switch self {
case .ready:
return "isReady"
case .executing:
return "isExecuting"
case .finished:
return "isFinished"
}
}
}
var state: State {
willSet {
willChangeValue(forKey: newValue.asKeyPath())
willChangeValue(forKey: state.asKeyPath())
}
didSet {
didChangeValue(forKey: oldValue.asKeyPath())
didChangeValue(forKey: state.asKeyPath())
}
}
private var delegate : ConcurrentOperationDelegate!
var clientExcute : TcpClient!
var excuteMessage : GSProtocolMessage!
override init() {
state = .ready
super.init()
}
convenience init(_ delegate : ConcurrentOperationDelegate?,_ client : TcpClient,_ msg : GSProtocolMessage) {
self.init()
if(delegate != nil){
self.delegate = delegate!
}
self.clientExcute = client
self.excuteMessage = msg
}
// MARK: - NSOperation
override open var isReady: Bool {
return state == .ready
}
override open var isExecuting: Bool {
return state == .executing
}
override open var isFinished: Bool {
return state == .finished
}
override open var isAsynchronous: Bool {
return true
}
override open func start() {
if self.isCancelled {
state = .finished
}else{
state = .ready
main()
}
}
open func TcpExcute() -> (Int,replyMsg : GSProtocolMessage?){
return (0,nil)
}
override open func main() {
if self.isCancelled {
state = .finished
}else{
state = .executing
debugPrint("Run OP \(excuteMessage.headCodeId) : \(excuteMessage.subCodeId)")
let ex = self.TcpExcute()
if(self.delegate != nil){
self.delegate.finishOperation(ex.0,ex.1,self.clientExcute)
}
state = .finished
}
}
deinit {
debugPrint("Finish Operation")
}
}
| mit | f7ad27cfffedeaec27fb2a3485d21471 | 22.630631 | 112 | 0.53374 | 4.848429 | false | false | false | false |
nuclearace/SwiftDiscord | Sources/SwiftDiscord/DiscordLogger.swift | 1 | 3197 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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
/// Represents the level of verbosity for the logger.
public enum DiscordLogLevel {
/// Log nothing.
case none
/// Log connecting, disconnecting, events (but not content), etc.
case info
/// Log content of events.
case verbose
/// Log everything.
case debug
}
/// Declares that a type will act as a logger.
public protocol DiscordLogger {
// MARK: Properties
/// Whether to log or not.
var level: DiscordLogLevel { get set }
// MARK: Methods
/// Normal log messages.
func log( _ message: @autoclosure () -> String, type: String)
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String)
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String)
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String)
}
public extension DiscordLogger {
/// Normal log messages.
func log(_ message: @autoclosure () -> String, type: String) {
guard level == .info || level == .verbose || level == .debug else { return }
abstractLog("LOG", message: message(), type: type)
}
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String) {
guard level == .verbose || level == .debug else { return }
abstractLog("VERBOSE", message: message(), type: type)
}
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String) {
guard level == .debug else { return }
abstractLog("DEBUG", message: message(), type: type)
}
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String) {
abstractLog("ERROR", message: message(), type: type)
}
private func abstractLog(_ logType: String, message: String, type: String) {
NSLog("\(logType): \(type): \(message)")
}
}
class DefaultDiscordLogger : DiscordLogger {
static var Logger: DiscordLogger = DefaultDiscordLogger()
var level = DiscordLogLevel.none
}
| mit | 50ef1be764b2190ace70a1f7e1ad4981 | 34.522222 | 119 | 0.675008 | 4.496484 | false | false | false | false |
kkireto/SwiftUtils | LabelUtils.swift | 1 | 3220 | //The MIT License (MIT)
//
//Copyright (c) 2014 Kireto
//
//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 LabelUtils: NSObject {
class func label(frame: CGRect, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString) -> UILabel {
var retValue = UILabel (frame: frame)
retValue.backgroundColor = UIColor.clearColor()
retValue.font = font
retValue.textColor = color
retValue.textAlignment = alignment
retValue.text = text
return retValue
}
class func label(frame: CGRect, numberOfLines: Int, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString) -> UILabel {
var retValue = UILabel (frame: frame)
retValue.backgroundColor = UIColor.clearColor()
retValue.numberOfLines = numberOfLines
retValue.font = font
retValue.textColor = color
retValue.textAlignment = alignment
retValue.text = text
return retValue
}
class func label(frame: CGRect, font: UIFont, color: UIColor, alignment: NSTextAlignment, text: NSString, shadowColor: UIColor, shadowOffset: CGSize) -> UILabel {
var retValue = LabelUtils.label(frame, font: font, color: color, alignment: alignment, text: text)
retValue.shadowColor = shadowColor
retValue.shadowOffset = shadowOffset
return retValue
}
class func textSize (text: NSString, font: UIFont) -> CGSize {
var attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
return text.sizeWithAttributes(attributes)
}
class func textSize (text: NSString, font: UIFont, lineBreakMode: NSLineBreakMode, initialSize: CGSize) -> CGSize {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
var attributes = NSDictionary(objectsAndKeys:
font, NSFontAttributeName,
paragraphStyle.copy(), NSParagraphStyleAttributeName)
var textRect = text.boundingRectWithSize(initialSize,
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: attributes,
context: nil)
return textRect.size
}
}
| mit | f386bc9791f69d3ccac9d92ed513def4 | 47.059701 | 166 | 0.714907 | 5.078864 | false | false | false | false |
DigitalShooting/DSM-iOS | DSM-iOS/SingleLineViewController.swift | 1 | 9596 | //
// FirstViewController.swift
// DSM-iOS
//
// Created by Jannik Lorenz on 31.10.15.
// Copyright © 2015 Jannik Lorenz. All rights reserved.
//
import Foundation
import XLForm
import SwiftyJSON
class SingleLineViewController: XLFormViewController {
var line: Line?
var updateing = false
// MARK: Init
convenience init(line: Line){
self.init(nibName: nil, bundle: nil)
self.line = line
line.events.listenTo("setSession") { () -> () in
self.updateForm()
}
line.events.listenTo("setConfig") { () -> () in
self.updateForm()
}
line.events.listenTo("disconnect", action: { () -> () in
self.navigationController?.popViewControllerAnimated(true)
})
line.events.listenTo("error", action: { () -> () in
self.navigationController?.popViewControllerAnimated(true)
})
self.initializeForm()
}
// MARK: View Livestyle
override func viewDidLoad() {
super.viewDidLoad()
// if let session = line?.session {
// let f = Test_View(frame: CGRectMake(0, 0, view.frame.width, 500), session: session)
// view.addSubview(f)
// }
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = line?.title
self.updateForm()
}
// MARK: Form Creation
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor()
section = XLFormSectionDescriptor() as XLFormSectionDescriptor
form.addFormSection(section)
section.title = "Modus"
// Disziplin
row = XLFormRowDescriptor(tag: "disziplin", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Disziplin")
section.addFormRow(row)
// Parts
row = XLFormRowDescriptor(tag: "part", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Part")
section.addFormRow(row)
section = XLFormSectionDescriptor() as XLFormSectionDescriptor
form.addFormSection(section)
section.title = "Nachricht"
// Nachricht
row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeSelectorActionSheet, title: "Nachricht")
row.selectorOptions = [
XLFormOptionsObject(value: "sicherheit", displayText: "Sicherheit"),
XLFormOptionsObject(value: "pause", displayText: "Pause"),
]
section.addFormRow(row)
// Nachricht ausblenden
row = XLFormRowDescriptor(tag: "hideMessage", rowType: XLFormRowDescriptorTypeButton, title: "Nachricht ausblenden")
row.action.formBlock = { form in
self.tableView.selectRowAtIndexPath(nil, animated: true, scrollPosition: .None)
self.line?.hideMessage()
}
section.addFormRow(row)
self.form = form
self.tableView?.reloadData()
}
func updateForm(){
self.updateing = true
// Disziplin
var row = form.formRowWithTag("disziplin")
var disziplinenList: [XLFormOptionsObject] = []
if let groups = line?.config?["disziplinen"]["groups"].arrayValue {
for singleGroup in groups {
for disziplinID in singleGroup["disziplinen"].arrayValue {
let disziplin = line?.config?["disziplinen"]["all"][disziplinID.stringValue]
let option = XLFormOptionsObject(value: disziplinID.stringValue, displayText: disziplin?["title"].stringValue)
disziplinenList.append(option)
if (disziplinID.stringValue == line?.session?["disziplin"]["_id"].string) {
row?.value = option
}
}
}
}
row?.selectorOptions = disziplinenList
// Parts
row = form.formRowWithTag("part")
var partsList: [XLFormOptionsObject] = []
if let parts = line?.session?["disziplin"]["parts"].dictionaryValue {
for (key, part) in parts {
let option = XLFormOptionsObject(value: key, displayText: part["title"].stringValue)
partsList.append(option)
if (key == line?.session?["type"].string) {
row?.value = option
}
}
}
row?.selectorOptions = partsList
self.tableView?.reloadData()
self.updateing = false
}
override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) {
if updateing {
return
}
switch (formRow.tag){
case "part"?:
if let option = formRow.value as? XLFormOptionsObject {
line?.setPart(option.valueData() as! String)
}
case "disziplin"?:
if let option = formRow.value as? XLFormOptionsObject {
line?.setDisziplin(option.valueData() as! String)
}
case "message"?:
if let option = formRow.value?.valueData() as? String {
switch (option){
case "sicherheit":
line?.showMessage("Sicherheit", type: Line.DSCAPIMethodMessage.danger)
case "pause":
line?.showMessage("Pause", type: Line.DSCAPIMethodMessage.black)
default:
break
}
formRow.value = nil
}
default:
break
}
}
class Test_View: UIView {
var session: JSON?
// override init(frame: CGRect) {
// super.init(frame: frame)
// }
//
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
convenience init(frame: CGRect, session: JSON){
self.init(frame: frame)
self.session = session
}
override func drawRect(rect: CGRect) {
let scheibe = session?["disziplin"]["scheibe"]
/*
var lastRing = scheibe.ringe[scheibe.ringe.length-1]
for (var i = scheibe.ringe.length-1; i >= 0; i--){
var ring = scheibe.ringe[i]
context.globalAlpha = 1.0
context.fillStyle = ring.color;
context.beginPath();
context.arc(lastRing.width/2*zoom.scale+zoom.offset.x, lastRing.width/2*zoom.scale+zoom.offset.y, ring.width/2*zoom.scale, 0, 2*Math.PI);
context.closePath();
context.fill();
context.strokeStyle = ring.textColor
context.lineWidth = 4;
context.stroke();
context.fillStyle = "black";
if (ring.text == true){
context.font = "bold "+(scheibe.text.size*zoom.scale)+"px verdana, sans-serif";
context.fillStyle = ring.textColor
context.fillText(ring.value, (lastRing.width/2 - ring.width/2 + scheibe.text.left)*zoom.scale+zoom.offset.x, (lastRing.width/2+scheibe.text.width)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2 + ring.width/2 + scheibe.text.right)*zoom.scale+zoom.offset.x, (lastRing.width/2+scheibe.text.width)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2-scheibe.text.width)*zoom.scale+zoom.offset.x, (lastRing.width/2 + ring.width/2 + scheibe.text.down)*zoom.scale+zoom.offset.y);
context.fillText(ring.value, (lastRing.width/2-scheibe.text.width)*zoom.scale+zoom.offset.x, (lastRing.width/2 - ring.width/2 + scheibe.text.up)*zoom.scale+zoom.offset.y);
}
}
*/
if let ringe = scheibe?["ringe"].arrayValue {
let lastRing = ringe.last
for ring in ringe {
print(ring)
// let radius = ring["width"].intValue/ 2*
var path = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 300, height: 300))
UIColor.greenColor().setFill()
path.fill()
}
}
// let h = rect.height
// let w = rect.width
// var color:UIColor = UIColor.yellowColor()
//
// var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
// var bpath:UIBezierPath = UIBezierPath(rect: drect)
// color.set()
// bpath.stroke()
}
}
}
| gpl-3.0 | 3d705a70cf7371b108c61cb1bc58f910 | 28.432515 | 186 | 0.511412 | 4.757065 | false | false | false | false |
matsprea/omim | iphone/Maps/Core/Theme/BookmarksStyleSheet.swift | 1 | 864 | import Foundation
class BookmarksStyleSheet: IStyleSheet {
static func register(theme: Theme, colors: IColors, fonts: IFonts) {
theme.add(styleName: "BookmarksCategoryTextView") { (s) -> (Void) in
s.font = fonts.regular16
s.fontColor = colors.blackPrimaryText
s.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
theme.add(styleName: "BookmarksCategoryDeleteButton") { (s) -> (Void) in
s.font = fonts.regular17
s.fontColor = colors.red
s.fontColorDisabled = colors.blackHintText
}
theme.add(styleName: "BookmarksActionCreateIcon") { (s) -> (Void) in
s.tintColor = colors.linkBlue
}
theme.add(styleName: "BookmarkSharingLicense", from: "TermsOfUseLinkText") { (s) -> (Void) in
s.fontColor = colors.blackSecondaryText
s.font = fonts.regular14
}
}
}
| apache-2.0 | 57ff490747cd5f28cedf5b63edf05370 | 32.230769 | 97 | 0.668981 | 3.74026 | false | false | false | false |
P0ed/FireTek | Source/SpaceEngine/Systems/WeaponSystem.swift | 1 | 3203 | import SpriteKit
import PowerCore
import Fx
struct WeaponSystem {
private let world: World
private var primaryFiringEntities = [] as Set<Entity>
private var secondaryFiringEntities = [] as Set<Entity>
init(world: World) {
self.world = world
}
mutating func update() {
applyShipsInputs()
updateCooldowns()
primaryFiringEntities = updateFiring(firing: primaryFiringEntities, weapons: world.primaryWpn)
secondaryFiringEntities = updateFiring(firing: secondaryFiringEntities, weapons: world.secondaryWpn)
}
private mutating func applyShipsInputs() {
let ships = world.ships
let inputs = world.shipInput
let primaryWpn = world.primaryWpn
let secondaryWpn = world.secondaryWpn
ships.enumerated().forEach { index, ship in
let entity = ships.entityAt(index)
let input = inputs[ship.input]
if input.primaryFire && primaryWpn[ship.primaryWpn].remainingCooldown == 0 {
primaryFiringEntities.insert(entity)
}
if input.secondaryFire && secondaryWpn[ship.secondaryWpn].remainingCooldown == 0 {
secondaryFiringEntities.insert(entity)
}
}
}
private func updateCooldowns() {
for index in world.primaryWpn.indices {
updateWeaponCooldown(&world.primaryWpn[index])
}
for index in world.secondaryWpn.indices {
updateWeaponCooldown(&world.secondaryWpn[index])
}
}
private func updateWeaponCooldown(_ weapon: inout WeaponComponent) {
if weapon.remainingCooldown != 0 {
weapon.remainingCooldown = max(0, weapon.remainingCooldown - Float(SpaceEngine.timeStep))
if weapon.remainingCooldown == 0 && weapon.rounds == 0 {
weapon.rounds = min(weapon.roundsPerShot, weapon.ammo)
}
}
}
private func updateFiring(firing: Set<Entity>, weapons: Store<WeaponComponent>) -> Set<Entity> {
return firing.filterSet { entity in
if let index = weapons.indexOf(entity) {
let weapon = weapons[index]
if weapon.remainingCooldown == 0 && weapon.rounds != 0 {
let offset = CGVector(dx: 0, dy: 36)
if let spriteIndex = world.sprites.indexOf(entity) {
let transform = world.sprites[spriteIndex].sprite.transform.move(by: offset)
fire(&weapons[index], at: transform, source: entity)
}
else {
return false
}
}
return weapons[index].rounds > 0
}
else {
return false
}
}
}
private func fire(_ weapon: inout WeaponComponent, at transform: Transform, source: Entity) {
let roundsPerTick = weapon.perShotCooldown == 0 ? weapon.rounds : 1
weapon.rounds -= roundsPerTick
weapon.ammo -= roundsPerTick
weapon.remainingCooldown += weapon.rounds == 0 ? weapon.cooldown : weapon.perShotCooldown
for round in 0..<roundsPerTick {
ProjectileFactory.createProjectile(
world,
at: transform.move(by: offset(round: round, outOf: roundsPerTick)),
velocity: weapon.velocity,
projectile: ProjectileComponent(
source: source,
type: weapon.type,
damage: weapon.damage
)
)
}
}
private func offset(round: Int, outOf total: Int) -> CGVector {
if total == 1 { return .zero }
let spacing = 4 as CGFloat
let spread = spacing * CGFloat(total - 1)
return CGVector(
dx: (-spread / 2) + spacing * CGFloat(round),
dy: 0
)
}
}
| mit | cb752936cf3af3ff99dfd1e3de3c4f6b | 27.096491 | 102 | 0.705276 | 3.411076 | false | false | false | false |
miller-ms/ViewAnimator | ViewAnimator/SpringAnimatorConroller.swift | 1 | 6745 | //
// SpringAnimatorConroller.swift
// ViewAnimator
//
// Created by William Miller DBA Miller Mobilesoft on 5/13/17.
//
// This application is intended to be a developer tool for evaluating the
// options for creating an animation or transition using the UIView static
// methods UIView.animate and UIView.transition.
// Copyright © 2017 William Miller DBA Miller Mobilesoft
//
// 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/>.
//
// If you would like to reach the developer you may email me at
// [email protected] or visit my website at
// http://millermobilesoft.com
//
import UIKit
class SpringAnimatorConroller: AnimatorController {
enum ParamCellIdentifiers:Int {
case durationCell = 0
case delayCell
case springDampingCell
case velocityCell
case optionsCell
case propertiesCell
case count
}
enum SpringAnimateCellIdentifiers:Int {
case animateCell = 0
case count
}
enum SectionIdentifiers:Int {
case animateSection = 0
case parameterSection
case count
}
var duration = Double(1.0)
var delay = Double(0.25)
var springDamping = CGFloat(0.5)
var velocity = CGFloat(0.5)
var animationProperties = PropertiesModel()
var options = OptionsModel(options: [UIViewAnimationOptions.curveEaseInOut])
override func viewDidLoad() {
super.viewDidLoad()
cellIdentifiers = [ "SpringAnimationCellId", "DurationCellId", "DelayCellId", "SpringDampingCellId", "SpringVelocityCellId", "OptionsCellId", "PropertiesCellId"]
sectionHeaderTitles = ["Spring Animation", "Parameters"]
identifierBaseIdx = [0,
SpringAnimateCellIdentifiers.count.rawValue]
sectionCount = [SpringAnimateCellIdentifiers.count.rawValue, ParamCellIdentifiers.count.rawValue]
rowHeights = [CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func saveParameters () {
var parameterPath = IndexPath(row:ParamCellIdentifiers.durationCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
var cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
duration = Double(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.delayCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
delay = Double(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.springDampingCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
springDamping = CGFloat(cell!.value)
}
parameterPath = IndexPath(row:ParamCellIdentifiers.velocityCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
velocity = CGFloat(cell!.value)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let section = SectionIdentifiers(rawValue: indexPath.section) else {
return
}
let cell = tableView.cellForRow(at: indexPath)!
cell.isSelected = false
switch section {
case .animateSection:
let curveCell = cell as! SpringAnimationCell
curveCell.reset()
default:
break
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is PropertiesController {
let propertiesVC = segue.destination as! PropertiesController
propertiesVC.animationProperties = animationProperties
} else if segue.destination is SpringOptionsController {
let optionsVC = segue.destination as! SpringOptionsController
optionsVC.options = options
}
}
@IBAction func durationChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
duration = Double(cell.value)
}
@IBAction func delayChanged(_ sender: UISlider) {
let cell = sender.superview?.superview as! FloatValueCell
delay = Double(cell.value)
}
@IBAction func springDampingChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
springDamping = CGFloat(cell.value)
}
@IBAction func springVelocityChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
velocity = CGFloat(cell.value)
}
@IBAction func executeSpringAnimation(_ sender: UIButton) {
let cell = sender.superview?.superview as! SpringAnimationCell
let hex = String(format: "%x", options.animationOptions.rawValue) // SpringOptionsController.springOptions.rawValue)
print("Options for animate are \(hex)")
saveParameters()
cell.executeAnimation(withDuration: duration, andDelay: delay, usingSpringwithDamping: springDamping, withInitialSpringVelocity: velocity, animationOptions: options.animationOptions, animationProperties: animationProperties)
}
}
| gpl-3.0 | b443988fc727b7eb3c423e8f8cfd8f88 | 31.114286 | 232 | 0.638938 | 5.195686 | false | false | false | false |
EasySwift/EasySwift | Carthage/Checkouts/Bond/BondTests/ProtocolProxyTests.swift | 4 | 2253 | //
// ProtocolProxyTests.swift
// Bond
//
// Created by Srdan Rasic on 29/08/16.
// Copyright © 2016 Swift Bond. All rights reserved.
//
import XCTest
import ReactiveKit
@testable import Bond
@objc protocol TestDelegate {
func methodA()
func methodB(_ object: TestObject)
func methodC(_ object: TestObject, value: Int)
func methodD(_ object: TestObject, value: Int) -> NSString
}
class TestObject: NSObject {
weak var delegate: TestDelegate! = nil
override init() {
super.init()
}
func callMethodA() {
delegate.methodA()
}
func callMethodB() {
delegate.methodB(self)
}
func callMethodC(_ value: Int) {
delegate.methodC(self, value: value)
}
func callMethodD(_ value: Int) -> NSString {
return delegate.methodD(self, value: value)
}
}
class ProtocolProxyTests: XCTestCase {
var object: TestObject! = nil
var delegate: ProtocolProxy {
return object.protocolProxy(for: TestDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
override func setUp() {
object = TestObject()
}
func testCallbackA() {
let stream = delegate.signal(for: #selector(TestDelegate.methodA)) { (stream: PublishSubject1<Int>) in
stream.next(0)
}
stream.expectNext([0, 0])
object.callMethodA()
object.callMethodA()
}
func testCallbackB() {
let stream = delegate.signal(for: #selector(TestDelegate.methodB(_:))) { (stream: PublishSubject1<Int>, _: TestObject) in
stream.next(0)
}
stream.expectNext([0, 0])
object.callMethodB()
object.callMethodB()
}
func testCallbackC() {
let stream = delegate.signal(for: #selector(TestDelegate.methodC(_:value:))) { (stream: PublishSubject1<Int>, _: TestObject, value: Int) in
stream.next(value)
}
stream.expectNext([10, 20])
object.callMethodC(10)
object.callMethodC(20)
}
func testCallbackD() {
let stream = delegate.signal(for: #selector(TestDelegate.methodD(_:value:))) { (stream: PublishSubject1<Int>, _: TestObject, value: Int) -> NSString in
stream.next(value)
return "\(value)" as NSString
}
stream.expectNext([10, 20])
XCTAssertEqual(object.callMethodD(10), "10")
XCTAssertEqual(object.callMethodD(20), "20")
}
}
| apache-2.0 | 4e65cae2d497fa6001207e85f941614a | 22.458333 | 155 | 0.666963 | 3.759599 | false | true | false | false |
calebkleveter/BluetoothKit | Source/BKScanner.swift | 1 | 4397 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// 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 CoreBluetooth
internal class BKScanner: BKCBCentralManagerDiscoveryDelegate {
// MARK: Type Aliases
internal typealias ScanCompletionHandler = ((_ result: [BKDiscovery]?, _ error: BKError?) -> Void)
// MARK: Enums
internal enum BKError: Error {
case noCentralManagerSet
case busy
case interrupted
}
// MARK: Properties
internal var configuration: BKConfiguration!
internal var centralManager: CBCentralManager!
private var busy = false
private var scanHandlers: (progressHandler: BKCentral.ScanProgressHandler?, completionHandler: ScanCompletionHandler )?
private var discoveries = [BKDiscovery]()
private var durationTimer: Timer?
// MARK: Internal Functions
internal func scanWithDuration(_ duration: TimeInterval, progressHandler: BKCentral.ScanProgressHandler? = nil, completionHandler: @escaping ScanCompletionHandler) throws {
do {
try validateForActivity()
busy = true
scanHandlers = ( progressHandler: progressHandler, completionHandler: completionHandler)
centralManager.scanForPeripherals(withServices: configuration.serviceUUIDs, options: nil)
durationTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(BKScanner.durationTimerElapsed), userInfo: nil, repeats: false)
} catch let error {
throw error
}
}
internal func interruptScan() {
guard busy else {
return
}
endScan(.interrupted)
}
// MARK: Private Functions
private func validateForActivity() throws {
guard !busy else {
throw BKError.busy
}
guard centralManager != nil else {
throw BKError.noCentralManagerSet
}
}
@objc private func durationTimerElapsed() {
endScan(nil)
}
private func endScan(_ error: BKError?) {
invalidateTimer()
centralManager.stopScan()
let completionHandler = scanHandlers?.completionHandler
let discoveries = self.discoveries
scanHandlers = nil
self.discoveries.removeAll()
busy = false
completionHandler?(discoveries, error)
}
private func invalidateTimer() {
if let durationTimer = self.durationTimer {
durationTimer.invalidate()
self.durationTimer = nil
}
}
// MARK: BKCBCentralManagerDiscoveryDelegate
internal func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard busy else {
return
}
let RSSI = Int(RSSI)
let remotePeripheral = BKRemotePeripheral(identifier: peripheral.identifier, peripheral: peripheral)
remotePeripheral.configuration = configuration
let discovery = BKDiscovery(advertisementData: advertisementData, remotePeripheral: remotePeripheral, RSSI: RSSI)
if !discoveries.contains(discovery) {
discoveries.append(discovery)
scanHandlers?.progressHandler?([ discovery ])
}
}
}
| mit | 6e6339241055b727b84324180aae4f1a | 35.338843 | 176 | 0.689334 | 5.136682 | false | false | false | false |
justinlevi/asymptotik-rnd-scenekit-kaleidoscope | Atk_Rnd_VisualToys/ScreenTextureQuad.swift | 2 | 4211 | //
// quadVertexBuffer.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 9/30/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
import OpenGLES
class ScreenTextureQuad {
var vertexBufferObject:GLuint = 0
var normalBufferObject:GLuint = 0
var indexBufferObject:GLuint = 0
var positionIndex:GLuint = 0
var textureCoordinateIndex:GLuint = 0
var textureUniformIndex:GLuint = 0
var glProgram:GLProgram? = nil;
init() {
}
var min:GLfloat = -1.0
var max:GLfloat = 1.0
func initialize() {
let verts:[GLfloat] = [
min, max, 0, // vert
0, 0, 1, // norm
0, 1, // tex
min, min, 0,
0, 0, 1,
0, 0,
max, max, 0,
0, 0, 1,
1, 1,
max, min, 0,
0, 0, 1,
1, 0
]
let indices:[GLushort] = [
0, 1, 2, 2, 1, 3
]
let ptr = UnsafePointer<GLfloat>(bitPattern: 0)
self.glProgram = GLProgram(vertexShaderFilename: "PassthroughShader", fragmentShaderFilename: "PassthroughShader")
self.glProgram!.addAttribute("position")
self.positionIndex = self.glProgram!.attributeIndex("position")
self.glProgram!.addAttribute("textureCoordinate")
self.textureCoordinateIndex = self.glProgram!.attributeIndex("textureCoordinate")
self.glProgram!.link()
self.textureUniformIndex = self.glProgram!.uniformIndex("textureUnit")
// Create the buffer objects
glGenBuffers(1, &vertexBufferObject)
glGenBuffers(1, &indexBufferObject)
// Copy data to video memory
// Vertex data
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferObject)
glBufferData(GLenum(GL_ARRAY_BUFFER), sizeof(GLfloat)*verts.count, verts, GLenum(GL_STATIC_DRAW))
glEnableVertexAttribArray(self.positionIndex)
glVertexAttribPointer(self.positionIndex, GLint(3), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr)
glEnableVertexAttribArray(self.textureCoordinateIndex)
glVertexAttribPointer(self.textureCoordinateIndex, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr.advancedBy(6))
// Indexes
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), indexBufferObject)
glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), sizeof(GLushort) * indices.count, indices, GLenum(GL_STATIC_DRAW))
}
func draw(target:GLenum, name:GLuint) {
glActiveTexture(GLenum(GL_TEXTURE0))
glEnable(target)
glBindTexture(target, name)
glUniform1i(GLint(self.textureUniformIndex), 0)
self.glProgram!.use()
// bind VBOs for vertex array and index array
// for vertex coordinates
let ptr = UnsafePointer<GLfloat>(bitPattern: 0)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), self.vertexBufferObject)
glEnableVertexAttribArray(self.positionIndex)
glVertexAttribPointer(self.positionIndex, GLint(3), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr)
glEnableVertexAttribArray(self.textureCoordinateIndex)
glVertexAttribPointer(self.textureCoordinateIndex, GLint(2), GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(sizeof(GLfloat) * 8), ptr.advancedBy(6))
// Indices
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), self.indexBufferObject) // for indices
// draw 2 triangle (6 indices) using offset of index array
glDrawElements(GLenum(GL_TRIANGLES), GLsizei(6), GLenum(GL_UNSIGNED_SHORT), ptr)
// bind with 0, so, switch back to normal pointer operation
glDisableVertexAttribArray(self.positionIndex)
glDisableVertexAttribArray(self.textureCoordinateIndex)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0)
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), 0)
}
} | mit | c6eedc3d121adde9879141cf90dee5ec | 33.809917 | 157 | 0.617668 | 4.262146 | false | false | false | false |
lakesoft/LKUserDefaultOption | Pod/Classes/LKUserDefaultOptionStepper.swift | 1 | 1011 | //
// LKUserDefaultOptionX.swift
// Pods
//
// Created by Hiroshi Hashiguchi on 2015/10/11.
//
//
public class LKUserDefaultOptionStepper:LKUserDefaultOption {
public var optionValue:Double = 0
public var minimumValue: Double = 0
public var maximumValue: Double = 10.0
public var stepValue: Double = 1.0
// MARK: - LKUserDefaultOptionModel
public override func save() {
saveUserDefaults(optionValue)
}
public override func restore() {
if let value = restoreUserDefaults() as? Double {
optionValue = value
}
}
public override func setValue(value:AnyObject) {
if let value = value as? Double {
optionValue = value
}
}
public override func value() -> AnyObject? {
return optionValue
}
public override func setDefaultValue(defaultValue: AnyObject) {
if let defaultValue = defaultValue as? Double {
optionValue = defaultValue
}
}
}
| mit | 1094e8a06952703a17fe2f3a808d4c69 | 24.275 | 67 | 0.622156 | 4.884058 | false | false | false | false |
OscarSwanros/swift | validation-test/Reflection/existentials.swift | 16 | 18112 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/existentials
// RUN: %target-run %target-swift-reflection-test %t/existentials | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
/*
This file pokes at the swift_reflection_projectExistential API
of the SwiftRemoteMirror library.
It tests the three conditions of existential layout:
- Class existentials
- Existentials whose contained type fits in the 3-word buffer
- Existentials whose contained type has to be allocated into a
raw heap buffer.
- Error existentials, a.k.a. `Error`.
- See also: SwiftReflectionTest.reflect(any:)
- See also: SwiftReflectionTest.reflect(error:)
*/
import SwiftReflectionTest
class MyClass<T, U> {
let x: T
let y: (T, U)
init(x: T, y: (T, U)) {
self.x = x
self.y = y
}
}
struct MyStruct<T, U, V> {
let x: T
let y: U
let z: V
}
protocol MyProtocol {}
protocol MyErrorProtocol : Error {}
struct MyError : MyProtocol, Error {
let i = 0xFEDCBA
}
struct MyCustomError : MyProtocol, MyErrorProtocol {}
struct HasError {
let singleError: Error
let errorInComposition: MyProtocol & Error
let customError: MyErrorProtocol
let customErrorInComposition: MyErrorProtocol & MyProtocol
}
// This will be projected as a class existential, so its
// size doesn't matter.
var mc = MyClass(x: 1010, y: (2020, 3030))
reflect(any: mc)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_class existentials.MyClass
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64: (reference kind=strong refcounting=native)
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_class existentials.MyClass
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32: (reference kind=strong refcounting=native)
// This value fits in the 3-word buffer in the container.
var smallStruct = MyStruct(x: 1, y: 2, z: 3)
reflect(any: smallStruct)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_struct existentials.MyStruct
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64: Type info:
// CHECK-64: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=x offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=y offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=z offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_struct existentials.MyStruct
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32: Type info:
// CHECK-32: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=x offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=y offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=z offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// This value will be copied into a heap buffer, with a
// pointer to it in the existential.
var largeStruct = MyStruct(x: (1,1,1), y: (2,2,2), z: (3,3,3))
reflect(any: largeStruct)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_struct existentials.MyStruct
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int))
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)
// CHECK-64-NEXT: (struct Swift.Int)))
// CHECK-64: Type info:
// CHECK-64-NEXT: (struct size=72 alignment=8 stride=72 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=x offset=0
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=y offset=24
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=z offset=48
// CHECK-64-NEXT: (tuple size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_struct existentials.MyStruct
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int))
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)
// CHECK-32-NEXT: (struct Swift.Int)))
// CHECK-32: Type info:
// CHECK-32: (struct size=36 alignment=4 stride=36 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=x offset=0
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=y offset=12
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=z offset=24
// CHECK-32-NEXT: (tuple size=12 alignment=4 stride=12 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
var he = HasError(singleError: MyError(), errorInComposition: MyError(), customError: MyCustomError(), customErrorInComposition: MyCustomError())
reflect(any: he)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F+]}}
// CHECK-64: Type reference:
// CHECK-64: (struct existentials.HasError)
// CHECK-64: Type info:
// CHECK-64: (struct size=144 alignment=8 stride=144
// CHECK-64-NEXT: (field name=singleError offset=0
// CHECK-64-NEXT: (error_existential size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647
// CHECK-64-NEXT: (field name=error offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-64-NEXT: (field name=errorInComposition offset=8
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=customError offset=56
// CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=customErrorInComposition offset=96
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (struct existentials.HasError)
// CHECK-32: Type info:
// CHECK-32: (struct size=72 alignment=4 stride=72 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=singleError offset=0
// CHECK-32-NEXT: (error_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=error offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-32-NEXT: (field name=errorInComposition offset=4
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=customError offset=28
// CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=customErrorInComposition offset=48
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
reflect(error: MyError())
// CHECK-64: Reflecting an error existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (struct existentials.MyError)
// CHECK-64: Type info:
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=i offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an error existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (struct existentials.MyError)
// CHECK-32: Type info:
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=i offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
doneReflecting()
| apache-2.0 | bb6ddfdfb241900154fdf74905e801ac | 50.454545 | 145 | 0.664311 | 3.201697 | false | false | false | false |
tiagomnh/LicensingViewController | LicensingViewControllerDemo/AppDelegate.swift | 1 | 1636 | //
// AppDelegate.swift
// LicensingViewControllerDemo
//
// Created by Tiago Henriques on 04/08/15.
// Copyright © 2015 Tiago Henriques. All rights reserved.
//
import LicensingViewController
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
let alamofireItem = LicensingItem(
title: "Alamofire",
license: License.mit(owner: "Alamofire Software Foundation (http://alamofire.org/)", years: "2014")
)
let caniveteItem = LicensingItem(
title: "Canivete",
license: License.mit(owner: "Tiago Henriques (http://tiagomnh.com)", years: "2015")
)
let kingfisherItem = LicensingItem(
title: "Kingfisher",
license: License.mit(owner: "Wei Wang", years: "2015")
)
let nanumfontItem = LicensingItem(
title: "Nanum",
license: License.ofl(owner: "NAVER Corporation (http://www.nhncorp.com)", years: "2010")
)
let licensingViewController = LicensingViewController()
licensingViewController.title = "Acknowledgments"
licensingViewController.items = [alamofireItem, caniveteItem, kingfisherItem, nanumfontItem]
licensingViewController.titleColor = UIButton().tintColor!
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.makeKeyAndVisible()
self.window?.rootViewController = UINavigationController(rootViewController: licensingViewController)
}
}
| mit | 7ba22dc8c738f7bc452f18a74090212e | 31.7 | 111 | 0.661774 | 4.671429 | false | false | false | false |
tempestrock/CarPlayer | CarPlayer/Locator.swift | 1 | 8660 | //
// Locator.swift
// Locator
//
// Created by Peter Störmer on 01.12.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
// KEEP IN MIND: In order for location services to work, add one or both of the following entries to Info.plist by simply adding
// them to the "Information Property List", having type "String" and getting no additional value:
// NSLocationWhenInUseUsageDescription
// NSLocationAlwaysUsageDescription
import Foundation
import CoreLocation
class Locator: CLLocationManager, CLLocationManagerDelegate {
var _locationManager: CLLocationManager!
var _seenError : Bool = false
var _locationStatus : NSString = "Not Started"
// Function to call in the case of new data:
var _notifierFunction : ((Int, String, String, String, String, Double, CLLocationCoordinate2D) -> (Void))?
// Use ',' instead of '." in decimal numbers:
var _useGermanDecimals : Bool
// Location Manager helper stuff
override init() {
_useGermanDecimals = false
super.init()
_seenError = false
_locationManager = CLLocationManager()
_locationManager.delegate = self
// Choose the accuracy according to the battery state of the device:
if (UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Charging) ||
(UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Full) {
// We can spend some more battery. ;)
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
} else {
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
_locationManager.requestAlwaysAuthorization()
_notifierFunction = nil
}
//
// Returns the currently used accuracy (which depends on the battery state).
//
func currentlyUsedAccuracy() -> CLLocationAccuracy {
return _locationManager.desiredAccuracy
}
//
// Sets the notification function that shall be called as soon as new data is available.
//
func setNotifierFunction(funcToCall: (Int, String, String, String, String, Double, CLLocationCoordinate2D) -> Void) {
_notifierFunction = funcToCall
}
//
// Sets the flag whether German decimals (taking a ',' instead of a '.') shall be used and printed out.
//
func setUseGermanDecimals(use: Bool) {
_useGermanDecimals = use
}
//
// Location Manager Delegate stuff
//
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
_locationManager.stopUpdatingLocation()
if !_seenError {
_seenError = true
print(error)
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if _notifierFunction == nil {
return
}
let locationArray: NSArray = locations as NSArray
let locationObj: CLLocation = locationArray.lastObject as! CLLocation
let speed: Double = locationObj.speed // in meters per second
let coord: CLLocationCoordinate2D = locationObj.coordinate
let speedAsInt: Int = (speed > 0 ? Int(speed * 3.6) : Locator.defaultSpeed) // km/h
// Also the string-based variant of the notifier function is about to be called.
let altitude = locationObj.altitude // in meters
let course: Double = locationObj.course
let latString = getNiceLatStringFromCoord(coord.latitude)
let longString = getNiceLongStringFromCoord(coord.longitude)
let altString = (getI18NedDecimalString(altitude.format(".0")) + " m")
let courseString = (course >= 0 ? (getI18NedDecimalString(course.format(".0")) + "°") : defaultCourse())
// Call the notification function that has been provided initially
_notifierFunction!(speedAsInt, latString, longString, altString, courseString, course, coord)
/*
print("Coord: \(latString), \(longString)")
print("Speed: \(speedString)")
print("Altitude: \(altString)")
print("Course: \(courseString)")
*/
}
func getNiceLatStringFromCoord(coord: Double) -> String {
return getNiceStringFromCoord(coord, posChar: "N", negChar: "S")
}
func getNiceLongStringFromCoord(coord: Double) -> String {
return getNiceStringFromCoord(coord, posChar: "E", negChar: "W")
}
//
// Makes something like "053°50,32'N" out of "53.853453"
//
func getNiceStringFromCoord(coord: Double, posChar: Character, negChar: Character) -> String {
// print("Coord: \(coord)")
let separatorChar = (_useGermanDecimals ? "," : ".")
var localCoord = coord
var finalChar: Character
if localCoord < 0 {
finalChar = negChar
localCoord = localCoord * (-1)
} else {
finalChar = posChar
}
var resultStr: String
resultStr = ""
// Get the part of the coordinate that is left of the ".":
let intPartOfCoord = Int(localCoord)
// Make "008" from "8":
resultStr = intPartOfCoord.format("03")
// Remove the integer part from the coordinate
localCoord = localCoord - Double(intPartOfCoord)
// Make the "minutes" part out of the number right of the ".":
localCoord = localCoord * 60
let intPartOfMinutes = Int(localCoord)
resultStr = resultStr + "° " + intPartOfMinutes.format("02") + separatorChar
// Remove the "minutes" part from the coordinate
localCoord = localCoord - Double(intPartOfMinutes)
// Shift three digits further out:
localCoord = localCoord * 10
// Get these two digits alone:
let intPartOfSeconds = Int(localCoord)
resultStr = resultStr + intPartOfSeconds.format("01") + "' "
// Append "N", "S", "E", or "W":
resultStr.append(finalChar)
// print(" --> " + resultStr)
return resultStr
}
//
// Returns a decimal string that has a ',' instead of a '.' if the localization is wanted.
//
func getI18NedDecimalString (str: String) -> String {
if _useGermanDecimals {
let newString = str.stringByReplacingOccurrencesOfString(".", withString: ",", options: NSStringCompareOptions.LiteralSearch, range: nil)
return newString
} else {
return str
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
_locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
_locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
_locationStatus = "Status not determined"
default:
_locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if shouldIAllow {
//DEBUG NSLog("Location to Allowed")
// Start location services
_locationManager.startUpdatingLocation()
// _locationManager.startUpdatingHeading()
} else {
NSLog("Denied access: \(_locationStatus)")
}
}
//
// Returns a default string for an "empty" speed.
//
class var defaultSpeedString: String {
get {
return "--"
}
}
//
// Returns a default value for an "empty" speed.
//
class var defaultSpeed: Int {
get {
return -1
}
}
//
// Returns a default string for an "empty" latitude.
//
func defaultLatitude() -> String {
return "---° --" + (_useGermanDecimals ? "," : ".") + "-' N"
}
//
// Returns a default string for an "empty" longitude.
//
func defaultLongitude() -> String {
return "---° --" + (_useGermanDecimals ? "," : ".") + "-' E"
}
//
// Returns a default string for an "empty" altitude.
//
func defaultAltitude() -> String {
return "-- m"
}
//
// Returns a default string for an "empty" course.
//
func defaultCourse() -> String {
return "---°"
}
}
| gpl-3.0 | b3e63914f0c3bae603503c5548fc0c44 | 27.463816 | 149 | 0.6095 | 4.828683 | false | false | false | false |
douShu/weiboInSwift | weiboInSwift/weiboInSwift/Classes/Module/Home(首页)/StatusCell/TopView.swift | 1 | 3693 | //
// TopView.swift
// weiboInSwift
//
// Created by 逗叔 on 15/9/11.
// Copyright © 2015年 逗叔. All rights reserved.
//
import UIKit
class TopView: UIView {
// MARK: - |----------------------------- 属性 -----------------------------|
var status: Status? {
didSet {
if let url = status?.user?.imageURL {
iconView.sd_setImageWithURL(url)
}
nameLabel.text = status?.user?.name ?? ""
vipIconView.image = status?.user?.vipImage
memberIconView.image = status?.user?.memberImage
// TODO: 后面会讲
timeLabel.text = NSDate.sinaDate((status?.created_at)!)?.dateDesctiption
sourceLabel.text = status?.source
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
// MARK: - |----------------------------- 构造方法 -----------------------------|
override init(frame: CGRect) {
super.init(frame: frame)
setupSubview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - |----------------------------- 设置子控件 -----------------------------|
private func setupSubview() {
addSubview(sepView)
addSubview(iconView)
addSubview(nameLabel)
addSubview(timeLabel)
addSubview(sourceLabel)
addSubview(memberIconView)
addSubview(vipIconView)
// 设置布局
sepView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10))
iconView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: sepView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: cellSubviewMargin, y: cellSubviewMargin))
nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
memberIconView.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: nameLabel, size: nil, offset: CGPoint(x: cellSubviewMargin, y: 0))
vipIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: cellSubviewMargin, y: cellSubviewMargin))
}
// MARK: - |----------------------------- 懒加载子控件 -----------------------------|
// 灰色分隔
private lazy var sepView: UIView = {
let v = UIView()
v.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
return v
}()
// 头像
private lazy var iconView: UIImageView = UIImageView()
// 姓名
private lazy var nameLabel: UILabel = UILabel(textLabelColor: UIColor.darkGrayColor(), fontSize: 14)
// 时间标签
private lazy var timeLabel: UILabel = UILabel(textLabelColor: UIColor.orangeColor(), fontSize: 9)
// 来源标签
private lazy var sourceLabel: UILabel = UILabel(textLabelColor: UIColor.lightGrayColor(), fontSize: 9)
// 会员图标
private lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
// vip图标
private lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_vip"))
}
| mit | 46b4f594330893fc488f9fc163c48977 | 35.242424 | 182 | 0.586678 | 4.496241 | false | false | false | false |
Yalantis/DisplaySwitcher | Example/DisplaySwitcher/Models/User/User.swift | 1 | 644 | //
// User.swift
// YALLayoutTransitioning
//
// Created by Roman on 23.02.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class User {
var name: String
var surname: String
var avatar: UIImage
var postsCount: Int
var commentsCount: Int
var likesCount: Int
init(name: String, surname: String, avatar: UIImage, postsCount: Int, commentsCount: Int, likesCount: Int) {
self.name = name
self.surname = surname
self.avatar = avatar
self.postsCount = postsCount
self.commentsCount = commentsCount
self.likesCount = likesCount
}
}
| mit | a81c5fb5f581715780ff3ddf6abe9cc1 | 21.172414 | 112 | 0.642302 | 4.230263 | false | false | false | false |
Coderian/SwiftedGPX | SwiftedGPX/Elements/License.swift | 1 | 1400 | //
// License.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/17.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX License
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="license" type="xsd:anyURI" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Link to external file containing license text.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class License : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName: String = "license"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Copyright: v.value.license = self
default: break
}
}
}
}
public var value: String!
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
} | mit | 615745240f82f35de7c012ebc0f13704 | 28.217391 | 83 | 0.593448 | 3.881503 | false | false | false | false |
vincent-cheny/DailyRecord | DailyRecord/SettingViewController.swift | 1 | 2175 | //
// SettingViewController.swift
// DailyRecord
//
// Created by ChenYong on 16/2/11.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
import UIKit
import Realm
class SettingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backItem = UIBarButtonItem()
backItem.title = ""
self.navigationItem.backBarButtonItem = backItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false;
}
@IBAction func resetData(sender: AnyObject) {
let alert = UIAlertController(title: "", message: "确认删除所有记录", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
RecordTemplate().resetTemplate()
Industry().resetIndustry()
Remind().resetRemind()
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: Utils.needBlackCheck)
defaults.setBool(false, forKey: Utils.needWhiteCheck)
defaults.setBool(false, forKey: Utils.needDailySummary)
defaults.setObject([20, 0], forKey: Utils.summaryTime)
defaults.setInteger(4, forKey: Utils.timeSetting1)
defaults.setInteger(8, forKey: Utils.timeSetting2)
defaults.setInteger(10, forKey: Utils.timeSetting3)
defaults.setInteger(13, forKey: Utils.timeSetting4)
defaults.setInteger(17, forKey: Utils.timeSetting5)
defaults.setInteger(21, forKey: Utils.timeSetting6)
}))
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
} | gpl-2.0 | f8efef28f945a382217691699f93fe8e | 38.072727 | 123 | 0.670857 | 4.826966 | false | false | false | false |
ahoppen/swift | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift | 14 | 3533 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5OuterOyAA5InnerVySiGGWV" = linkonce_odr hidden constant %swift.enum_vwtable
// CHECK: @"$s4main5OuterOyAA5InnerVySiGGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (
// CHECK-SAME: %swift.enum_vwtable,
// CHECK-SAME: %swift.enum_vwtable* @"$s4main5OuterOyAA5InnerVySiGGWV",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 0
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5InnerVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Outer<First> {
case first(First)
}
struct Inner<First> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5OuterOyAA5InnerVySiGGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Outer.first(Inner(first: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 6acccc645c4d89f12d12fe12fc137f0e | 35.05102 | 157 | 0.584489 | 2.944167 | false | false | false | false |
ahoppen/swift | SwiftCompilerSources/Sources/SIL/Location.swift | 2 | 598 | //===--- Location.swift - Source location ---------------------------------===//
//
// 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 SILBridging
public struct Location {
let bridged: BridgedLocation
}
| apache-2.0 | b0bb579932cedda0f8e970f2dd5f3834 | 34.176471 | 80 | 0.593645 | 5.067797 | false | false | false | false |
ahoppen/swift | test/Interpreter/SDK/objc_cast.swift | 13 | 19063 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
@objc protocol SwiftObjCProto {}
class SwiftSuperPort : Port { }
class SwiftSubPort : SwiftSuperPort { }
class SwiftSuper { }
class SwiftSub : SwiftSuper { }
extension Port : SwiftObjCProto {}
var obj : AnyObject
func genericCast<T>(_ x: AnyObject, _: T.Type) -> T? {
return x as? T
}
func genericCastObjCBound<T: NSObject>(_ x: AnyObject, _: T.Type) -> T? {
return x as? T
}
// Test instance of Swift subclass of Objective-C class
obj = SwiftSubPort()
_ = obj as! SwiftSubPort
_ = obj as! SwiftSuperPort
_ = (obj as? Port)
_ = (obj as? NSObject)!
if (obj as? SwiftSubPort) == nil { abort() }
if (obj as? SwiftSuperPort) == nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
obj = SwiftSuperPort()
_ = obj as! SwiftSuperPort
_ = obj as! Port
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) == nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
// Test instance of Objective-C class that has Swift subclass
obj = Port()
_ = obj as! Port
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? Port) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
if (obj as? SwiftObjCProto) == nil { abort() }
obj = Port()
_ = genericCast(obj, Port.self)!
_ = genericCast(obj, NSObject.self)!
if genericCast(obj, SwiftSubPort.self) != nil { abort() }
if genericCast(obj, SwiftSuperPort.self) != nil { abort() }
if genericCast(obj, Port.self) == nil { abort() }
if genericCast(obj, NSObject.self) == nil { abort() }
if genericCast(obj, NSArray.self) != nil { abort() }
if genericCast(obj, SwiftSub.self) != nil { abort() }
if genericCast(obj, SwiftSuper.self) != nil { abort() }
_ = genericCastObjCBound(obj, Port.self)!
_ = genericCastObjCBound(obj, NSObject.self)!
if genericCastObjCBound(obj, SwiftSubPort.self) != nil { abort() }
if genericCastObjCBound(obj, SwiftSuperPort.self) != nil { abort() }
if genericCastObjCBound(obj, Port.self) == nil { abort() }
if genericCastObjCBound(obj, NSObject.self) == nil { abort() }
if genericCastObjCBound(obj, NSArray.self) != nil { abort() }
obj = NSObject()
_ = obj as! NSObject
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? Port) != nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSCopying) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
if (obj as? SwiftObjCProto) != nil { abort() }
// Test instance of a tagged pointer type
obj = NSNumber(value: 1234567)
_ = obj as! NSNumber
_ = obj as! NSValue
_ = obj as! NSObject
_ = obj as! NSCopying
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSNumber) == nil { abort() }
if (obj as? NSValue) == nil { abort() }
if (obj as? NSObject) == nil { abort() }
if (obj as? NSCopying) == nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) != nil { abort() }
// Test instance of a Swift class with no Objective-C inheritance
obj = SwiftSub()
_ = obj as! SwiftSub
_ = obj as! SwiftSuper
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSObject) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) == nil { abort() }
if (obj as? SwiftSuper) == nil { abort() }
obj = SwiftSuper()
_ = obj as! SwiftSuper
if (obj as? SwiftSubPort) != nil { abort() }
if (obj as? SwiftSuperPort) != nil { abort() }
if (obj as? NSObject) != nil { abort() }
if (obj as? NSArray) != nil { abort() }
if (obj as? SwiftSub) != nil { abort() }
if (obj as? SwiftSuper) == nil { abort() }
// Test optional and non-optional bridged conversions
var ao: AnyObject = "s" as NSObject
ao as! String
ao is String
var auo: AnyObject! = "s" as NSObject
var s: String = auo as! String
var auoo: AnyObject? = "s" as NSObject
auoo! as? String
// Test bridged casts.
// CHECK: Downcast to hello
obj = NSString(string: "hello")
if let str = obj as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string hello
let forcedStr: String = obj as! String
print("Forced to string \(forcedStr)")
// CHECK-NEXT: Downcast to Swift
var objOpt: AnyObject? = NSString(string: "Swift")
if let str = objOpt as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string Swift
let forcedStrOpt: String = objOpt as! String
print("Forced to string \(forcedStrOpt)")
// CHECK-NEXT: Downcast to world
var objImplicitOpt: AnyObject! = NSString(string: "world")
if let str = objImplicitOpt as? String {
print("Downcast to \(str)")
} else {
print("Not a string?")
}
// Forced cast using context
// CHECK-NEXT: Forced to string world
let forcedStrImplicitOpt: String = objImplicitOpt as! String
print("Forced to string \(forcedStrImplicitOpt)")
// CHECK-NEXT: Downcast correctly failed due to nil
objOpt = nil
if let str = objOpt as? String {
print("Downcast should not succeed for nil")
} else {
print("Downcast correctly failed due to nil")
}
// CHECK-NEXT: Downcast correctly failed due to nil
objImplicitOpt = nil
if let str = objImplicitOpt as? String {
print("Downcast should not succeed for nil")
} else {
print("Downcast correctly failed due to nil")
}
// Test bridged "isa" checks.
// CHECK: It's a string!
obj = NSString(string: "hello")
if obj is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: It's a string!
objOpt = NSString(string: "Swift")
if objOpt is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: It's a string!
objImplicitOpt = NSString(string: "world")
if objImplicitOpt is String {
print("It's a string!")
} else {
print("Not a string?")
}
// CHECK-NEXT: Isa correctly failed due to nil
objOpt = nil
if objOpt is String {
print("Isa should not succeed for nil")
} else {
print("Isa correctly failed due to nil")
}
// CHECK-NEXT: Isa correctly failed due to nil
objImplicitOpt = nil
if objImplicitOpt is String {
print("Isa should not succeed for nil")
} else {
print("Isa correctly failed due to nil")
}
let words = ["Hello", "Swift", "World"]
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
obj = words as AnyObject
if let strArr = obj as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Check downcast from the bridged type itself.
// CHECK-NEXT: NSArray-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarr = words as NSArray
if let strArr = nsarr as? [String] {
print("NSArray-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray?-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarrOpt = words as NSArray?
if let strArr = nsarrOpt as? [String] {
print("NSArray?-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray?-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray!-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsarrImplicitOpt = words as NSArray!
if let strArr = nsarrImplicitOpt as? [String] {
print("NSArray!-to-bridged-array cast produced \(strArr)")
} else {
print("NSArray!-to-bridged-array cast failed")
}
// Check downcast from a superclass of the bridged type.
// CHECK-NEXT: NSObject-to-bridged-array cast produced ["Hello", "Swift", "World"]
var nsobj: NSObject = nsarr
if let strArr = nsobj as? [String] {
print("NSObject-to-bridged-array cast produced \(strArr)")
} else {
print("NSObject-to-bridged-array cast failed")
}
// CHECK-NEXT: NSArray is [String]
if nsarr is [String] {
print("NSArray is [String]")
} else {
print("NSArray is not a [String]")
}
// CHECK-NEXT: NSArray? is [String]
if nsarrOpt is [String] {
print("NSArray? is [String]")
} else {
print("NSArray? is not a [String]")
}
// CHECK-NEXT: NSArray! is [String]
if nsarrImplicitOpt is [String] {
print("NSArray! is [String]")
} else {
print("NSArray! is not a [String]")
}
// CHECK-NEXT: NSObject is [String]
if nsobj is [String] {
print("NSObject is [String]")
} else {
print("NSObject is not a [String]")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
var forcedStrArray: [String] = obj as! [String]
print("Forced to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarr as! [String]
print("Forced NSArray to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray? to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarrOpt as! [String]
print("Forced NSArray? to string array \(forcedStrArray)")
// CHECK-NEXT: Forced NSArray! to string array ["Hello", "Swift", "World"]
forcedStrArray = nsarrImplicitOpt as! [String]
print("Forced NSArray! to string array \(forcedStrArray)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = obj as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK-NEXT: Object-to-bridged-array cast failed due to bridge mismatch
if let strArr = obj as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK-NEXT: Array of strings is not an array of ints
if obj is [Int] {
print("Array of strings should not be an array of ints!")
} else {
print("Array of strings is not an array of ints")
}
// Implicitly unwrapped optional of object to array casts.
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
objOpt = words as AnyObject?
if let strArr = objOpt as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
let forcedStrArrayOpt: [String] = objOpt as! [String]
print("Forced to string array \(forcedStrArrayOpt)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = objOpt as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK: Object-to-bridged-array cast failed due to bridge mismatch
if let intArr = objOpt as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK: Object-to-bridged-array cast failed due to nil
objOpt = nil
if let strArr = objOpt as? [String] {
print("Cast from nil succeeded?")
} else {
print("Object-to-bridged-array cast failed due to nil")
}
// Optional of object to array casts.
// CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"]
objImplicitOpt = words as AnyObject!
if let strArr = objImplicitOpt as? [String] {
print("Object-to-bridged-array cast produced \(strArr)")
} else {
print("Object-to-bridged-array cast failed")
}
// Forced downcast based on context.
// CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"]
let forcedStrArrayImplicitOpt: [String] = objImplicitOpt as! [String]
print("Forced to string array \(forcedStrArrayImplicitOpt)")
// CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World]
if let strArr = objImplicitOpt as? [NSString] {
print("Object-to-array cast produced \(strArr)")
} else {
print("Object-to-array cast failed")
}
// CHECK: Object-to-bridged-array cast failed due to bridge mismatch
if let intArr = objImplicitOpt as? [Int] {
print("Object-to-bridged-array cast should not have succeeded")
} else {
print("Object-to-bridged-array cast failed due to bridge mismatch")
}
// CHECK: Object-to-bridged-array cast failed due to nil
objImplicitOpt = nil
if let strArr = objImplicitOpt as? [String] {
print("Cast from nil succeeded?")
} else {
print("Object-to-bridged-array cast failed due to nil")
}
// Casting an array of numbers to different numbers.
// CHECK: Numbers-as-doubles cast produces [3.9375, 2.71828, 0.0]
obj = ([3.9375, 2.71828, 0] as [Double]) as AnyObject
if let doubleArr = obj as? [Double] {
print(MemoryLayout<Double>.size)
print("Numbers-as-doubles cast produces \(doubleArr)")
} else {
print("Numbers-as-doubles failed")
}
// CHECK-FAIL: Numbers-as-floats cast produces [3.9375, 2.71828{{.*}}, 0.0]
// TODO: check if this is intention: rdar://33021520
if let floatArr = obj as? [Float] {
print(MemoryLayout<Float>.size)
print("Numbers-as-floats cast produces \(floatArr)")
} else {
print("Numbers-as-floats failed")
}
// CHECK-FAIL: Numbers-as-ints cast produces [3, 2, 0]
// TODO: check if this is intention: rdar://33021520
if let intArr = obj as? [Int] {
print("Numbers-as-ints cast produces \(intArr)")
} else {
print("Numbers-as-ints failed")
}
// CHECK-FAIL: Numbers-as-bools cast produces [true, true, false]
// TODO: check if this is intention: rdar://33021520
if let boolArr = obj as? [Bool] {
print("Numbers-as-bools cast produces \(boolArr)")
} else {
print("Numbers-as-bools failed")
}
class Base : NSObject {
override var description: String {
return "Base"
}
}
class Derived : Base {
override var description: String {
return "Derived"
}
}
// CHECK: Array-of-base cast produces [Derived, Derived, Base]
obj = [Derived(), Derived(), Base()] as NSObject
if let baseArr = obj as? [Base] {
print("Array-of-base cast produces \(baseArr)")
} else {
print("Not an array of base")
}
// CHECK: Not an array of derived
if let derivedArr = obj as? [Derived] {
print("Array-of-derived cast produces \(derivedArr)")
} else {
print("Not an array of derived")
}
// CHECK: Dictionary-of-base-base cast produces
obj = [Derived() : Derived(), Derived() : Base(), Derived() : Derived() ] as AnyObject
if let baseDict = obj as? Dictionary<Base, Base> {
print("Dictionary-of-base-base cast produces \(baseDict)")
} else {
print("Not a dictionary of base/base")
}
// CHECK: Dictionary-of-derived-base cast produces
if let baseDict = obj as? Dictionary<Derived, Base> {
print("Dictionary-of-derived-base cast produces \(baseDict)")
} else {
print("Not a dictionary of derived/base")
}
// CHECK: Not a dictionary of derived/derived
if let dict = obj as? Dictionary<Derived, Derived> {
print("Dictionary-of-derived-derived cast produces \(dict)")
} else {
print("Not a dictionary of derived/derived")
}
let strArray: AnyObject = ["hello", "world"] as NSObject
let intArray: AnyObject = [1, 2, 3] as NSObject
let dictArray: AnyObject = [["hello" : 1, "world" : 2],
["swift" : 1, "speedy" : 2]] as NSObject
// CHECK: Dictionary<String, AnyObject> is
obj = ["a" : strArray, "b" : intArray, "c": dictArray] as NSObject
if let dict = obj as? Dictionary<String, [AnyObject]> {
print("Dictionary<String, AnyObject> is \(dict)")
} else {
print("Not a Dictionary<String, AnyObject>")
}
// CHECK: Not a Dictionary<String, String>
if let dict = obj as? Dictionary<String, [String]> {
print("Dictionary<String, String> is \(dict)")
} else {
print("Not a Dictionary<String, String>")
}
// CHECK: Not a Dictionary<String, Int>
if let dict = obj as? Dictionary<String, [Int]> {
print("Dictionary<String, Int> is \(dict)")
} else {
print("Not a Dictionary<String, Int>")
}
// CHECK: [Dictionary<String, Int>] is
obj = dictArray
if let array = obj as? [Dictionary<String, Int>] {
print("[Dictionary<String, Int>] is \(array)")
} else {
print("Not a [Dictionary<String, Int>]")
}
// CHECK: Not a [Dictionary<String, String>]
if let array = obj as? [Dictionary<String, String>] {
print("[Dictionary<String, String>] is \(array)")
} else {
print("Not a [Dictionary<String, String>]")
}
// CHECK: Dictionary<String, [Dictionary<String, Int>]> is ["a": [
obj = ["a" : dictArray] as NSObject
if let dict = obj as? Dictionary<String, [Dictionary<String, Int>]> {
print("Dictionary<String, [Dictionary<String, Int>]> is \(dict)")
} else {
print("Not a Dictionary<String, [Dictionary<String, Int>]>")
}
// CHECK: Not a Dictionary<String, [Dictionary<String, String>]>
if let dict = obj as? Dictionary<String, [Dictionary<String, String>]> {
print("Dictionary<String, [Dictionary<String, String>]> is \(dict)")
} else {
print("Not a Dictionary<String, [Dictionary<String, String>]>")
}
// CHECK: [Dictionary<String, [Dictionary<String, Int>]>] is
obj = [obj, obj, obj] as NSObject
if let array = obj as? [Dictionary<String, [Dictionary<String, Int>]>] {
print("[Dictionary<String, [Dictionary<String, Int>]>] is \(array)")
} else {
print("Not a [Dictionary<String, [Dictionary<String, Int>]>]")
}
// CHECK: Not a Dictionary<String, [Dictionary<String, String>]>[]
if let array = obj as? Dictionary<String, [Dictionary<String, String>]> {
print("Dictionary<String, [Dictionary<String, String>]>[] is \(array)")
} else {
print("Not a Dictionary<String, [Dictionary<String, String>]>[]")
}
// Helper function that downcasts
func downcastToStringArrayOptOpt(_ obj: AnyObject???!) {
if let strArrOptOpt = obj as? [String]?? {
if let strArrOpt = strArrOptOpt {
if let strArr = strArrOpt {
print("some(some(some(\(strArr))))")
} else {
print("some(some(none))")
}
} else {
print("some(none)")
}
} else {
print("none")
}
}
// CHECK: {{^}}some(some(some(["a", "b", "c"]))){{$}}
var objOptOpt: AnyObject?? = .some(.some(["a", "b", "c"] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
// CHECK: {{^}}none{{$}}
objOptOpt = .some(.some([1 : "hello", 2 : "swift", 3 : "world"] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
// CHECK: {{^}}none{{$}}
objOptOpt = .some(.some([1, 2, 3] as NSObject))
downcastToStringArrayOptOpt(objOptOpt)
print("ok") // CHECK: ok
| apache-2.0 | 65cb02aebd12f060362c10ac1fe07a72 | 30.148693 | 86 | 0.659393 | 3.313576 | false | false | false | false |
dreamsxin/swift | test/SILGen/objc_imported_generic.swift | 1 | 5187 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared @_TFCSo12GenericClassCfT5thingGSQx__GSQGS_x__
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil @_TF21objc_imported_generic24genericMethodOnAnyObject
// CHECK: dynamic_method [volatile] {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign : <T where T : AnyObject> GenericClass<T> -> () -> T?, $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil @_TF21objc_imported_generic31genericMethodOnAnyObjectChained
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil @_TF21objc_imported_generic27genericSubscriptOnAnyObject
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil @_TF21objc_imported_generic26genericPropertyOnAnyObject
// CHECK: dynamic_method_br %4 : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
// TODO: Crashes in IRGen because the type metadata for `T` is not found in
// the witness thunk to satisfy the associated type requirement. This could be
// addressed by teaching IRGen to fulfill erased type parameters from protocol
// witness tables (rdar://problem/26602097).
#if !IRGEN_INTEGRATION_TEST
extension GenericClass: ThingHolder {}
#endif
public func genericBlockBridging<T: AnyObject>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil @_TF21objc_imported_generic20genericBlockBridging
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @_TTRGRxs9AnyObjectrXFdCb_dx_ax_XFo_ox_ox_
// CHECK: partial_apply [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @_TTRGRxs9AnyObjectrXFo_ox_ox_XFdCb_dx_ax_
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil @_TF21objc_imported_generic20arraysOfGenericParam
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref {{@_TFCSo12GenericClassCfT13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned ImplicitlyUnwrappedOptional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil shared [thunk] @_TTOFCSo12GenericClasscfT13arrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned ImplicitlyUnwrappedOptional<GenericClass<τ_0_0>>
| apache-2.0 | 2010069e957c2a9887f8bc688f350b77 | 55.184783 | 288 | 0.698201 | 3.710696 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/URLRequest.swift | 1 | 11767 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
public struct URLRequest : ReferenceConvertible, Equatable, Hashable {
public typealias ReferenceType = NSURLRequest
public typealias CachePolicy = NSURLRequest.CachePolicy
public typealias NetworkServiceType = NSURLRequest.NetworkServiceType
/*
NSURLRequest has a fragile ivar layout that prevents the swift subclass approach here, so instead we keep an always mutable copy
*/
internal var _handle: _MutableHandle<NSMutableURLRequest>
internal mutating func _applyMutation<ReturnType>(_ whatToDo : (NSMutableURLRequest) -> ReturnType) -> ReturnType {
if !isKnownUniquelyReferenced(&_handle) {
let ref = _handle._uncopiedReference()
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._uncopiedReference())
}
/// Creates and initializes a URLRequest with the given URL and cache policy.
/// - parameter url: The URL for the request.
/// - parameter cachePolicy: The cache policy for the request. Defaults to `.useProtocolCachePolicy`
/// - parameter timeoutInterval: The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals. Defaults to 60.0
public init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0) {
_handle = _MutableHandle(adoptingReference: NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
fileprivate init(_bridged request: NSURLRequest) {
_handle = _MutableHandle(reference: request.mutableCopy() as! NSMutableURLRequest)
}
/// The URL of the receiver.
public var url: URL? {
get {
return _handle.map { $0.url }
}
set {
_applyMutation { $0.url = newValue }
}
}
/// The cache policy of the receiver.
public var cachePolicy: CachePolicy {
get {
return _handle.map { $0.cachePolicy }
}
set {
_applyMutation { $0.cachePolicy = newValue }
}
}
//URLRequest.timeoutInterval should be given precedence over the URLSessionConfiguration.timeoutIntervalForRequest regardless of the value set,
// if it has been set at least once. Even though the default value is 60 ,if the user sets URLRequest.timeoutInterval
// to explicitly 60 then the precedence should be given to URLRequest.timeoutInterval.
internal var isTimeoutIntervalSet = false
/// Returns the timeout interval of the receiver.
/// - discussion: The timeout interval specifies the limit on the idle
/// interval allotted to a request in the process of loading. The "idle
/// interval" is defined as the period of time that has passed since the
/// last instance of load activity occurred for a request that is in the
/// process of loading. Hence, when an instance of load activity occurs
/// (e.g. bytes are received from the network for a request), the idle
/// interval for a request is reset to 0. If the idle interval ever
/// becomes greater than or equal to the timeout interval, the request
/// is considered to have timed out. This timeout interval is measured
/// in seconds.
public var timeoutInterval: TimeInterval {
get {
return _handle.map { $0.timeoutInterval }
}
set {
_applyMutation { $0.timeoutInterval = newValue }
isTimeoutIntervalSet = true
}
}
/// The main document URL associated with this load.
/// - discussion: This URL is used for the cookie "same domain as main
/// document" policy.
public var mainDocumentURL: URL? {
get {
return _handle.map { $0.mainDocumentURL }
}
set {
_applyMutation { $0.mainDocumentURL = newValue }
}
}
/// The URLRequest.NetworkServiceType associated with this request.
/// - discussion: This will return URLRequest.NetworkServiceType.default for requests that have
/// not explicitly set a networkServiceType
public var networkServiceType: NetworkServiceType {
get {
return _handle.map { $0.networkServiceType }
}
set {
_applyMutation { $0.networkServiceType = newValue }
}
}
/// `true` if the receiver is allowed to use the built in cellular radios to
/// satisfy the request, `false` otherwise.
public var allowsCellularAccess: Bool {
get {
return _handle.map { $0.allowsCellularAccess }
}
set {
_applyMutation { $0.allowsCellularAccess = newValue }
}
}
/// The HTTP request method of the receiver.
public var httpMethod: String? {
get {
return _handle.map { $0.httpMethod }
}
set {
_applyMutation {
if let value = newValue {
$0.httpMethod = value
} else {
$0.httpMethod = "GET"
}
}
}
}
/// A dictionary containing all the HTTP header fields of the
/// receiver.
public var allHTTPHeaderFields: [String : String]? {
get {
return _handle.map { $0.allHTTPHeaderFields }
}
set {
_applyMutation { $0.allHTTPHeaderFields = newValue }
}
}
/// The value which corresponds to the given header
/// field. Note that, in keeping with the HTTP RFC, HTTP header field
/// names are case-insensitive.
/// - parameter field: the header field name to use for the lookup (case-insensitive).
public func value(forHTTPHeaderField field: String) -> String? {
return _handle.map { $0.value(forHTTPHeaderField: field) }
}
/// If a value was previously set for the given header
/// field, that value is replaced with the given value. Note that, in
/// keeping with the HTTP RFC, HTTP header field names are
/// case-insensitive.
public mutating func setValue(_ value: String?, forHTTPHeaderField field: String) {
_applyMutation {
$0.setValue(value, forHTTPHeaderField: field)
}
}
/// This method provides a way to add values to header
/// fields incrementally. If a value was previously set for the given
/// header field, the given value is appended to the previously-existing
/// value. The appropriate field delimiter, a comma in the case of HTTP,
/// is added by the implementation, and should not be added to the given
/// value by the caller. Note that, in keeping with the HTTP RFC, HTTP
/// header field names are case-insensitive.
public mutating func addValue(_ value: String, forHTTPHeaderField field: String) {
_applyMutation {
$0.addValue(value, forHTTPHeaderField: field)
}
}
/// This data is sent as the message body of the request, as
/// in done in an HTTP POST request.
public var httpBody: Data? {
get {
return _handle.map { $0.httpBody }
}
set {
_applyMutation { $0.httpBody = newValue }
}
}
/// The stream is returned for examination only; it is
/// not safe for the caller to manipulate the stream in any way. Also
/// note that the HTTPBodyStream and HTTPBody are mutually exclusive - only
/// one can be set on a given request. Also note that the body stream is
/// preserved across copies, but is LOST when the request is coded via the
/// NSCoding protocol
public var httpBodyStream: InputStream? {
get {
return _handle.map { $0.httpBodyStream }
}
set {
_applyMutation { $0.httpBodyStream = newValue }
}
}
/// `true` if cookies will be sent with and set for this request; otherwise `false`.
public var httpShouldHandleCookies: Bool {
get {
return _handle.map { $0.httpShouldHandleCookies }
}
set {
_applyMutation { $0.httpShouldHandleCookies = newValue }
}
}
/// `true` if the receiver should transmit before the previous response
/// is received. `false` if the receiver should wait for the previous response
/// before transmitting.
public var httpShouldUsePipelining: Bool {
get {
return _handle.map { $0.httpShouldUsePipelining }
}
set {
_applyMutation { $0.httpShouldUsePipelining = newValue }
}
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_handle.map { $0 })
}
public static func ==(lhs: URLRequest, rhs: URLRequest) -> Bool {
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
extension URLRequest : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let u = url {
return u.description
} else {
return "url: nil"
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "url", value: url as Any))
c.append((label: "cachePolicy", value: cachePolicy.rawValue))
c.append((label: "timeoutInterval", value: timeoutInterval))
c.append((label: "mainDocumentURL", value: mainDocumentURL as Any))
c.append((label: "networkServiceType", value: networkServiceType))
c.append((label: "allowsCellularAccess", value: allowsCellularAccess))
c.append((label: "httpMethod", value: httpMethod as Any))
c.append((label: "allHTTPHeaderFields", value: allHTTPHeaderFields as Any))
c.append((label: "httpBody", value: httpBody as Any))
c.append((label: "httpBodyStream", value: httpBodyStream as Any))
c.append((label: "httpShouldHandleCookies", value: httpShouldHandleCookies))
c.append((label: "httpShouldUsePipelining", value: httpShouldUsePipelining))
return Mirror(self, children: c, displayStyle: .struct)
}
}
extension URLRequest : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLRequest.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLRequest {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) {
result = URLRequest(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) -> Bool {
result = URLRequest(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLRequest?) -> URLRequest {
var result: URLRequest? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 | 58616c54194defb534e32de0b8a3ef24 | 38.223333 | 179 | 0.631087 | 5.065433 | false | false | false | false |
ReedD/RolodexNavigationController | RolodexNavigationController/ChildViewController.swift | 1 | 1986 | //
// ChildViewController.swift
// RolodexNavigationController
//
// Created by Reed Dadoune on 12/7/14.
// Copyright (c) 2014 Dadoune. All rights reserved.
//
import UIKit
class ChildViewController: UIViewController {
@IBOutlet weak var previousController: UIButton!
@IBOutlet weak var nextController: UIButton!
enum ControllerNavigation: Int {
case Previous, Next
}
var rolodexController: RolodexNavigationController? {
get {
if let controller = self.navigationController?.parentViewController as? RolodexNavigationController {
return controller
}
return nil
}
}
@IBAction func showRolodexTouched(sender: AnyObject) {
self.rolodexController?.showRolodex = true;
}
@IBAction func goToController(sender: UIButton) {
if let rolodexController = self.rolodexController {
let button = ControllerNavigation(rawValue: sender.tag)
var index = 0
if let button = ControllerNavigation(rawValue: sender.tag) {
switch button {
case .Next:
index = rolodexController.selectedIndex! + 1
case .Previous:
index = rolodexController.selectedIndex! - 1
}
}
let viewController = rolodexController.viewControllers[index]
rolodexController.goToViewController(viewController, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
var randomRed = CGFloat(drand48())
var randomGreen = CGFloat(drand48())
var randomBlue = CGFloat(drand48())
self.view.backgroundColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.previousController?.enabled = true
self.previousController?.enabled = true
if self.rolodexController?.viewControllers.first == self.navigationController {
self.previousController?.enabled = false
} else if self.rolodexController?.viewControllers.last == self.navigationController {
self.nextController?.enabled = false
}
}
}
| mit | ae89488f52a1f6cca42ac3d7b13c54a6 | 27.782609 | 104 | 0.738167 | 3.82659 | false | false | false | false |
schibsted/layout | Layout/LayoutNode+Layout.swift | 1 | 3550 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
extension LayoutNode {
/// Create a new LayoutNode instance from a Layout template
convenience init(
layout: Layout,
outlet: String? = nil,
state: Any = (),
constants: [String: Any]...
) throws {
try self.init(
layout: layout,
outlet: outlet,
state: state,
constants: merge(constants),
isRoot: true
)
}
private convenience init(
layout: Layout,
outlet: String? = nil,
state: Any = (),
constants: [String: Any] = [:],
isRoot: Bool
) throws {
do {
if let path = layout.templatePath {
throw LayoutError("Cannot initialize \(layout.className) node until content for \(path) has been loaded")
}
let _class: AnyClass = try layout.getClass()
var expressions = layout.expressions
if let body = layout.body {
guard case let bodyExpression?? = _class.bodyExpression else {
throw LayoutError("\(layout.className) does not support inline (X)HTML content")
}
expressions[bodyExpression] = body
}
if let outlet = outlet {
expressions["outlet"] = outlet
}
try self.init(
class: _class,
id: layout.id,
state: state,
constants: constants,
expressions: expressions,
children: layout.children.map {
try LayoutNode(layout: $0, isRoot: false)
}
)
_parameters = layout.parameters
_macros = layout.macros
rootURL = layout.rootURL
guard let xmlPath = layout.xmlPath else {
return
}
var deferredError: Error?
LayoutLoader().loadLayout(
withContentsOfURL: urlFromString(xmlPath, relativeTo: rootURL),
relativeTo: layout.relativePath
) { [weak self] layout, error in
if let layout = layout {
do {
try self?.update(with: layout)
} catch {
deferredError = error
}
} else if let error = error {
deferredError = error
}
}
// TODO: what about errors thrown by deferred load?
if let error = deferredError {
throw error
}
} catch {
throw LayoutError(error, in: layout.className, in: isRoot ? layout.rootURL : nil)
}
}
}
extension Layout {
// Experimental - extracts a layout template from an existing node
// TODO: this isn't a lossless conversion - find a better approach
init(_ node: LayoutNode) {
self.init(
className: nameOfClass(node._class),
id: node.id,
expressions: node._originalExpressions,
parameters: node._parameters,
macros: node._macros,
children: node.children.map(Layout.init(_:)),
body: nil,
xmlPath: nil, // TODO: what if the layout is currently loading this? Race condition!
templatePath: nil,
childrenTagIndex: nil,
relativePath: nil,
rootURL: node.rootURL
)
}
}
| mit | bd629c3f735c2c16396bf8008c71e8cf | 33.125 | 121 | 0.504931 | 5.242245 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/WMFChangePasswordViewController.swift | 3 | 6665 | import WMF
import UIKit
class WMFChangePasswordViewController: WMFScrollViewController, Themeable {
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var subTitleLabel: UILabel!
@IBOutlet fileprivate var passwordField: ThemeableTextField!
@IBOutlet fileprivate var retypeField: ThemeableTextField!
@IBOutlet fileprivate var passwordTitleLabel: UILabel!
@IBOutlet fileprivate var retypeTitleLabel: UILabel!
@IBOutlet fileprivate var saveButton: WMFAuthButton!
fileprivate var theme: Theme = Theme.standard
public var funnel: WMFLoginFunnel?
public var userName:String?
@IBAction fileprivate func saveButtonTapped(withSender sender: UIButton) {
save()
}
@IBAction func textFieldDidChange(_ sender: UITextField) {
guard
let password = passwordField.text,
let retype = retypeField.text
else{
enableProgressiveButton(false)
return
}
enableProgressiveButton((!password.isEmpty && !retype.isEmpty))
}
fileprivate func passwordFieldsMatch() -> Bool {
return passwordField.text == retypeField.text
}
func enableProgressiveButton(_ highlight: Bool) {
saveButton.isEnabled = highlight
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
enableProgressiveButton(false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
passwordField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
enableProgressiveButton(false)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField == passwordField) {
retypeField.becomeFirstResponder()
} else if (textField == retypeField) {
save()
}
return true
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
titleLabel.text = WMFLocalizedString("new-password-title", value:"Set your password", comment:"Title for password change interface")
subTitleLabel.text = WMFLocalizedString("new-password-instructions", value:"You logged in with a temporary password. To finish logging in set a new password here.", comment:"Instructions for password change interface")
passwordField.placeholder = WMFLocalizedString("field-new-password-placeholder", value:"enter new password", comment:"Placeholder text shown inside new password field until user taps on it")
retypeField.placeholder = WMFLocalizedString("field-new-password-confirm-placeholder", value:"re-enter new password", comment:"Placeholder text shown inside confirm new password field until user taps on it")
passwordTitleLabel.text = WMFLocalizedString("field-new-password-title", value:"New password", comment:"Title for new password field")
retypeTitleLabel.text = WMFLocalizedString("field-new-password-confirm-title", value:"Confirm new password", comment:"Title for confirm new password field")
view.wmf_configureSubviewsForDynamicType()
apply(theme: theme)
}
@objc func closeButtonPushed(_ : UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
fileprivate func save() {
guard passwordFieldsMatch() else {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("account-creation-passwords-mismatched", value:"Password fields do not match.", comment:"Alert shown if the user doesn't enter the same password in both password boxes"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
passwordField.text = nil
retypeField.text = nil
passwordField.becomeFirstResponder()
return
}
wmf_hideKeyboard()
enableProgressiveButton(false)
WMFAlertManager.sharedInstance.dismissAlert()
guard let userName = userName,
let password = passwordField.text,
let retypePassword = retypeField.text else {
assertionFailure("One or more of the required parameters are nil")
return
}
WMFAuthenticationManager.sharedInstance.login(username: userName, password: password, retypePassword: retypePassword, oathToken: nil, captchaID: nil, captchaWord: nil) { (loginResult) in
switch loginResult {
case .success(_):
let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName)
WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
self.dismiss(animated: true, completion: nil)
self.funnel?.logSuccess()
case .failure(let error):
self.enableProgressiveButton(true)
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
if let error = error as? URLError {
if error.code != .notConnectedToInternet {
self.passwordField.text = nil
self.retypeField.text = nil
}
}
default:
break
}
}
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
view.tintColor = theme.colors.link
let labels = [titleLabel, subTitleLabel, passwordTitleLabel, retypeTitleLabel]
for label in labels {
label?.textColor = theme.colors.secondaryText
}
let fields = [passwordField, retypeField]
for field in fields {
field?.apply(theme: theme)
}
saveButton.apply(theme: theme)
}
}
| mit | b3fba2d1489555a04e8c982dfe717d07 | 41.724359 | 319 | 0.656864 | 5.74569 | false | false | false | false |
kevinhankens/runalysis | Runalysis/RouteSummary.swift | 1 | 13070 | //
// RouteSummaryView.swift
// Runalysis
//
// Created by Kevin Hankens on 9/3/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
/*!
* Provides a summary of a list of Route objects.
*/
class RouteSummary: NSObject {
// Tracks the route store.
var routeStore: RouteStore?
// Tracks the current route ID.
var routeId: NSNumber = 0
// Tracks a list of route points.
var points: [AnyObject]?
// The lowest velocity, currently 0.
var velocity_low: CLLocationSpeed = Double(0)
var mov_avg_low: CLLocationSpeed = Double(0)
// The highest velocity reached.
var velocity_high: CLLocationSpeed = Double(0)
var mov_avg_high: CLLocationSpeed = Double(0)
// The quantile for each bin.
var velocity_step: CLLocationSpeed = Double(0)
var mov_avg_step: CLLocationSpeed = Double(0)
// The mean velocity over the course.
var velocity_mean: CLLocationSpeed = Double(0)
// The total distance traveled.
var distance_total: CLLocationDistance = Double(0)
// Tracks a distribution of velocities relative to the mean.
var distribution = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var mov_avg_dist = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var animation_length: Int = 0
// Tracks the duration of the run.
var duration: Double = Double(0)
// Tracks the times for each mile run.
var mileTimes: [Double] = []
/*!
* Factory method to create a summary.
*
* @param NSNumber routeId
* @param RouteStore routeStore
*
* @return RouteSummary
*/
class func createRouteSummary(routeId: NSNumber, routeStore: RouteStore)->RouteSummary {
let rsv = RouteSummary()
rsv.routeStore = routeStore
rsv.updateRoute(routeId)
return rsv
}
/*!
* Upstes the summary to a new set of points.
*
* @param NSNumber id
*/
func updateRoute(id: NSNumber) {
if id == self.routeId {
// @todo != creates an error "ambiguous use of !="
}
else {
self.routeId = id
}
// @todo can we skip this if the screen is locked?
self.points = self.routeStore!.getPointsForId(self.routeId)
self.calculateSummary()
}
/*!
* Gets a label for the total mileage with the pace.
*
* @return String
*/
func getTotalAndPace()->String {
return "\(self.totalDistance())\(RunalysisUnits.getUnitLabel()) @\(self.avgVelocityInMinutesPerUnit())"
}
/*!
* Gets the total in miles.
*
* @return String
*/
func totalDistance()->String {
let total = RunalysisUnits.convertMetersToUnits(self.distance_total)
let rounded = round(total * 100)/100
let miles = Int(rounded)
let fraction = Int((rounded - Double(miles)) * 100)
var fraction_string = "\(fraction)"
if fraction < 10 {
fraction_string = "0\(fraction)"
}
return "\(miles).\(fraction_string)"
}
/*!
* Gets a label for the average pace in minutes per mile.
*
* @return String
*/
func avgVelocityInMinutesPerUnit()->String {
let unitsPerMinute = RunalysisUnits.getVelocityPerUnit(self.velocity_mean)/Double(60)
if unitsPerMinute > 0 {
let minutesPerUnit = Double(1)/unitsPerMinute
let minutes = Int(minutesPerUnit)
let seconds = Int(round((minutesPerUnit - Double(minutes)) * 60))
var seconds_string = "\(String(seconds))"
if seconds < Int(10) {
seconds_string = "0\(String(seconds))"
}
return "\(String(minutes)):\(seconds_string)"
}
return "0:00"
}
/*!
* Calculates the averages and totals for the set of points.
*/
func calculateSummary() {
self.velocity_low = Double(0)
self.velocity_high = Double(0)
self.velocity_mean = Double(0)
self.distance_total = Double(0)
self.mov_avg_low = Double(0)
self.mov_avg_high = Double(0)
self.calculateVelocity()
self.calculateDistribution()
//println("Distribution: \(self.distribution)");
//println("Low: \(self.velocity_low)");
//println("High: \(self.velocity_high)");
//println("Mean: \(self.velocity_mean)");
//println("Dist: \(self.distance_total)");
}
/*!
* Calculates the average velocity and the total distance.
*/
func calculateVelocity() {
var count = 0
var total = Double(0)
var started = false
var duration = Double(0)
self.mileTimes.removeAll(keepCapacity: false)
var unitCount = 0
var unitTime = Double(0.0)
var unitTimeTmp = Double(0.0)
var distanceTotal = Double(0.0)
var movingAverage: [Double] = [0, 0, 0, 0, 0]
var movingAverageTotal = Double(0.0)
if self.points?.count > 0 {
var velocityRange = [Double](count: self.points!.count, repeatedValue: 0.0)
// Find outliers.
var i = 0
for p in self.points! {
if let point = p as? Route {
// Track the raw double value to speed up drawing.
point.latitude_raw = point.latitude.doubleValue
point.longitude_raw = point.longitude.doubleValue
point.altitude_raw = point.altitude.doubleValue
// Track the range of velocity points.
point.velocity_raw = point.velocity.doubleValue
velocityRange[i] = point.velocity_raw
}
i++
}
// Determine inner fences.
velocityRange.sort { $0 < $1 }
let q25 = locateQuantile(0.25, values: velocityRange)
let q75 = locateQuantile(0.75, values: velocityRange)
let qr = 1.5 * (q75 - q25)
let bl = q25 - qr
let bu = q75 + qr
var vlow = 0.0
var vhigh = 0.0
var malow = 0.0
var mahigh = 0.0
var movingAveragePos = 0
for p in self.points! {
if let point = p as? Route {
if !started {
// skip the first one as 0 velocity skews the averages.
started = true
continue
}
let testv: AnyObject? = point.valueForKey("velocity")
if let v = testv as? NSNumber {
// Determine the moving average by compiling a list
// of trailing values.
movingAverageTotal -= movingAverage[movingAveragePos]
movingAverageTotal += point.velocity_raw
movingAverage[movingAveragePos] = point.velocity_raw
movingAveragePos++
if movingAveragePos > 4 {
movingAveragePos = 0
}
// Set the new velocity if the moving average array
// has enough values to be significant.
if count > 4 {
point.velocityMovingAvg = movingAverageTotal / Double(movingAverage.count)
}
else {
point.velocityMovingAvg = point.velocity_raw
}
if point.velocity_raw > Double(0.0) {
// Check for outliers.
if point.velocity_raw > bu {
point.velocity = NSNumber(double: bu)
point.velocity_raw = bu
}
if point.velocity_raw < vlow || vlow == Double(0) {
// @todo low is always 0.
vlow = point.velocity_raw
}
else if point.velocity_raw > vhigh {
vhigh = point.velocity_raw
}
if point.velocityMovingAvg < malow || malow == Double(0) {
malow = point.velocityMovingAvg
}
else if point.velocityMovingAvg > mahigh {
mahigh = point.velocityMovingAvg
}
distanceTotal += Double(point.distance)
total += Double(point.velocity)
duration += Double(point.interval)
count++
}
}
// Track the miles.
if Int(RunalysisUnits.convertMetersToUnits(distanceTotal)) > unitCount {
unitCount++
unitTimeTmp = duration - unitTime
unitTime = duration
self.mileTimes.append(unitTimeTmp)
}
}
}
self.distance_total = distanceTotal
self.velocity_low = vlow
self.velocity_high = vhigh
self.mov_avg_low = malow
self.mov_avg_high = mahigh
}
if count > 0 {
self.velocity_mean = total/Double(count)
self.duration = duration
}
}
/*!
* Locates the quantile given an array of sorted values.
*
* @param quantile
* @param values
*
* @return Double
*/
func locateQuantile(quantile: Double, values: [Double])->Double {
let length = values.count
let index = quantile * Double(length-1)
let boundary = Int(index)
let delta = index - Double(boundary)
if length == 0 {
return 0.0
} else if boundary == length-1 {
return values[boundary]
} else {
return (1-delta)*values[boundary] + delta*values[boundary+1]
}
}
/*!
* Calculates the distribution of velocities.
*/
func calculateDistribution() {
var rel = 0
// For some reason trying to adjust self.distribution is very expensive. So do it in a local var and update once at the end.
var tmp = [0,0,0,0,0,0,0,0,0]
var tmp_mov = [0,0,0,0,0,0,0,0,0]
let velocityDiff = self.velocity_high - self.velocity_low
self.velocity_step = velocityDiff/Double(tmp.count)
let velocityDiffMov = self.mov_avg_high - self.mov_avg_low
self.mov_avg_step = velocityDiffMov/Double(tmp_mov.count)
if self.points?.count > 0 {
for p: AnyObject in self.points! {
if let point = p as? Route {
// This is a little overkill, but the simulator occasionally
// fails leaving an invalid point in the db due to a null value
// for the velocity column. Strange because it's got a default
// value of 0. This is the only way I've found to prevent crashing.
let testv: AnyObject? = point.valueForKey("velocity")
if let v = testv as? NSNumber {
rel = self.getRelativeVelocity(point.velocity_raw, low: self.velocity_low, step: self.velocity_step)
point.relativeVelocity = rel
tmp[rel]++
rel = self.getRelativeVelocity(point.velocityMovingAvg, low: self.velocity_low, step: self.velocity_step)
point.relVelMovingAvg = rel
tmp_mov[rel]++
}
}
}
}
var i = 0
for i = 0; i < tmp.count; i++ {
self.distribution[i] = tmp[i]
self.mov_avg_dist[i] = tmp_mov[i]
}
}
/*!
* Gets the relative velocity of a point compared to the high, low and average.
*
* @return NSNumber
*/
func getRelativeVelocity(velocity: Double, low: CLLocationSpeed, step: CLLocationSpeed)->Int {
var rel = 0
for var i = 0; i < self.distribution.count; i++ {
if velocity < low + (step * Double((i + 1))) {
rel = i
break
}
}
return rel
}
}
| mit | 16d11aa163930ce2b4edaf7add06227f | 33.760638 | 132 | 0.493573 | 4.757918 | false | false | false | false |
JohnPJenkins/swift-t | stc/tests/691-file-copy.swift | 4 | 589 | import files;
import assert;
main () {
file a<"691-tmp.txt"> = write("contents.");
// Check we can copy to mapped and unmapped files
file b = a;
assertEqual(read(b), "contents.", "b");
file c<"691-tmp2.txt">;
// unmapped to mapped
c = copy_wrapper(a);
// unmapped to unmapped
file d = copy_wrapper(b);
assertEqual(read(d), "contents.", "d");
// mapped to mapped
file e<"691-tmp3.txt"> = c;
assertEqual(read(e), "contents.", "e");
}
(file o) copy_wrapper (file i) {
// Don't know mapping status of these files
o = i;
}
| apache-2.0 | a6ca37d2d85803d2154e52d91d0c03de | 20.035714 | 53 | 0.573854 | 3.346591 | false | false | false | false |
bixubot/AcquainTest | ChatRoom/ChatRoom/AvatarTableViewCell.swift | 1 | 2438 | //
// AvatarTableViewCell.swift
// ChatRoom
//
// Created by Mutian on 4/21/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class AvatarTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var chatIDLabel: UILabel!
// fetch User object from NewMessageController and pass to chatlogcontroller
var user: User?
func fetchUserAndSetupNavBarTitle() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
// for some reason uid = nil
return
}
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
self.user?.setValuesForKeys(dictionary)
}
}, withCancel: nil)
}
/**
Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
@param None
@return None
*/
override func awakeFromNib() {
super.awakeFromNib()
self.accessoryType = .disclosureIndicator
self.avatarImageView.layer.masksToBounds = true
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.size.width/2/180 * 30
self.avatarImageView.layer.borderWidth = 0.5
self.avatarImageView.layer.borderColor = UIColor.lightGray.cgColor
self.avatarImageView.translatesAutoresizingMaskIntoConstraints = false
self.nicknameLabel.translatesAutoresizingMaskIntoConstraints = false
self.chatIDLabel.translatesAutoresizingMaskIntoConstraints = false
// fetchUserAndSetupNavBarTitle()
//
// if let profileImageUrl = self.user?.profileImageUrl {
// self.avatarImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
// }
// self.nicknameLabel.text = user?.name
// self.chatIDLabel.text = user?.email
}
/**
Configure the view for the selected state
@param None
@return None
*/
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 91487cc218e4003f110320b6f32e1ded | 31.932432 | 121 | 0.645055 | 5.109015 | false | false | false | false |
jarrroo/MarkupKitLint | Tools/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift | 33 | 2634 | import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith<S: Sequence, T: Equatable>(_ startingElement: T) -> Predicate<S>
where S.Iterator.Element == T {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return PredicateStatus(bool: actualGenerator.next() == startingElement)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual collection's first element
/// is equal to the expected object.
public func beginWith(_ startingElement: Any) -> Predicate<NMBOrderedCollection> {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
guard let collection = try actualExpression.evaluate() else { return .fail }
guard collection.count > 0 else { return .doesNotMatch }
#if os(Linux)
guard let collectionValue = collection.object(at: 0) as? NSObject else {
return .fail
}
#else
let collectionValue = collection.object(at: 0) as AnyObject
#endif
return PredicateStatus(bool: collectionValue.isEqual(startingElement))
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(_ startingSubstring: String) -> Predicate<String> {
return Predicate.simple("begin with <\(startingSubstring)>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let range = actual.range(of: startingSubstring)
return PredicateStatus(bool: range != nil && range!.lowerBound == actual.startIndex)
}
return .fail
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beginWithMatcher(_ expected: Any) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = try! actualExpression.evaluate()
if (actual as? String) != nil {
let expr = actualExpression.cast { $0 as? String }
return try! beginWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try! beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
#endif
| mit | a97689319057e53c7b1e48e91962efc2 | 42.9 | 104 | 0.66287 | 4.951128 | false | false | false | false |
Hodglim/hacking-with-swift | Project-14/WhackAPenguin/GameViewController.swift | 1 | 1272 | //
// GameViewController.swift
// WhackAPenguin
//
// Created by Darren Hodges on 27/10/2015.
// Copyright (c) 2015 Darren Hodges. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene")
{
// Configure the view.
let skView = self.view as! SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool
{
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask
{
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
return .AllButUpsideDown
}
else
{
return .All
}
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
}
| mit | ab8a1f35a192361b5f890554c5283135 | 21.714286 | 94 | 0.591981 | 5.213115 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | GeekSpeak Show Timer/BreakCount-3/Timer+StatePreservation.swift | 2 | 5177 | import UIKit
extension Timer: NSCoding {
// MARK: -
// MARK: State Preservation and Restoration
convenience init?(coder aDecoder: NSCoder) {
self.init()
decodeWithCoder(coder: aDecoder)
}
func decodeWithCoder(coder aDecoder: NSCoder) {
let decodedObject = aDecoder.decodeObject(forKey: Constants.UUIDId) as! UUID
uuid = decodedObject
demoTimings = aDecoder.decodeBool(forKey: Constants.DemoId)
let countingState = aDecoder.decodeCInt(forKey: Constants.StateId)
switch countingState {
case 1:
_state = .Ready
case 2:
_state = .Counting
case 3:
_state = .Paused
default:
_state = .Ready
}
let countingStartTimeDecoded =
aDecoder.decodeDouble(forKey: Constants.CountingStartTimeId)
if countingStartTimeDecoded == DBL_MAX {
countingStartTime = .none
} else {
countingStartTime = countingStartTimeDecoded
}
timing = ShowTiming()
let int = aDecoder.decodeCInt(forKey: Constants.PhaseId)
let phase: ShowPhase
switch int {
case 1: phase = .PreShow
case 2: phase = .Section1
case 3: phase = .Break1
case 4: phase = .Section2
case 5: phase = .Break2
case 6: phase = .Section3
case 7: phase = .PostShow
default: phase = .PreShow
}
timing.phase = phase
timing.durations.preShow =
aDecoder.decodeDouble(forKey: Constants.Durations.PreShowId)
timing.durations.section1 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section1Id)
timing.durations.section2 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section2Id)
timing.durations.section3 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section3Id)
timing.durations.break1 =
aDecoder.decodeDouble(forKey: Constants.Durations.Break1Id)
timing.durations.break2 =
aDecoder.decodeDouble(forKey: Constants.Durations.Break2Id)
timing.timeElapsed.preShow =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.PreShowId)
timing.timeElapsed.section1 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section1Id)
timing.timeElapsed.section2 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section2Id)
timing.timeElapsed.section3 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section3Id)
timing.timeElapsed.break1 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Break1Id)
timing.timeElapsed.break2 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Break2Id)
timing.timeElapsed.postShow =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.PostShowId)
incrementTimer()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(uuid, forKey: Constants.UUIDId)
aCoder.encode(demoTimings, forKey: Constants.DemoId)
switch _state {
case .Ready:
aCoder.encodeCInt(1, forKey: Constants.StateId)
case .Counting:
aCoder.encodeCInt(2, forKey: Constants.StateId)
case .Paused:
aCoder.encodeCInt(3, forKey: Constants.StateId)
case .PausedAfterComplete:
aCoder.encodeCInt(4, forKey: Constants.StateId)
case .CountingAfterComplete:
aCoder.encodeCInt(5, forKey: Constants.StateId)
}
if let countingStartTime = countingStartTime {
aCoder.encode( countingStartTime,
forKey: Constants.CountingStartTimeId)
} else {
aCoder.encode( DBL_MAX,
forKey: Constants.CountingStartTimeId)
}
aCoder.encode(demoTimings, forKey: Constants.UseDemoDurations)
let int: Int32
switch timing.phase {
case .PreShow: int = 1
case .Section1: int = 2
case .Break1: int = 3
case .Section2: int = 4
case .Break2: int = 5
case .Section3: int = 6
case .PostShow: int = 7
}
aCoder.encodeCInt(int, forKey: Constants.PhaseId)
let d = timing.durations
aCoder.encode(d.preShow, forKey: Constants.Durations.PreShowId)
aCoder.encode(d.section1, forKey: Constants.Durations.Section1Id)
aCoder.encode(d.break1, forKey: Constants.Durations.Break1Id)
aCoder.encode(d.section2, forKey: Constants.Durations.Section2Id)
aCoder.encode(d.break2, forKey: Constants.Durations.Break2Id)
aCoder.encode(d.section3, forKey: Constants.Durations.Section3Id)
let t = timing.timeElapsed
aCoder.encode(t.preShow, forKey: Constants.ElapsedTime.PreShowId)
aCoder.encode(t.section1, forKey: Constants.ElapsedTime.Section1Id)
aCoder.encode(t.break1, forKey: Constants.ElapsedTime.Break1Id)
aCoder.encode(t.section2, forKey: Constants.ElapsedTime.Section2Id)
aCoder.encode(t.break2, forKey: Constants.ElapsedTime.Break2Id)
aCoder.encode(t.section3, forKey: Constants.ElapsedTime.Section3Id)
aCoder.encode(t.postShow, forKey: Constants.ElapsedTime.PostShowId)
}
}
| mit | 86513f4c6ed9c6125997c3e9c5ba3e98 | 31.35625 | 82 | 0.662353 | 4.267931 | false | false | false | false |
CalvinChina/Demo | Swift3Demo/Swift3Demo/AnimationWithCollisionQuartzCore/CollisionQuartzCoreViewController.swift | 1 | 3741 | //
// CollisionQuartzCoreViewController.swift
// Swift3Demo
//
// Created by pisen on 16/9/19.
// Copyright © 2016年 丁文凯. All rights reserved.
//
import UIKit
class CollisionQuartzCoreViewController: UIViewController,UICollisionBehaviorDelegate {
@IBOutlet weak var gravity: UIButton!
@IBOutlet weak var push: UIButton!
@IBOutlet weak var attachment: UIButton!
var collision:UICollisionBehavior!
var animator = UIDynamicAnimator()
var attachmentBehavior: UIAttachmentBehavior? = nil
@IBAction func gravityClick(_ sender :UIButton){
animator.removeAllBehaviors()
let gravity_t = UIGravityBehavior(items:[self.gravity,self.push,self.attachment])
animator.addBehavior(gravity_t)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func push(_ sender:AnyObject){
animator.removeAllBehaviors()
let push_t = UIPushBehavior(items:[self.gravity,self.push,self.attachment], mode:.instantaneous)
push_t.magnitude = 2
animator.addBehavior(push_t)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func attachment(_ sender:AnyObject){
animator.removeAllBehaviors()
let anchorPoint = CGPoint(x:self.attachment.center.x ,y:self.attachment.center.y)
attachmentBehavior = UIAttachmentBehavior(item:self.attachment ,attachedToAnchor:anchorPoint)
attachmentBehavior!.frequency = 0.5
attachmentBehavior!.damping = 2
attachmentBehavior!.length = 20
animator.addBehavior(attachmentBehavior!)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func handleAttachment(_ sender: UIPanGestureRecognizer) {
if((attachmentBehavior) != nil){
attachmentBehavior!.anchorPoint = sender.location(in: self.view)
}
}
override func viewDidLoad() {
super.viewDidLoad()
animator = UIDynamicAnimator(referenceView: self.view)
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let max: CGRect = UIScreen.main.bounds
let snap1 = UISnapBehavior(item: self.gravity, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 - 50))
let snap2 = UISnapBehavior(item: self.push, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 ))
let snap3 = UISnapBehavior(item: self.attachment, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 + 50))
snap1.damping = 1
snap2.damping = 2
snap3.damping = 4
animator.addBehavior(snap1)
animator.addBehavior(snap2)
animator.addBehavior(snap3)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6b6721fb10d20a6d6ab0bfcc32afc042 | 34.542857 | 122 | 0.678725 | 4.676692 | false | false | false | false |
modocache/FutureKit | FutureKit/Synchronization.swift | 3 | 22522 | //
// NSData-Ext.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// this adds some missing feature that we don't have with normal dispatch_queue_t
// like .. what DispatchQueue am I currently running in?
// Add assertions to make sure logic is always running on a specific Queue
// Don't know what sort of synchronization is perfect?
// try them all!
// testing different strategys may result in different performances (depending on your implementations)
public protocol SynchronizationProtocol {
init()
// modify your object. The block() code may run asynchronously, but doesn't return any result
func modify(block:() -> Void)
// modify your shared object and return some value in the process
// the "done" block could execute inside ANY thread/queue so care should be taken.
// will try NOT to block the current thread (for Barrier/Queue strategies)
// Lock strategies may still end up blocking the calling thread.
func modifyAsync<_ANewType>(block:() -> _ANewType, done : (_ANewType) -> Void)
// modify your container and retrieve a result/element to the same calling thread
// current thread will block until the modifyBlock is done running.
func modifySync<_ANewType>(block:() -> _ANewType) -> _ANewType
// read your object. The block() code may run asynchronously, but doesn't return any result
// if you need to read the block and return a result, use readAsync/readSync
func read(block:() -> Void)
// perform a readonly query of your shared object and return some value/element T
// current thread may block until the read block is done running.
// do NOT modify your object inside this block
func readSync<_ANewType>(block:() -> _ANewType) -> _ANewType
// perform a readonly query of your object and return some value/element of type _ANewType.
// the results are delivered async inside the done() block.
// the done block is NOT protected by the synchronization - do not modify your shared data inside the "done:" block
// the done block could execute inside ANY thread/queue so care should be taken
// do NOT modify your object inside this block
func readAsync<_ANewType>(block:() -> _ANewType, done : (_ANewType) -> Void)
}
public enum SynchronizationType {
case BarrierConcurrent
case BarrierSerial
case SerialQueue
case NSObjectLock
case NSLock
case NSRecursiveLock
case OSSpinLock
func lockObject() -> SynchronizationProtocol {
switch self {
case BarrierConcurrent:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_CONCURRENT)
case BarrierSerial:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_SERIAL)
case SerialQueue:
return QueueSerialSynchronization()
case NSObjectLock:
return NSObjectLockSynchronization()
case NSLock:
return NSLockSynchronization()
case NSRecursiveLock:
return NSRecursiveLockSynchronization()
case OSSpinLock:
return OSSpinLockSynchronization()
}
}
}
let DispatchQueuePoolIsActive = false
class DispatchQueuePool {
let attr : dispatch_queue_attr_t
let qos : qos_class_t
let relative_priority : Int32
let syncObject : SynchronizationProtocol
var queues : [dispatch_queue_t] = []
init(a : dispatch_queue_attr_t, qos q: qos_class_t = QOS_CLASS_DEFAULT, relative_priority p :Int32 = 0) {
self.attr = a
self.qos = q
self.relative_priority = p
let c_attr = dispatch_queue_attr_make_with_qos_class(self.attr,self.qos, self.relative_priority)
let synchObjectBarrierQueue = dispatch_queue_create("DispatchQueuePool-Root", c_attr)
self.syncObject = QueueBarrierSynchronization(queue: synchObjectBarrierQueue)
}
final func createNewQueue() -> dispatch_queue_t {
let c_attr = dispatch_queue_attr_make_with_qos_class(self.attr,self.qos, self.relative_priority)
return dispatch_queue_create(nil, c_attr)
}
func getQueue() -> dispatch_queue_t {
if (DispatchQueuePoolIsActive) {
let queue = self.syncObject.modifySync { () -> dispatch_queue_t? in
if let q = self.queues.last {
self.queues.removeLast()
return q
}
else {
return nil
}
}
if let q = queue {
return q
}
}
return self.createNewQueue()
}
func recycleQueue(q: dispatch_queue_t) {
if (DispatchQueuePoolIsActive) {
self.syncObject.modify { () -> Void in
self.queues.append(q)
}
}
}
func flushQueue(keepCapacity : Bool = false) {
self.syncObject.modify { () -> Void in
self.queues.removeAll(keepCapacity: keepCapacity)
}
}
}
/* public var serialQueueDispatchPool = DispatchQueuePool(a: DISPATCH_QUEUE_SERIAL, qos: QOS_CLASS_DEFAULT, relative_priority: 0)
public var concurrentQueueDispatchPool = DispatchQueuePool(a: DISPATCH_QUEUE_CONCURRENT, qos: QOS_CLASS_DEFAULT, relative_priority: 0)
public var defaultBarrierDispatchPool = concurrentQueueDispatchPool */
public class QueueBarrierSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
let c_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_CONCURRENT,QOS_CLASS_DEFAULT, 0)
self.q = dispatch_queue_create("QueueBarrierSynchronization", c_attr)
}
init(type : dispatch_queue_attr_t, _ q: qos_class_t = QOS_CLASS_DEFAULT, _ p :Int32 = 0) {
let c_attr = dispatch_queue_attr_make_with_qos_class(type,q, p)
self.q = dispatch_queue_create("QueueBarrierSynchronization", c_attr)
}
public func read(block:() -> Void) {
dispatch_async(self.q,block)
}
public func readSync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modify(block:() -> Void) {
dispatch_barrier_async(self.q,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_barrier_async(self.q) {
done(block())
}
}
public func modifySync<T>(block:() -> T) -> T {
var ret : T?
dispatch_barrier_sync(self.q) {
ret = block()
}
return ret!
}
}
public class QueueSerialSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
let c_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,QOS_CLASS_DEFAULT, 0)
self.q = dispatch_queue_create("QueueSynchronization", c_attr)
}
public func read(block:() -> Void) {
dispatch_async(self.q,block)
}
public func readSync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modify(block:() -> Void) {
dispatch_async(self.q,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modifySync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
}
class NSObjectLockSynchronization : SynchronizationProtocol {
var lock : AnyObject
required init() {
self.lock = NSObject()
}
init(lock l: AnyObject) {
self.lock = l
}
func synchronized<T>(block:() -> T) -> T {
return SYNCHRONIZED(self.lock) { () -> T in
return block()
}
}
func read(block:() -> Void) {
self.synchronized(block)
}
func readSync<T>(block:() -> T) -> T {
return self.synchronized(block)
}
func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = self.synchronized(block)
done(ret)
}
func modify(block:() -> Void) {
self.synchronized(block)
}
func modifySync<T>(block:() -> T) -> T {
return self.synchronized(block)
}
func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = self.synchronized(block)
done(ret)
}
}
func synchronizedWithLock<T>(l: NSLocking, @noescape closure: ()->T) -> T {
l.lock()
let retVal: T = closure()
l.unlock()
return retVal
}
public class NSLockSynchronization : SynchronizationProtocol {
var lock = NSLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
}
func synchronizedWithSpinLock<T>(l: UnSafeMutableContainer<OSSpinLock>, @noescape closure: ()->T) -> T {
OSSpinLockLock(l.unsafe_pointer)
let retVal: T = closure()
OSSpinLockUnlock(l.unsafe_pointer)
return retVal
}
public class OSSpinLockSynchronization : SynchronizationProtocol {
var lock = UnSafeMutableContainer<OSSpinLock>(OS_SPINLOCK_INIT)
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithSpinLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithSpinLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithSpinLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithSpinLock(lock,block)
done(ret)
}
}
public class NSRecursiveLockSynchronization : SynchronizationProtocol {
var lock = NSRecursiveLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
}
// wraps your synch strategy into a Future
// increases 'composability'
// warning: Future has it's own lockObject (usually NSLock)
public class SynchronizationObject<P : SynchronizationProtocol> {
let sync : P
let defaultExecutor : Executor // used to execute 'done' blocks for async lookups
public init() {
self.sync = P()
self.defaultExecutor = Executor.Immediate
}
public init(_ p : P) {
self.sync = p
self.defaultExecutor = Executor.Immediate
}
public init(_ p : P, _ executor : Executor) {
self.sync = p
self.defaultExecutor = executor
}
public func read(block:() -> Void) {
self.sync.read(block)
}
public func readSync<T>(block:() -> T) -> T {
return self.sync.readSync(block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
return self.sync.readAsync(block,done: done)
}
public func modify(block:() -> Void) {
self.sync.modify(block)
}
public func modifySync<T>(block:() -> T) -> T {
return self.sync.modifySync(block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
return self.sync.modifyAsync(block,done: done)
}
public func modifyFuture<T>(block:() -> T) -> Future<T> {
return self.modifyFuture(self.defaultExecutor,block: block)
}
public func readFuture<T>(block:() -> T) -> Future<T> {
return self.readFuture(self.defaultExecutor,block: block)
}
public func readFuture<T>(executor : Executor, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.sync.readAsync({ () -> T in
return block()
}, done: { (result) -> Void in
p.completeWithSuccess(result)
})
return p.future
}
public func modifyFuture<T>(executor : Executor, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.sync.modifyAsync({ () -> T in
return block()
}, done: { (t) -> Void in
p.completeWithSuccess(t)
})
return p.future
}
}
class CollectionAccessControl<C : MutableCollectionType, S: SynchronizationProtocol> {
typealias Index = C.Index
typealias Element = C.Generator.Element
var syncObject : SynchronizationObject<S>
var collection : C
init(c : C, _ s: SynchronizationObject<S>) {
self.collection = c
self.syncObject = s
}
func getValue(key : Index) -> Future<Element> {
return self.syncObject.readFuture { () -> Element in
return self.collection[key]
}
}
/* subscript (key: Index) -> Element {
get {
return self.syncObject.readSync { () -> Element in
return self.collection[key]
}
}
set(newValue) {
self.syncObject.modifySync {
self.collection[key] = newValue
}
}
} */
}
class DictionaryWithSynchronization<Key : Hashable, Value, S: SynchronizationProtocol> {
typealias Index = Key
typealias Element = Value
typealias DictionaryType = Dictionary<Key,Value>
var syncObject : SynchronizationObject<S>
var dictionary : DictionaryType
init() {
self.dictionary = DictionaryType()
self.syncObject = SynchronizationObject<S>()
}
init(_ d : DictionaryType, _ s: SynchronizationObject<S>) {
self.dictionary = d
self.syncObject = s
}
init(_ s: SynchronizationObject<S>) {
self.dictionary = DictionaryType()
self.syncObject = s
}
func getValue(key : Key) -> Future<Value?> {
return self.syncObject.readFuture { () -> Value? in
return self.dictionary[key]
}
}
var count: Int {
get {
return self.syncObject.readSync { () -> Int in
return self.dictionary.count
}
}
}
var isEmpty: Bool {
get {
return self.syncObject.readSync { () -> Bool in
return self.dictionary.isEmpty
}
}
}
/* subscript (key: Key) -> Value? {
get {
return self.syncObject.readSync { () -> Element? in
return self.dictionary[key]
}
}
set(newValue) {
self.syncObject.modifySync {
self.dictionary[key] = newValue
}
}
} */
}
class ArrayAccessControl<T, S: SynchronizationProtocol> : CollectionAccessControl< Array<T> , S> {
var array : Array<T> {
get {
return self.collection
}
}
init() {
super.init(c: Array<T>(), SynchronizationObject<S>())
}
init(array : Array<T>, _ a: SynchronizationObject<S>) {
super.init(c: array, a)
}
init(a: SynchronizationObject<S>) {
super.init(c: Array<T>(), a)
}
var count: Int {
get {
return self.syncObject.readSync { () -> Int in
return self.collection.count
}
}
}
var isEmpty: Bool {
get {
return self.syncObject.readSync { () -> Bool in
return self.collection.isEmpty
}
}
}
var first: T? {
get {
return self.syncObject.readSync { () -> T? in
return self.collection.first
}
}
}
var last: T? {
get {
return self.syncObject.readSync { () -> T? in
return self.collection.last
}
}
}
/* subscript (future index: Int) -> Future<T> {
return self.syncObject.readFuture { () -> T in
return self.collection[index]
}
} */
func getValue(atIndex i: Int) -> Future<T> {
return self.syncObject.readFuture { () -> T in
return self.collection[i]
}
}
func append(newElement: T) {
self.syncObject.modify {
self.collection.append(newElement)
}
}
func removeLast() -> T {
return self.syncObject.modifySync {
self.collection.removeLast()
}
}
func insert(newElement: T, atIndex i: Int) {
self.syncObject.modify {
self.collection.insert(newElement,atIndex: i)
}
}
func removeAtIndex(index: Int) -> T {
return self.syncObject.modifySync {
self.collection.removeAtIndex(index)
}
}
}
class DictionaryWithLockAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,NSObjectLockSynchronization> {
typealias LockObjectType = SynchronizationObject<NSObjectLockSynchronization>
override init() {
super.init(LockObjectType(NSObjectLockSynchronization()))
}
init(d : Dictionary<Key,Value>) {
super.init(d,LockObjectType(NSObjectLockSynchronization()))
}
}
class DictionaryWithBarrierAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,QueueBarrierSynchronization> {
typealias LockObjectType = SynchronizationObject<QueueBarrierSynchronization>
init(queue : dispatch_queue_t) {
super.init(LockObjectType(QueueBarrierSynchronization(queue: queue)))
}
init(d : Dictionary<Key,Value>,queue : dispatch_queue_t) {
super.init(d,LockObjectType(QueueBarrierSynchronization(queue: queue)))
}
}
/* func dispatch_queue_create_compatibleIOS8(label : String,
attr : dispatch_queue_attr_t,
qos_class : dispatch_qos_class_t,relative_priority : Int32) -> dispatch_queue_t
{
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority)
let queue = dispatch_queue_create(label, c_attr)
return queue;
} */
/* class DispatchQueue: NSObject {
enum QueueType {
case Serial
case Concurrent
}
enum QueueClass {
case Main
case UserInteractive // QOS_CLASS_USER_INTERACTIVE
case UserInitiated // QOS_CLASS_USER_INITIATED
case Default // QOS_CLASS_DEFAULT
case Utility // QOS_CLASS_UTILITY
case Background // QOS_CLASS_BACKGROUND
}
var q : dispatch_queue_t
var type : QueueType
init(name : String, type : QueueType, relative_priority : Int32) {
var attr = (type == .Concurrent) ? DISPATCH_QUEUE_CONCURRENT : DISPATCH_QUEUE_SERIAL
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority);
dispatch_queue_t queue = dispatch_queue_create(label, c_attr);
return queue;
}
} */
| mit | 8873e0fbd74d3a924e08d6b0811b78b8 | 27.32956 | 134 | 0.58818 | 4.226309 | false | false | false | false |
yajeka/PS | PS/BackendManager.swift | 1 | 2854 | //
// BackendManager.swift
// PS
//
// Created by Andrey Koyro on 20/03/2016.
// Copyright © 2016 hackathon. All rights reserved.
//
import Foundation
import Parse
public typealias BackedBlock = (success: PFObject?, error: String?) -> Void
public class BackendManager {
private class func handleResult(result: AnyObject? , error: NSError?, block: BackedBlock?, className: String) {
if result is String {
block!(success: nil, error: result as? String)
} else if error != nil {
block!(success: nil, error: error?.localizedDescription)
} else if let input = result as? NSDictionary {
let query = PFQuery(className: className);
let objectId = input["objectId"] as! String
let task = query.getObjectInBackgroundWithId(objectId)
task.waitUntilFinished()
let object:PFObject = task.result as! PFObject
block!(success: object, error: nil)
}
}
public class func signUp(uid: String, email: String, password: String, block: BackedBlock?) {
findByEmailAndPassword(email, password: password, block: { (success: PFObject?, error: String?) -> Void in
if ((error) != nil) {
let account = PFObject(className: "Account")
account["uids"] = [uid]
account["email"] = email
account["password"] = password
let task = account.saveInBackground()
task.waitUntilFinished()
block!(success: account, error: nil)
} else {
block!(success: nil, error: "account_exists")
}
})
}
public class func findByEmailAndPassword(email: String, password: String, block: BackedBlock?) {
PFCloud.callFunctionInBackground("findByEmailAndPassword", withParameters: ["email": email, "password": password], block: {(result: AnyObject? , error: NSError?) -> Void in
handleResult(result,error: error, block: block, className: "Account")
});
}
public class func findByUid(uid: String, block: BackedBlock?) {
PFCloud.callFunctionInBackground("findByUid", withParameters: ["uid": uid], block: {(result: AnyObject? , error: NSError?) -> Void in
handleResult(result,error: error, block: block, className: "Account")
});
}
public class func findByEmailAndPassword(email: String, password: String) -> BFTask {
return PFCloud.callFunctionInBackground("findByEmailAndPassword", withParameters: ["email": email, "password": password]);
}
private class func findByUid(uid: String) -> BFTask {
return PFCloud.callFunctionInBackground("findByUid", withParameters: ["uid": uid]);
}
}
| lgpl-3.0 | 314437cfd30385099d09342318c758c4 | 38.082192 | 180 | 0.604276 | 4.72351 | false | false | false | false |
EZ-NET/ESOcean | ESOcean/DateTime/Time.swift | 1 | 3114 | //
// Time.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/06/19.
//
//
import Darwin.C
extension timespec : Equatable {
public init(_ value:timeval) {
self.tv_sec = value.tv_sec
self.tv_nsec = Int(value.tv_usec) * Time.nanosecondPerMicrosecond
}
}
extension timeval : Equatable {
public init(_ spec:timespec) {
self.tv_sec = spec.tv_sec
self.tv_usec = Int32(spec.tv_nsec / Time.nanosecondPerMicrosecond)
}
}
public func == (lhs:timespec, rhs:timespec) -> Bool {
return lhs.tv_sec == rhs.tv_sec && lhs.tv_nsec == rhs.tv_nsec
}
public func == (lhs:timeval, rhs:timeval) -> Bool {
return lhs.tv_sec == rhs.tv_sec && lhs.tv_usec == rhs.tv_usec
}
public struct Time {
var _timespec:timespec
/// Get an instance means Today.
public init?() {
var value = timeval()
guard gettimeofday(&value, nil) == 0 else {
return nil
}
self._timespec = timespec(value)
}
public init(_ spec:timespec) {
self._timespec = spec
}
public init(_ value:timeval) {
self.init(timespec(value))
}
/// Get time by nanoseconds.
public var nanoseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.nanosecondPerSecond.toIntMax() + self._timespec.tv_nsec.toIntMax()
}
public var microseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.microsecondPerSecond.toIntMax() + IntMax(self._timespec.tv_nsec / Time.nanosecondPerMicrosecond)
}
public var milliseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.millisecondPerSecond.toIntMax() + IntMax(self._timespec.tv_nsec / Time.nanosecondPerMillisecond)
}
public var seconds:Int64 {
return Int64(self._timespec.tv_sec) + Int64(self._timespec.tv_nsec / Time.nanosecondPerSecond)
}
/// Get time as Unix time.
public var time:Int {
return self._timespec.tv_sec
}
public var gmtTime:Int {
var time = self.time
return mktime(gmtime(&time))
}
public var localTime:Int {
var time = self.time
return mktime(localtime(&time))
}
public var localTimeString:String {
var _time = time
let _characters = ctime(&_time)
return String.fromCString(_characters)!.replace("\n", "")
}
}
extension Time : CustomStringConvertible {
public var description:String {
return self.localTimeString
}
}
extension Time : Comparable {
}
public func == (lhs:Time, rhs:Time) -> Bool {
return lhs._timespec == rhs._timespec
}
public func < (lhs:Time, rhs:Time) -> Bool {
return lhs.nanoseconds < rhs.nanoseconds
}
// MARK: Constants
extension Time {
/// Get milliseconds per a second.
public static let millisecondPerSecond = 1000;
/// Get microseconds per a second.
public static let microsecondPerSecond = 1000000;
/// Get nanoseconds per a second.
public static let nanosecondPerSecond = 1000000000;
/// Get microseconds per a millisecond.
public static let microsecondPerMillisecond = 1000
/// Get nanoseconds per a millisecond.
public static let nanosecondPerMillisecond = 1000000
/// Get nanoseconds per a microsecond.
public static let nanosecondPerMicrosecond = 1000
} | mit | b78b855f500f632fe7ff7cbbbd82164f | 18.71519 | 145 | 0.68754 | 3.395856 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/LoadingButton.swift | 1 | 3574 | import Library
import Prelude
import UIKit
final class LoadingButton: UIButton {
// MARK: - Properties
private let viewModel: LoadingButtonViewModelType = LoadingButtonViewModel()
private lazy var activityIndicator: UIActivityIndicatorView = {
UIActivityIndicatorView(style: .medium)
|> \.hidesWhenStopped .~ true
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
public var activityIndicatorStyle: UIActivityIndicatorView.Style = .medium {
didSet {
self.activityIndicator.style = self.activityIndicatorStyle
}
}
public var isLoading: Bool = false {
didSet {
self.viewModel.inputs.isLoading(self.isLoading)
}
}
private var originalTitles: [UInt: String] = [:]
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureViews()
self.bindViewModel()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.configureViews()
self.bindViewModel()
}
override func setTitle(_ title: String?, for state: UIControl.State) {
// Do not allow changing the title while the activity indicator is animating
guard !self.activityIndicator.isAnimating else {
self.originalTitles[state.rawValue] = title
return
}
super.setTitle(title, for: state)
}
// MARK: - Configuration
private func configureViews() {
self.addSubview(self.activityIndicator)
self.activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
// MARK: - View model
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.isUserInteractionEnabled
.observeForUI()
.observeValues { [weak self] isUserInteractionEnabled in
_ = self
?|> \.isUserInteractionEnabled .~ isUserInteractionEnabled
}
self.viewModel.outputs.startLoading
.observeForUI()
.observeValues { [weak self] in
self?.startLoading()
}
self.viewModel.outputs.stopLoading
.observeForUI()
.observeValues { [weak self] in
self?.stopLoading()
}
}
// MARK: - Loading
private func startLoading() {
self.removeTitle()
self.activityIndicator.startAnimating()
}
private func stopLoading() {
self.activityIndicator.stopAnimating()
self.restoreTitle()
}
// MARK: - Titles
private func removeTitle() {
let states: [UIControl.State] = [.disabled, .highlighted, .normal, .selected]
states.compactMap { state -> (String, UIControl.State)? in
guard let title = self.title(for: state) else { return nil }
return (title, state)
}
.forEach { title, state in
self.originalTitles[state.rawValue] = title
self.setTitle(nil, for: state)
}
_ = self
|> \.accessibilityLabel %~ { _ in Strings.Loading() }
UIAccessibility.post(notification: .layoutChanged, argument: self)
}
private func restoreTitle() {
let states: [UIControl.State] = [.disabled, .highlighted, .normal, .selected]
states.compactMap { state -> (String, UIControl.State)? in
guard let title = self.originalTitles[state.rawValue] else { return nil }
return (title, state)
}
.forEach { title, state in
self.originalTitles[state.rawValue] = nil
self.setTitle(title, for: state)
}
_ = self
|> \.accessibilityLabel .~ nil
UIAccessibility.post(notification: .layoutChanged, argument: self)
}
}
| apache-2.0 | 64b765d6a0c218dfb1646fcc818dbc69 | 24.528571 | 96 | 0.674314 | 4.653646 | false | false | false | false |
Onion-Shen/ONSCalendar | src/CalendarItem.swift | 1 | 819 | import UIKit
class CalendarItem : UIView
{
var year : Int = 0
var month : Int = 0
var day : Int = 0
var contentLabel : UILabel = UILabel()
override init(frame: CGRect)
{
super.init(frame: frame)
self.backgroundColor = UIColor.white
self.layer.borderColor = UIColor.black.cgColor
self.layer.borderWidth = 0.25
self.contentLabel.textAlignment = .center
self.addSubview(self.contentLabel)
}
override func layoutSubviews()
{
super.layoutSubviews()
self.contentLabel.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 80ce59ce196ef24e78005640c0716e70 | 23.818182 | 114 | 0.600733 | 4.356383 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/AddressedEnvelope.swift | 1 | 3088 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// A data structure for processing addressed datagrams, such as those used by UDP.
///
/// The AddressedEnvelope is used extensively on `DatagramChannel`s in order to keep track
/// of source or destination address metadata: that is, where some data came from or where
/// it is going.
public struct AddressedEnvelope<DataType> {
public var remoteAddress: SocketAddress
public var data: DataType
/// Any metadata associated with this `AddressedEnvelope`
public var metadata: Metadata? = nil
public init(remoteAddress: SocketAddress, data: DataType) {
self.remoteAddress = remoteAddress
self.data = data
}
public init(remoteAddress: SocketAddress, data: DataType, metadata: Metadata?) {
self.remoteAddress = remoteAddress
self.data = data
self.metadata = metadata
}
/// Any metadata associated with an `AddressedEnvelope`
public struct Metadata: Hashable, Sendable {
/// Details of any congestion state.
public var ecnState: NIOExplicitCongestionNotificationState
public var packetInfo: NIOPacketInfo?
public init(ecnState: NIOExplicitCongestionNotificationState) {
self.ecnState = ecnState
self.packetInfo = nil
}
public init(ecnState: NIOExplicitCongestionNotificationState, packetInfo: NIOPacketInfo?) {
self.ecnState = ecnState
self.packetInfo = packetInfo
}
}
}
extension AddressedEnvelope: CustomStringConvertible {
public var description: String {
return "AddressedEnvelope { remoteAddress: \(self.remoteAddress), data: \(self.data) }"
}
}
extension AddressedEnvelope: Equatable where DataType: Equatable {}
extension AddressedEnvelope: Hashable where DataType: Hashable {}
extension AddressedEnvelope: Sendable where DataType: Sendable {}
/// Possible Explicit Congestion Notification States
public enum NIOExplicitCongestionNotificationState: Hashable, Sendable {
/// Non-ECN Capable Transport.
case transportNotCapable
/// ECN Capable Transport (flag 0).
case transportCapableFlag0
/// ECN Capable Transport (flag 1).
case transportCapableFlag1
/// Congestion Experienced.
case congestionExperienced
}
public struct NIOPacketInfo: Hashable, Sendable {
public var destinationAddress: SocketAddress
public var interfaceIndex: Int
public init(destinationAddress: SocketAddress, interfaceIndex: Int) {
self.destinationAddress = destinationAddress
self.interfaceIndex = interfaceIndex
}
}
| apache-2.0 | ba982225b62307093babc5c56544ff79 | 34.494253 | 99 | 0.679728 | 4.972625 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Data Offers/HATDataOffer.swift | 1 | 11206 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 SwiftyJSON
// MARK: Struct
public struct HATDataOffer: HATObject {
// MARK: - CodingKeys
/**
The JSON fields used by the hat
The Fields are the following:
* `dataOfferID` in JSON is `id`
* `createdDate` in JSON is `created`
* `offerTitle` in JSON is `title`
* `shortDescription` in JSON is `shortDescription`
* `longDescription` in JSON is `longDescription`
* `imageURL` in JSON is `illustrationUrl`
* `offerStarts` in JSON is `starts`
* `offerExpires` in JSON is `expires`
* `collectsDataFor` in JSON is `collectFor`
* `minimumUsers` in JSON is `requiredMinUser`
* `maximumUsers` in JSON is `requiredMaxUser`
* `usersClaimedOffer` in JSON is `totalUserClaims`
* `requiredDataDefinitions` in JSON is `requiredDataDefinition`
* `dataConditions` in JSON is `dataConditions`
* `dataRequirements` in JSON is `dataRequirements`
* `reward` in JSON is `reward`
* `owner` in JSON is `owner`
* `claim` in JSON is `claim`
* `pii` in JSON is `pii`
* `merchantCode` in JSON is `merchantCode`
*/
private enum CodingKeys: String, CodingKey {
case dataOfferID = "id"
case dateCreated = "created"
case offerTitle = "title"
case shortDescription = "shortDescription"
case longDescription = "longDescription"
case imageURL = "illustrationUrl"
case startDate = "starts"
case expireDate = "expires"
case collectsDataFor = "collectFor"
case minimumUsers = "requiredMinUser"
case maximumUsers = "requiredMaxUser"
case usersClaimedOffer = "totalUserClaims"
case requiredDataDefinition = "requiredDataDefinition"
case dataConditions = "dataConditions"
case dataRequirements = "dataRequirements"
case reward = "reward"
case owner = "owner"
case claim = "claim"
case isPΙIRequested = "pii"
case merchantCode = "merchantCode"
}
// MARK: - Variables
/// The `Data Offer` unique ID
public var dataOfferID: String = ""
/// The `Data Offer` title
public var offerTitle: String = ""
/// The short description of the `Data Offer`, usually 1 phrase
public var shortDescription: String = ""
/// The long description of the `Data Offer`, usually 1 small paragraph stating more info about the offer and the reward
public var longDescription: String = ""
/// The image URL of the `Data Offer` in order to fetch it
public var imageURL: String = ""
/// The merchant code of the `Data Offer`, this is how you can ask for offers from a specific merchants. Any merchant ending in `private` is not visible publicly. Some merchants can be public as well
public var merchantCode: String = ""
/// the date created as unix time stamp
public var dateCreated: String = ""
/// the start date of the `Data Offer` as unix time stamp
public var startDate: String = ""
/// the expire date of the `Data Offer` as unix time stamp. After this date no one can claim the offer
public var expireDate: String = ""
/// the duration that the `Data Offer` collects data for as unix time stamp
public var collectsDataFor: Int = -1
/// the minimum users required for the `Data Offer` to activate
public var minimumUsers: Int = -1
/// the max users of the `Data Offer`. If this number is reached no one else can claim the offer
public var maximumUsers: Int = -1
/// the number of users claimed the `Data Offer` so far
public var usersClaimedOffer: Int = -1
/// the data definition object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var requiredDataDefinition: HATDataDefinition?
/// the data conditions object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var dataConditions: HATDataDefinition?
/// the data requirements object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var dataRequirements: HATDataDefinition?
/// the rewards information of the `Data Offer`. Here you can find information about the type of the reward, tha value, vouchers etc
public var reward: HATDataOfferRewards = HATDataOfferRewards()
/// The owner information of the `Data Offer`. Here you can find stuff like the name of the owner, email address etc
public var owner: HATDataOfferOwner = HATDataOfferOwner()
/// The claim information object of the `Data Offer`. Here you can find stuff like if the offer is claimed, when was it claimed etc
public var claim: HATDataOfferClaim = HATDataOfferClaim()
/// The downloaded image of the `Data Offer`, used to cache the image once downloaded. Optional
public var image: UIImage?
/// A flag indicating if the `Data Offer` requires pii, personal identifying information
public var isPΙIRequested: Bool = false
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
dataOfferID = ""
offerTitle = ""
shortDescription = ""
longDescription = ""
imageURL = ""
merchantCode = ""
dateCreated = ""
startDate = ""
expireDate = ""
collectsDataFor = -1
minimumUsers = -1
maximumUsers = -1
usersClaimedOffer = -1
requiredDataDefinition = nil
dataConditions = nil
dataRequirements = nil
reward = HATDataOfferRewards()
owner = HATDataOfferOwner()
claim = HATDataOfferClaim()
image = nil
isPΙIRequested = false
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(dictionary: Dictionary<String, JSON>) {
if let tempID: String = dictionary[HATDataOffer.CodingKeys.dataOfferID.rawValue]?.string {
dataOfferID = tempID
}
if let tempCreated: String = dictionary[HATDataOffer.CodingKeys.dateCreated.rawValue]?.string {
dateCreated = tempCreated
}
if let tempTitle: String = dictionary[HATDataOffer.CodingKeys.offerTitle.rawValue]?.string {
offerTitle = tempTitle
}
if let tempShortDescription: String = dictionary[HATDataOffer.CodingKeys.shortDescription.rawValue]?.string {
shortDescription = tempShortDescription
}
if let tempLongDescription: String = dictionary[HATDataOffer.CodingKeys.longDescription.rawValue]?.string {
longDescription = tempLongDescription
}
if let tempIllustrationUrl: String = dictionary[HATDataOffer.CodingKeys.imageURL.rawValue]?.string {
imageURL = tempIllustrationUrl
}
if let tempMerchantCode: String = dictionary[HATDataOffer.CodingKeys.merchantCode.rawValue]?.string {
merchantCode = tempMerchantCode
}
if let tempOfferStarts: String = dictionary[HATDataOffer.CodingKeys.startDate.rawValue]?.string {
startDate = tempOfferStarts
}
if let tempOfferExpires: String = dictionary[HATDataOffer.CodingKeys.expireDate.rawValue]?.string {
expireDate = tempOfferExpires
}
if let tempCollectOfferFor: Int = dictionary[HATDataOffer.CodingKeys.collectsDataFor.rawValue]?.int {
collectsDataFor = tempCollectOfferFor
}
if let tempRequiresMinUsers: Int = dictionary[HATDataOffer.CodingKeys.minimumUsers.rawValue]?.int {
minimumUsers = tempRequiresMinUsers
}
if let tempRequiresMaxUsers: Int = dictionary[HATDataOffer.CodingKeys.maximumUsers.rawValue]?.int {
maximumUsers = tempRequiresMaxUsers
}
if let tempUserClaims: Int = dictionary[HATDataOffer.CodingKeys.usersClaimedOffer.rawValue]?.int {
usersClaimedOffer = tempUserClaims
}
if let tempPII: Bool = dictionary[HATDataOffer.CodingKeys.isPΙIRequested.rawValue]?.bool {
isPΙIRequested = tempPII
}
if let tempRequiredDataDefinition: JSON = dictionary[HATDataOffer.CodingKeys.requiredDataDefinition.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempRequiredDataDefinition.rawData()
requiredDataDefinition = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempDataConditions: JSON = dictionary[HATDataOffer.CodingKeys.dataConditions.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempDataConditions.rawData()
dataConditions = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempDataRequirements: JSON = dictionary[HATDataOffer.CodingKeys.dataRequirements.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempDataRequirements.rawData()
dataRequirements = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempReward: [String: JSON] = dictionary[HATDataOffer.CodingKeys.reward.rawValue]?.dictionary {
reward = HATDataOfferRewards(dictionary: tempReward)
}
if let tempOwner: [String: JSON] = dictionary[HATDataOffer.CodingKeys.owner.rawValue]?.dictionary {
owner = HATDataOfferOwner(dictionary: tempOwner)
}
if let tempClaim: [String: JSON] = dictionary[HATDataOffer.CodingKeys.claim.rawValue]?.dictionary {
claim = HATDataOfferClaim(dictionary: tempClaim)
}
}
}
| mpl-2.0 | f492cdb5004a28c363ce8d712291b164 | 37.228669 | 203 | 0.621641 | 4.925682 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Extensions/UIView+Extensions.swift | 1 | 5679 | //
// UIView+Extensions.swift
// EclipseSoundscapes
//
// Created by Arlindo on 7/15/18.
// Copyright © 2018 Arlindo Goncalves. All rights reserved.
//
import UIKit
extension UIView {
class var identifier: String {
return String(describing: self)
}
/// Add subviews
/// - Note: Each view's translatesAutoresizingMaskIntoConstraints attribute is marked as false
///
/// - Parameter views: Views to add
func addSubviews(_ views : UIView...) {
views.forEach { (view) in
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
}
}
/// Center a view in given view
///
/// - Parameter view: View to center in
/// - Returns: Array of NSLayoutContraints
@discardableResult
func center(in view : UIView) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
anchors.append(centerXAnchor.constraint(equalTo: view.centerXAnchor))
anchors.append(centerYAnchor.constraint(equalTo: view.centerYAnchor))
anchors.forEach({$0.isActive = true})
return anchors
}
/// Set the size of the view
/// - Note: Values are constant values
///
/// - Parameters:
/// - width: Width Constant
/// - height: Height Constant
/// - Returns: Array of NSLayoutContraints
@discardableResult
func setSize(_ width: CGFloat, height: CGFloat ) -> [NSLayoutConstraint] {
return self.anchor(nil, left: nil, bottom: nil, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: width, heightConstant: height)
}
/// Set the size of the view
/// - Note: Values are constrained to layout dimensions
///
/// - Parameters:
/// - widthAnchor: Width dimension
/// - heightAnchor: Height dimension
/// - Returns: Array of NSLayoutContraints
@discardableResult
func setSize(widthAnchor: NSLayoutDimension, heightAnchor: NSLayoutDimension, widthMultiplier: CGFloat = 1, heightMultiplier: CGFloat = 1) -> [NSLayoutConstraint] {
var anchors = [NSLayoutConstraint]()
anchors.append(widthAnchor.constraint(equalTo: widthAnchor, multiplier: widthMultiplier))
anchors.append(heightAnchor.constraint(equalTo: heightAnchor, multiplier: heightMultiplier))
anchors.forEach({$0.isActive = true})
return anchors
}
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
_ = anchor(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant)
}
@discardableResult
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
/// Get Rombus Pattern View
///
/// - Returns: Rombus Pattern View
class func rombusPattern() -> UIView {
let iv = UIImageView()
iv.image = #imageLiteral(resourceName: "Rhombus Pattern")
return iv
}
/**
Slide in view from the top.
*/
func slideInFromTop(_ duration: TimeInterval = 0.3, completionDelegate: AnyObject? = nil) {
let slideInFromTopTransition = CATransition()
if let delegate: AnyObject = completionDelegate {
slideInFromTopTransition.delegate = delegate as? CAAnimationDelegate
}
slideInFromTopTransition.type = CATransitionType.push
slideInFromTopTransition.subtype = CATransitionSubtype.fromBottom
slideInFromTopTransition.duration = duration
slideInFromTopTransition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
slideInFromTopTransition.fillMode = CAMediaTimingFillMode.removed
self.layer.add(slideInFromTopTransition, forKey: "slideInFromTopTransition")
}
}
| gpl-3.0 | 376660908e144672a9e7d4ca9ac1377d | 37.890411 | 348 | 0.676999 | 5.06512 | false | false | false | false |
joshua7v/ResearchOL-iOS | ResearchOL/Class/Home/Controller/ROLHomeDetailController.swift | 1 | 10332 | //
// ROLHomeDetailController.swift
// ResearchOL
//
// Created by Joshua on 15/4/18.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
protocol ROLHomeDetailControllerDelegate: NSObjectProtocol {
func homeDetailControllerDidGetQuestions(homeDetailController: ROLHomeDetailController, questionare: ROLQuestionare)
}
class ROLHomeDetailController: UITableViewController {
var questionare: ROLQuestionare = ROLQuestionare()
var delegate: ROLHomeDetailControllerDelegate?
var watch = false
var sysBtnColor: UIColor {
get {
return UIButton().tintColor!
}
}
@IBOutlet weak var watchBtn: UIButton!
@IBOutlet weak var indicator: UIActivityIndicatorView!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var participantLabel: UILabel!
@IBOutlet weak var pointLabel: UILabel!
@IBOutlet weak var requiredTimeLabel: UILabel!
@IBAction func watchBtnDIdClicked(sender: UIButton) {
if !ROLUserInfoManager.sharedManager.isUserLogin {
SEProgressHUDTool.showError("需要登录", toView: self.navigationController?.view, yOffset: 200)
return
}
if !self.watch {
sender.enabled = false
sender.setTitle("关注中...", forState: .Normal)
ROLUserInfoManager.sharedManager.watchQuestionareForCurrentUser(self.questionare.uuid, success: { () -> Void in
sender.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
sender.setTitle("已关注 √", forState: .Normal)
sender.enabled = true
self.watch = true
}, failure: { () -> Void in
sender.setTitle("关注问卷", forState: .Normal)
sender.setTitleColor(self.sysBtnColor, forState: .Normal)
sender.enabled = true
self.watch = false
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SEProgressHUDTool.showError("请检查网络", toView: self.view)
})
})
} else {
sender.enabled = false
sender.setTitle("取消关注中...", forState: .Normal)
ROLUserInfoManager.sharedManager.unWatchQuestionareForCurrentUser(self.questionare.uuid, success: { () -> Void in
sender.setTitleColor(self.sysBtnColor, forState: .Normal)
sender.setTitle("关注问卷", forState: .Normal)
sender.enabled = true
self.watch = false
}, failure: { () -> Void in
sender.setTitle("已关注 √", forState: .Normal)
sender.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
sender.enabled = true
self.watch = true
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SEProgressHUDTool.showError("请检查网络", toView: self.view)
})
})
}
}
@IBAction func startBtnClicked() {
if !ROLUserInfoManager.sharedManager.isUserLogin {
var alert = AMSmoothAlertView(dropAlertWithTitle: "提示", andText: "未登陆无法获得奖励哦", andCancelButton: true, forAlertType: AlertType.Info, andColor: UIColor.blackColor(), withCompletionHandler: { (alertView, button) -> Void in
if button == alertView.defaultButton {
self.presentViewController(UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController() as! UINavigationController, animated: true, completion: { () -> Void in
})
} else {
var dest = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ROLQuestionareController") as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
dest.isAnonymous = true
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
self.presentViewController(dest, animated: true) { () -> Void in
}
}
})
alert.defaultButton.setTitle("去登录", forState: .Normal)
alert.cancelButton.setTitle("匿名答题", forState: .Normal)
alert.defaultButton.titleLabel?.font = UIFont.systemFontOfSize(13)
alert.cancelButton.titleLabel?.font = UIFont.systemFontOfSize(13)
alert.cornerRadius = 5
alert.show()
return
}
var dest = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ROLQuestionareController") as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
self.presentViewController(dest, animated: true) { () -> Void in
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.setupData()
self.setupNotifications()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !ROLUserInfoManager.sharedManager.isUserLogin { return }
// if self.startBtn.titleLabel?.text == "正在提交答案..." { return }
if ROLQuestionManager.sharedManager.isQuestionareAnswered(self.questionare.uuid) {
self.startBtn.setTitle("您已答过", forState: .Normal)
self.startBtn.enabled = false
} else {
self.startBtn.setTitle("马上参与", forState: .Normal)
self.startBtn.enabled = true
}
}
// MARK: - private
private func setupNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUserFinishedAnswerQuestionareNotification", name: ROLNotifications.userFinishedAnswerQuestionareNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUserDidFinishedAnswerQuestionareNotification", name: ROLNotifications.userDidFinishedAnswerQuestionareNotification, object: nil)
}
@objc private func handleUserFinishedAnswerQuestionareNotification() {
// self.startBtn.setTitle("正在提交答案...", forState: .Normal)
SEProgressHUDTool.showMessage("正在提交答案...", toView: self.view)
self.startBtn.enabled = false
}
@objc private func handleUserDidFinishedAnswerQuestionareNotification() {
self.startBtn.setTitle("您已答过", forState: .Normal)
SEProgressHUDTool.hideHUDForView(self.view)
self.startBtn.enabled = false
}
func setup() {
self.navigationItem.title = "问卷详情"
titleLabel.text = questionare.title
descLabel.text = questionare.desc
participantLabel.text = String(format: "%d 人", questionare.participant)
pointLabel.text = String(format: "%d 积分", questionare.point)
requiredTimeLabel.text = String(format: "%d 分钟", 3)
self.watchBtn.enabled = false
}
func setupData() {
if questionare.questions.count == 0 {
self.startBtn.enabled = false
self.startBtn.setTitle("数据加载中", forState: .Normal)
self.indicator.hidden = false
self.indicator.startAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
ROLQuestionManager.sharedManager.getQuestions(questionare.questionCount, questionare: questionare) { () -> Void in
println("get questions success -- ")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.startBtn.setTitle("马上参与", forState: .Normal)
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.startBtn.enabled = true
self.watchBtn.enabled = true
self.indicator.stopAnimating()
self.indicator.hidden = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
if (self.delegate?.respondsToSelector("homeDetailControllerDidGetQuestions:") != nil) {
self.delegate?.homeDetailControllerDidGetQuestions(self, questionare: self.questionare)
}
}
} else {
self.startBtn.setTitle("马上参与", forState: .Normal)
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.startBtn.enabled = true
self.watchBtn.enabled = true
self.indicator.stopAnimating()
self.indicator.hidden = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
var watchList = ROLUserInfoManager.sharedManager.getWatchListForCurrentUser()
for i in watchList {
if self.questionare.uuid == i {
self.watchBtn.setTitle("已关注 √", forState: .Normal)
self.watchBtn.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
self.watch = true
return
}
}
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.watchBtn.setTitleColor(self.sysBtnColor, forState: .Normal)
self.watch = false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var dest = segue.destinationViewController as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | 012197daf8598023a62ca5506497f49b | 44 | 231 | 0.61756 | 4.902724 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/Shared/Collection View Controllers/DescriptionCollectionViewController.swift | 1 | 4654 |
import Foundation
class DescriptionCollectionViewController: ResponsiveCollectionViewController, UICollectionViewDelegateFlowLayout {
var headerTitle: String?
var sizingCell: DescriptionCollectionViewCell?
var dataSource: [(key: Any, value: String)] = [("", "")]
var isDark = true {
didSet {
guard isDark != oldValue else { return }
collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(UINib(nibName: String(describing: DescriptionCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: "cell")
}
override func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewFlowLayout, didChangeToSize size: CGSize) {
var estimatedContentHeight: CGFloat = 0.0
for section in 0..<collectionView.numberOfSections {
let headerSize = self.collectionView(collectionView, layout: layout, referenceSizeForHeaderInSection: section)
estimatedContentHeight += headerSize.height
let numberOfCells = collectionView.numberOfItems(inSection: section)
for item in 0..<numberOfCells {
let itemSize = self.collectionView(collectionView, layout: layout, sizeForItemAt: IndexPath(item: item, section: section))
estimatedContentHeight += itemSize.height + layout.minimumLineSpacing
}
}
super.collectionView(collectionView, layout: layout, didChangeToSize: CGSize(width: collectionView.bounds.width, height: estimatedContentHeight))
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DescriptionCollectionViewCell
let data = dataSource[indexPath.row]
if let text = data.key as? String {
cell.keyLabel.text = text
} else if let attributedText = data.key as? NSAttributedString {
cell.keyLabel.attributedText = attributedText
}
cell.valueLabel.text = data.value
cell.isDark = isDark
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let data = dataSource[indexPath.row]
sizingCell = sizingCell ?? .fromNib()
if let text = data.key as? String {
sizingCell?.keyLabel.text = text
} else if let attributedText = data.key as? NSAttributedString {
sizingCell?.keyLabel.attributedText = attributedText
}
sizingCell?.valueLabel.text = data.value
sizingCell?.setNeedsLayout()
sizingCell?.layoutIfNeeded()
let maxWidth = collectionView.bounds.width
let targetSize = CGSize(width: maxWidth, height: 0)
return sizingCell?.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel) ?? .zero
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return headerTitle == nil ? .zero : CGSize(width: collectionView.bounds.width, height: 50)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader, let title = headerTitle {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
let titleLabel = view.viewWithTag(1) as? UILabel
titleLabel?.text = title
titleLabel?.textColor = isDark ? .white : .black
return view
}
return super.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath)
}
}
| gpl-3.0 | d9e81d53490223ec9a3098fcf626d4dc | 42.092593 | 201 | 0.670176 | 6.2977 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Features/ExceptionTrackerImpl.swift | 1 | 18138 | import Foundation
//these function should be global due to requriements to NSSetUncaughtExceptionHandler
private func exceptionHandler(exception: NSException) {
defer {
// init old handler
if let oldHandler = ExceptionTrackerImpl.previousExceptionHandler {
oldHandler(exception)
}
}
//Save exception to file
WebtrekkTracking.defaultLogger.logDebug("""
Webtrekk catched exception: \(exception),
callStack: \(exception.callStackSymbols),
reason: \(exception.reason ?? "nil"),
name: \(exception.name),
user info: \(String(describing: exception.userInfo)),
return address: \(exception.callStackReturnAddresses)
""")
ExceptionSaveAndSendHelper.default.saveToFile(name: exception.name.rawValue,
stack: exception.callStackSymbols,
reason: exception.reason,
userInfo: exception.userInfo as NSDictionary?,
stackReturnAddress: exception.callStackReturnAddresses)
}
#if !os(watchOS)
//these function should be global due to requriements to signal handler API
private func signalHandler(signalNum: Int32) {
let signalsMap: [Int32: String] = [4: "SIGILL",
5: "SIGTRAP",
6: "SIGABRT",
8: "SIGFPE",
10: "SIGBUS",
11: "SIGSEGV",
13: "SIGPIPE"]
//Save exception to file
defer {
if let oldSignal = ExceptionTrackerImpl.previousSignalHandlers[signalNum] {
//just call original one it should exit
oldSignal(signalNum)
}
exit(signalNum)
}
//Save exception to file
WebtrekkTracking.defaultLogger.logDebug("""
Webtrekk catched signal: \(signalsMap[signalNum] ?? "undefined") with dump: \(Thread.callStackSymbols)
""")
// remove first two items as this is handler function items.
let stack = Array(Thread.callStackSymbols.suffix(from: 2))
ExceptionSaveAndSendHelper.default.saveToFile(name: "Signal: \(signalsMap[signalNum] ?? "undefined")",
stack: stack,
reason: nil,
userInfo: nil,
stackReturnAddress: nil)
}
#endif
class ExceptionTrackerImpl: ExceptionTracker {
// use var to make it lazy initialized.
static var previousExceptionHandler: ExceptionHandler = nil
private static var initialized = false
fileprivate static var previousSignalHandlers = [Int32: SignalHanlder]()
#if !os(watchOS)
private let signals: [Int32] = [SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGTRAP]
#endif
private var errorLogLevel: ErrorLogLevel = .disable
typealias SignalHanlder = (@convention(c) (Int32) -> Swift.Void)
typealias ExceptionHandler = (@convention(c) (NSException) -> Swift.Void)?
fileprivate enum ErrorLogLevel: Int {
case disable, fatal, catched, info
}
//here should be defined exceptionTrackingMode
func initializeExceptionTracking(config: TrackerConfiguration) {
// init only once
guard !ExceptionTrackerImpl.initialized else {
return
}
if let errorLogLevel = config.errorLogLevel, (0...3).contains(errorLogLevel) {
self.errorLogLevel = ErrorLogLevel(rawValue: errorLogLevel)!
}
guard satisfyToLevel(level: .fatal) else {
// don't do anything for disable level
ExceptionTrackerImpl.initialized = true
return
}
installUncaughtExceptionHandler()
ExceptionTrackerImpl.initialized = true
}
func sendSavedException() {
guard satisfyToLevel(level: .fatal) else {
// don't do anything for disable level
return
}
ExceptionSaveAndSendHelper.default.loadAndSend(logLevel: self.errorLogLevel)
}
deinit {
guard ExceptionTrackerImpl.initialized else {
return
}
NSSetUncaughtExceptionHandler(ExceptionTrackerImpl.previousExceptionHandler)
ExceptionTrackerImpl.previousExceptionHandler = nil
#if !os(watchOS)
for signalNum in self.signals {
// restore signals back
signal(signalNum, ExceptionTrackerImpl.previousSignalHandlers[signalNum])
}
#endif
ExceptionTrackerImpl.initialized = false
}
private func installUncaughtExceptionHandler() {
// save previous exception handler
ExceptionTrackerImpl.previousExceptionHandler = NSGetUncaughtExceptionHandler()
// set Webtrekk one
NSSetUncaughtExceptionHandler(exceptionHandler)
#if !os(watchOS)
// setup processing for signals. Save old processing as well
for signalNum in self.signals {
// set Webtrekk signal handler and get previoius one
let oldSignal = signal(signalNum, signalHandler)
// save previoius signal handler
if oldSignal != nil {
ExceptionTrackerImpl.previousSignalHandlers[signalNum] = oldSignal
}
}
#endif
WebtrekkTracking.defaultLogger.logDebug("exception tracking has been initialized")
}
func trackInfo(_ name: String, message: String) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .info) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to info/warning level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel, name: name, message: message)
}
func trackException(_ exception: NSException) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel,
name: exception.name.rawValue,
stack: exception.callStackSymbols,
message: exception.reason,
userInfo: exception.userInfo as NSDictionary?,
stackReturnAddress: exception.callStackReturnAddresses)
}
func trackError(_ error: Error) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel,
name: "Error",
message: error.localizedDescription)
}
func trackNSError(_ error: NSError) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel, name: "NSError",
message: "code:\(error.code), domain:\(error.domain)",
userInfo: error.userInfo as NSDictionary?)
}
private func checkIfInitialized() -> Bool {
if !ExceptionTrackerImpl.initialized {
logError("Webtrekk exception tracking isn't initialited")
}
return ExceptionTrackerImpl.initialized
}
private func satisfyToLevel(level: ErrorLogLevel) -> Bool {
return self.errorLogLevel.rawValue >= level.rawValue
}
}
private class ExceptionSaveAndSendHelper {
private var applicationSupportDir: URL?
private let exceptionFileName = "webtrekk_exception"
private let maxParameterLength = 255
private let saveDirectory: FileManager.SearchPathDirectory
// set it var to make it lazy
fileprivate static var `default` = ExceptionSaveAndSendHelper()
init() {
#if os(tvOS)
saveDirectory = .cachesDirectory
#else
saveDirectory = .applicationSupportDirectory
#endif
self.applicationSupportDir = FileManager.default.urls(for: saveDirectory,
in: .userDomainMask).first?.appendingPathComponent("Webtrekk")
}
private func normalizeStack(stack: [String]?) -> NSString {
let returnStack = stack?.joined(separator: "|")
.replacingOccurrences(of: "\\s{2,}", with: " ", options: .regularExpression, range: nil)
return normalizeField(field: returnStack, fieldName: "stack")
}
private func normalizeUserInfo(userInfo: NSDictionary?) -> NSString {
let userInfo = userInfo?.compactMap { key, value in
return "\(key):\(value);"
}.joined()
return normalizeField(field: userInfo, fieldName: "user info")
}
private func normalizeUserReturnAddress(returnAddress: [NSNumber]?) -> NSString {
let returnValue = returnAddress?.compactMap({$0.stringValue}).joined(separator: " ")
return normalizeField(field: returnValue, fieldName: "stack return address")
}
// make string not more then 255 length TODO: use Swift4 for this converstions
private func normalizeField(field: String?, fieldName: String) -> NSString {
guard let fieldUtf8 = field?.utf8CString, !fieldUtf8.isEmpty else {
return ""
}
guard fieldUtf8.count <= 255 else {
WebtrekkTracking.defaultLogger.logWarning("""
Field \(fieldName) is more then 255 length during excception tracking.
Normalize it by cutting to 255 length.
""")
let cutUTF8Field = Array(fieldUtf8.prefix(maxParameterLength))
return cutUTF8Field.withUnsafeBytes { buffer in
return NSString(bytes: buffer.baseAddress!,
length: maxParameterLength,
encoding: String.Encoding.utf8.rawValue)!
}
}
return NSString(string: field ?? "")
}
fileprivate func saveToFile(name: String,
stack: [String],
reason: String?,
userInfo: NSDictionary?,
stackReturnAddress: [NSNumber]?) {
saveToFile(name: normalizeField(field: name, fieldName: "name"),
stack: normalizeStack(stack: stack),
reason: normalizeField(field: reason, fieldName: "reason"),
userInfo: normalizeUserInfo(userInfo: userInfo),
stackReturnAddress: normalizeUserReturnAddress(returnAddress: stackReturnAddress))
}
private func saveToFile(name: NSString,
stack: NSString,
reason: NSString,
userInfo: NSString,
stackReturnAddress: NSString) {
// get url
guard let url = newFileURL else {
return
}
let array: NSArray = [name, stack, reason, userInfo, stackReturnAddress]
//construct string
guard array.write(to: url, atomically: true) else {
WebtrekkTracking.defaultLogger.logError("""
Can't save exception with url: \(url). Exception tracking won't be done.
""")
return
}
}
private var newFileURL: URL? {
var url: URL
var i: Int = 0
repeat {
let urlValue = applicationSupportDir?.appendingPathComponent(exceptionFileName+"\(i)"+".xml")
if urlValue == nil {
WebtrekkTracking.defaultLogger.logError("""
Can't define path for saving exception.
Exception tracking for fatal exception won't work.
""")
return nil
} else {
url = urlValue!
}
i = i + 1
} while FileManager.default.fileExists(atPath: url.path)
return url
}
private var existedFileURL: URL? {
guard let supportDir = applicationSupportDir?.path else {
WebtrekkTracking.defaultLogger.logError("""
Can't define path for reading exception.
Exception tracking for fatal exception won't work.
""")
return nil
}
let enumerator = FileManager.default.enumerator(atPath: supportDir)
var minimumNumber: Int? = nil
var fileName: String? = nil
//find file with minimumID
enumerator?.forEach { value in
if let strValue = value as? String, strValue.contains(exceptionFileName) {
if let range = strValue.range(of: "\\d", options: .regularExpression),
let number = Int(strValue[range]) {
if minimumNumber == nil || minimumNumber! > number {
minimumNumber = number
fileName = strValue
}
}
}
}
guard let _ = fileName else {
return nil
}
return applicationSupportDir?.appendingPathComponent(fileName!)
}
// send exception that is saved on NAND
fileprivate func loadAndSend(logLevel: ExceptionTrackerImpl.ErrorLogLevel) {
while let url = self.existedFileURL {
defer {
// delete file
do {
try FileManager.default.removeItem(atPath: url.path)
} catch let error {
WebtrekkTracking.defaultLogger.logError("""
Serious problem with saved exception file deletion: \(error).
Information about exception can be sent several times.
""")
}
}
guard let array = NSArray(contentsOf: url) as? [NSString] else {
continue
}
// send action
track(logLevel: logLevel,
name: array[0],
stack: array[1],
message: array[2],
userInfo: array[3],
stackReturnAddress: array[4])
}
}
fileprivate func track(logLevel: ExceptionTrackerImpl.ErrorLogLevel,
name: String, stack: [String]? = nil,
message: String? = nil,
userInfo: NSDictionary? = nil,
stackReturnAddress: [NSNumber]? = nil) {
track(logLevel: logLevel,
name: normalizeField(field: name, fieldName: "name"),
stack: normalizeStack(stack: stack),
message: normalizeField(field: message, fieldName: "message/reason"),
userInfo: normalizeUserInfo(userInfo: userInfo),
stackReturnAddress: normalizeUserReturnAddress(returnAddress: stackReturnAddress))
}
// common function for tracking exception field message can be as message and reason
private func track(logLevel: ExceptionTrackerImpl.ErrorLogLevel,
name: NSString? = nil,
stack: NSString? = nil,
message: NSString? = nil,
userInfo: NSString? = nil,
stackReturnAddress: NSString? = nil) {
guard let webtrekk = WebtrekkTracking.instance() as? DefaultTracker else {
WebtrekkTracking.defaultLogger.logDebug("Can't convert to DefaultTracker for sending event")
return
}
guard logLevel.rawValue > ExceptionTrackerImpl.ErrorLogLevel.disable.rawValue else {
WebtrekkTracking.defaultLogger.logDebug("Error level is disabled. Won't do any call")
return
}
//define details
var details: [Int: TrackingValue] = [:]
details[910] = .constant(String(logLevel.rawValue))
if let name = name as String?, !name.isEmpty {
details[911] = .constant(name)
}
if let message = message as String?, !message.isEmpty {
details[912] = .constant(message)
}
if let stack = stack as String?, !stack.isEmpty {
details[913] = .constant(stack)
}
if let userInfo = userInfo as String?, !userInfo.isEmpty {
details[916] = .constant(userInfo)
}
if let stackReturnAddress = stackReturnAddress as String?, !stackReturnAddress.isEmpty {
details[917] = .constant(stackReturnAddress)
}
let action = ActionEvent(actionProperties: ActionProperties(name: "webtrekk_ignore", details: details),
pageProperties: PageProperties(name: nil))
webtrekk.enqueueRequestForEvent(action, type: .exceptionTracking)
}
}
| mit | 57148845dcd401bd5ff4e54cb841aa8e | 36.168033 | 123 | 0.566325 | 5.51307 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Concat.swift | 8 | 5067 | //
// Concat.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Observable<Element> where Source.Element == Element {
Observable.concat([self.asObservable(), second.asObservable()])
}
}
extension ObservableType {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
return Concat(sources: sequence, count: nil)
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Observable<Element>
where Collection.Element == Observable<Element> {
return Concat(sources: collection, count: Int64(collection.count))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Observable<Element> ...) -> Observable<Element> {
Concat(sources: sources, count: Int64(sources.count))
}
}
final private class ConcatSink<Sequence: Swift.Sequence, Observer: ObserverType>
: TailRecursiveSink<Sequence, Observer>
, ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>){
switch event {
case .next:
self.forwardOn(event)
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self.schedule(.moveNext)
}
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
source.subscribe(self)
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
if let source = observable as? Concat<Sequence> {
return (source.sources.makeIterator(), source.count)
}
else {
return nil
}
}
}
final private class Concat<Sequence: Swift.Sequence>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableConvertibleType {
typealias Element = Sequence.Element.Element
fileprivate let sources: Sequence
fileprivate let count: IntMax?
init(sources: Sequence, count: IntMax?) {
self.sources = sources
self.count = count
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = ConcatSink<Sequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run((self.sources.makeIterator(), self.count))
return (sink: sink, subscription: subscription)
}
}
| mit | 6bb01a0eb55b8bf89101ae17332cbda3 | 37.671756 | 171 | 0.692657 | 4.923226 | false | false | false | false |
jiaopen/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/PreviewSupplementaryView.swift | 1 | 2711 | //
// PreviewSupplementaryView.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class PreviewSupplementaryView : UICollectionReusableView {
private let button: UIButton = {
let button = UIButton()
button.tintColor = .whiteColor()
button.userInteractionEnabled = false
button.setImage(PreviewSupplementaryView.checkmarkImage, forState: .Normal)
button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, forState: .Selected)
return button
}()
var buttonInset = UIEdgeInsetsZero
var selected: Bool = false {
didSet {
button.selected = selected
reloadButtonBackgroundColor()
}
}
class var checkmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark")
// let image = UIImage(contentsOfFile: bundle.pathForResource("PreviewSupplementaryView-Checkmark", ofType: "png")!)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
class var selectedCheckmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected")
// let image = UIImage(contentsOfFile: bundle.pathForResource("PreviewSupplementaryView-Checkmark-Selected", ofType: "png")!)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(button)
}
// MARK: - Other Methods
override func prepareForReuse() {
super.prepareForReuse()
selected = false
}
override func tintColorDidChange() {
super.tintColorDidChange()
reloadButtonBackgroundColor()
}
private func reloadButtonBackgroundColor() {
button.backgroundColor = (selected) ? tintColor : nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
button.sizeToFit()
button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom)
button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0
}
}
| mit | b6161f4df07ebd0d9b0c024e0e1f90c9 | 28.150538 | 133 | 0.646625 | 5.400398 | false | false | false | false |
fauve-/sunday-afternoon-swift | Sources/main.swift | 1 | 1863 | //so we're going to implement http://rosettacode.org/wiki/Globally_replace_text_in_several_files
//invoked like so `./fnr "my sweet text" file1 file2 file3 file4
//if those files are directories, we'll ignore them
//pretty much it
//it's a little weird not having an entrypoint function
//wonder how large programs do the whole
//int main(){
//init_state()
//main_loop()
//}
//idiom that is so common
//my it's my server-side background talking
//import glibc for exit etc
import Glibc
//let's go ahead and look at our arguments
//TODO: guards!
if Process.arguments.count < 3 {
print("Invoke like this \(Process.arguments[0]) <old string> <new string> <some files...>")
exit(-1)
}
//okay, now we need to do some real work I guess
//we have to revert back to c stuff to open some files
let toReplace = Process.arguments[1]
let newString = Process.arguments[2]
//remove the cruft
var filesToScan = Array<String>.init(Process.arguments)
filesToScan.removeFirst(3)
for filename in filesToScan {
//some dog and pony show to open up this pit
let UnsafeFileName = [UInt8](filename.utf8)
var unsafeFilePointer = UnsafeMutablePointer<Int8>(UnsafeFileName)
let fp = fopen(unsafeFilePointer,"r+")
let BUFSIZE = 1024
var buf = [CChar](count:BUFSIZE, repeatedValue:CChar(0))
fread(&buf,Int(1),Int(BUFSIZE),fp)
fclose(fp)
//let us now do some things
let contents = String.fromCString(buf)!
let newContents = contents.replace(toReplace,newString:newString)
let UnsafeNewContents = [UInt8](newContents.utf8)
//reopen file to get a new FILE* that will allow us to tuncate if the file lengths are different
let newfp = fopen(unsafeFilePointer,"w")
fwrite(UnsafeNewContents,Int(1),UnsafeNewContents.count,newfp);
fflush(newfp)
fclose(newfp)
}
| mit | 6ad09466b4ea9ac797fd5efa50b6fbcc | 32.267857 | 100 | 0.700483 | 3.631579 | false | false | false | false |
nuclearace/Starscream | Sources/Starscream/WebSocket.swift | 1 | 54685 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import SSCommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public enum ErrorType: Error {
case outputStreamWriteError //output stream error during write
case compressionError
case invalidSSLError //Invalid SSL certificate
case writeTimeoutError //The socket timed out waiting to be ready to write
case protocolError //There was an error parsing the WebSocket frames
case upgradeError //There was an error during the HTTP upgrade
case closeError //There was an error during the close (socket probably has been dereferenced)
}
public struct WSError: Error {
public let type: ErrorType
public let message: String
public let code: Int
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set}
var disableSSLCertValidation: Bool {get set}
var overrideTrustHostname: Bool {get set}
var desiredTrustHostname: String? {get set}
var sslClientCertificate: SSLClientCertificate? {get set}
#if os(Linux)
#else
var security: SSLTrustValidator? {get set}
var enabledSSLCipherSuites: [SSLCipherSuite]? {get set}
#endif
var isConnected: Bool {get}
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
public let useSSL: Bool
public let disableCertValidation: Bool
public var overrideTrustHostname: Bool
public var desiredTrustHostname: String?
public let sslClientCertificate: SSLClientCertificate?
#if os(Linux)
#else
public let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
if let sslClientCertificate = ssl.sslClientCertificate {
settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn)))
}
if resOut != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
} else if self == nil {
completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0))
return
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
guard let outputStream = outputStream else { return (nil, nil) }
let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String?
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var sslClientCertificate: SSLClientCertificate? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
mutex.lock()
let isConnected = connected
mutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let mutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)"
request.setValue(hostValue, forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname),
sslClientCertificate: sslClientCertificate
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
sslClientCertificate: sslClientCertificate,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let s = self else {return}
if error != nil {
s.disconnectStream(error)
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let s = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
s.certValidated = false
#else
if let sec = s.security, !s.certValidated {
let trustObj = s.stream.sslTrust()
if let possibleTrust = trustObj.trust {
s.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
s.certValidated = false
}
if !s.certValidated {
s.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0))
return
}
}
#endif
let _ = s.stream.write(data: data)
}
s.writeQueue.addOperation(operation)
})
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
mutex.lock()
cleanupStream()
connected = false
mutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
mutex.lock()
connected = true
mutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.advancedDelegate?.websocketDidConnect(socket: s)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
s.onPong?(pongData)
s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str)
s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = s.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor {
do {
data = try compressor.compress(data)
if s.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= s.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
if !s.readyToWrite {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
}
let stream = s.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
mutex.lock()
connected = false
mutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
cleanupStream()
mutex.unlock()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
#if swift(>=4)
#else
fileprivate extension String {
var count: Int {
return self.characters.count
}
}
#endif
| apache-2.0 | 4f5c0ef81ba226ccec3d59e64134d0ff | 39.417591 | 226 | 0.585956 | 5.35183 | false | false | false | false |
Nimbow/Client-iOS | client/client/BinarySms.swift | 1 | 931 | //
// BinarySms.swift
// client
//
// Created by Awesome Developer on 23/01/16.
// Copyright © 2016 Nimbow. All rights reserved.
//
public final class BinarySms : Sms {
public var Data: NSData?
public var Udh: String?
public convenience init(from: String?, to: String?, data: NSData?, udh: String?) {
self.init(from: from, to: to)
Data = data
Udh = udh
}
override func ToSendSmsRequest() -> SendSmsRequest {
let request = super.ToSendSmsRequest()
request.Type = SmsType.Binary
request.Udh = Udh
if (Data == nil) { return request; }
var string = ""
var byte: UInt8 = 0
for i in 0 ..< Data!.length {
Data!.getBytes(&byte, range: NSMakeRange(i, 1))
string += String(format: "%04x", byte)
}
request.Text = string
return request
}
} | mit | 2b7daf85c2eed4a90fe8bd97efc14fda | 24.162162 | 86 | 0.544086 | 3.924051 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.