repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev | iOS/Pods/BluemixAppID/Source/BluemixAppID/internal/SecurityUtils.swift | 2 | 10311 | /* * Copyright 2016, 2017 IBM Corp.
* 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
internal class SecurityUtils {
private static func getKeyBitsFromKeyChain(_ tag:String) throws -> Data {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnData : true as AnyObject
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! Data
}
internal static func generateKeyPair(_ keySize:Int, publicTag:String, privateTag:String) throws {
//make sure keys are deleted
_ = SecurityUtils.deleteKeyFromKeyChain(publicTag)
_ = SecurityUtils.deleteKeyFromKeyChain(privateTag)
var status:OSStatus = noErr
var privateKey:SecKey?
var publicKey:SecKey?
let privateKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : privateTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPrivate
]
let publicKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : publicTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
]
let keyPairAttr : [NSString:AnyObject] = [
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits : keySize as AnyObject,
kSecPublicKeyAttrs : publicKeyAttr as AnyObject,
kSecPrivateKeyAttrs : privateKeyAttr as AnyObject
]
status = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if (status != errSecSuccess) {
throw AppIDError.generalError
}
}
private static func getKeyRefFromKeyChain(_ tag:String) throws -> SecKey {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnRef : kCFBooleanTrue
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! SecKey
}
internal static func getItemFromKeyChain(_ label:String) -> String? {
let query: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecReturnData: kCFBooleanTrue
]
var results: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &results)
if status == errSecSuccess {
let data = results as! Data
let password = String(data: data, encoding: String.Encoding.utf8)!
return password
}
return nil
}
public static func getJWKSHeader() throws ->[String:Any] {
let publicKey = try? SecurityUtils.getKeyBitsFromKeyChain(AppIDConstants.publicKeyIdentifier)
guard let unWrappedPublicKey = publicKey, let pkModulus : Data = getPublicKeyMod(unWrappedPublicKey), let pkExponent : Data = getPublicKeyExp(unWrappedPublicKey) else {
throw AppIDError.generalError
}
let mod:String = Utils.base64StringFromData(pkModulus, isSafeUrl: true)
let exp:String = Utils.base64StringFromData(pkExponent, isSafeUrl: true)
let publicKeyJSON : [String:Any] = [
"e" : exp as AnyObject,
"n" : mod as AnyObject,
"kty" : AppIDConstants.JSON_RSA_VALUE
]
return publicKeyJSON
}
private static func getPublicKeyMod(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1 // TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
if(mod_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, mod_size).toRange()!)
}
//Return public key exponent
private static func getPublicKeyExp(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1// TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
iterator += mod_size
iterator += 1 // TYPE - bit stream exp
let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
//Ensure we got an exponent size
if(exp_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, exp_size).toRange()!)
}
private static func derEncodingGetSizeFrom(_ buf : Data, at iterator: inout Int) -> Int{
// Have to cast the pointer to the right size
//let pointer = UnsafePointer<UInt8>((buf as NSData).bytes)
//let count = buf.count
// Get our buffer pointer and make an array out of it
//let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
let data = buf//[UInt8](buffer)
var itr : Int = iterator
var num_bytes :UInt8 = 1
var ret : Int = 0
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80
itr += 1
}
for i in 0 ..< Int(num_bytes) {
ret = (ret * 0x100) + Int(data[itr + i])
}
iterator = itr + Int(num_bytes)
return ret
}
internal static func signString(_ payloadString:String, keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String {
do {
let privateKeySec = try getKeyRefFromKeyChain(ids.privateKey)
guard let payloadData : Data = payloadString.data(using: String.Encoding.utf8) else {
throw AppIDError.generalError
}
let signedData = try signData(payloadData, privateKey:privateKeySec)
//return signedData.base64EncodedString()
return Utils.base64StringFromData(signedData, isSafeUrl: true)
}
catch {
throw AppIDError.generalError
}
}
private static func signData(_ data:Data, privateKey:SecKey) throws -> Data {
func doSha256(_ dataIn:Data) throws -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
dataIn.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(dataIn.count), &hash)
}
return Data(bytes: hash)
}
guard let digest:Data = try? doSha256(data), let signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else {
throw AppIDError.generalError
}
var signedDataLength: Int = signedData.length
let digestBytes: UnsafePointer<UInt8> = ((digest as NSData).bytes).bindMemory(to: UInt8.self, capacity: digest.count)
let digestlen = digest.count
let mutableBytes: UnsafeMutablePointer<UInt8> = signedData.mutableBytes.assumingMemoryBound(to: UInt8.self)
let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen,
mutableBytes, &signedDataLength)
guard signStatus == errSecSuccess else {
throw AppIDError.generalError
}
return signedData as Data
}
internal static func saveItemToKeyChain(_ data:String, label: String) -> Bool{
guard let stringData = data.data(using: String.Encoding.utf8) else {
return false
}
let key: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecValueData: stringData as AnyObject
]
var status = SecItemAdd(key as CFDictionary, nil)
if(status != errSecSuccess){
if(SecurityUtils.removeItemFromKeyChain(label) == true) {
status = SecItemAdd(key as CFDictionary, nil)
}
}
return status == errSecSuccess
}
internal static func removeItemFromKeyChain(_ label: String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
internal static func deleteKeyFromKeyChain(_ tag:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag : tag as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
}
| apache-2.0 | 8638bab36af9161f8eee877422963530 | 36.223827 | 176 | 0.600524 | 5.298561 | false | false | false | false |
1985apps/PineKit | Pod/Classes/PineMenuTransition.swift | 1 | 1791 | //
// KamaConfig.swift
// KamaUIKit
//
// Created by Prakash Raman on 13/02/16.
// Copyright © 2016 1985. All rights reserved.
//
import Foundation
import UIKit
open class PineMenuTransition : NSObject {
open var mainController: PineMenuViewController?
open var menuView: PineBaseMenuView?
public override init(){
self.mainController = nil
}
// ONCE THE CONTROLLER IS SETUP THE MENU IS SETUP AS WELL
// START MENU POSITION IS VERY IMPORTANT
func setController(_ controller: PineMenuViewController){
self.mainController = controller
self.menuView = self.mainController!.menuView!
self.setup()
}
func setup(){
self.mainController!.menuView!.frame = self.mainController!.view.frame
}
func toggle(){
setup()
if self.isOpen() {
close()
} else {
open()
}
}
func isOpen() -> Bool {
let contentFrame = self.mainController!.contentNavigationController!.view.frame
let controllerFrame = self.mainController!.view.frame
return (controllerFrame != contentFrame) ? true : false
}
func open(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
var frame = (self.mainController?.contentNavigationController!.view.frame)! as CGRect
frame.origin.x = 200
self.mainController?.contentNavigationController!.view.frame = frame
})
}
func close(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
self.mainController!.contentNavigationController!.view.frame = self.mainController!.view.frame
})
}
}
| mit | b48876544934c9240dc1c58f154e0dc8 | 27.412698 | 106 | 0.629609 | 4.773333 | false | false | false | false |
anirudh24seven/wikipedia-ios | Wikipedia/Code/WMFReferencePanelViewController.swift | 1 | 2029 |
import Foundation
class WMFReferencePanelViewController: UIViewController {
@IBOutlet private var containerViewHeightConstraint:NSLayoutConstraint!
@IBOutlet var containerView:UIView!
var reference:WMFReference?
override func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer.bk_recognizerWithHandler { (sender, state, location) in
if state == .Ended {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
view.addGestureRecognizer((tapRecognizer as? UITapGestureRecognizer)!)
embedContainerControllerView()
}
private func panelHeight() -> CGFloat {
return view.frame.size.height * (UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation) ? 0.4 : 0.6)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
containerViewHeightConstraint.constant = panelHeight()
containerController.scrollEnabled = true
containerController.scrollToTop()
}
private lazy var containerController: WMFReferencePopoverMessageViewController = {
let referenceVC = WMFReferencePopoverMessageViewController.wmf_initialViewControllerFromClassStoryboard()
referenceVC.reference = self.reference
return referenceVC
}()
private func embedContainerControllerView() {
containerController.willMoveToParentViewController(self)
containerController.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(containerController.view!)
containerView.bringSubviewToFront(containerController.view!)
containerController.view.mas_makeConstraints { make in
make.top.bottom().leading().and().trailing().equalTo()(self.containerView)
}
self.addChildViewController(containerController)
containerController.didMoveToParentViewController(self)
}
}
| mit | 3a6959b2a25a71a5f7292c5cec9ba4ca | 38.784314 | 121 | 0.717595 | 6.587662 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/Compound.swift | 6 | 3774 | //
// Compound.swift
// Cartography
//
// Created by Robert Böhnke on 18/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol Compound {
var context: Context { get }
var properties: [Property] { get }
}
/// Compound properties conforming to this protocol can use the `==` operator
/// with other compound properties of the same type.
public protocol RelativeCompoundEquality : Compound { }
/// Declares a property equal to a the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The expression.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func == <P: RelativeCompoundEquality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value)
}
/// Declares a property equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
@discardableResult public func == <P: RelativeCompoundEquality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs)
}
/// Compound properties conforming to this protocol can use the `<=` and `>=`
/// operators with other compound properties of the same type.
public protocol RelativeCompoundInequality : Compound { }
/// Declares a property less than or equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeCompoundInequality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs, relation: .lessThanOrEqual)
}
/// Declares a property greater than or equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeCompoundInequality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs, relation: .greaterThanOrEqual)
}
/// Declares a property less than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeCompoundInequality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: .lessThanOrEqual)
}
/// Declares a property greater than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeCompoundInequality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: .greaterThanOrEqual)
}
| mit | 2d4942210c741978c19a9efea0a99df4 | 38.291667 | 119 | 0.71474 | 4.437647 | false | false | false | false |
scinfu/SwiftSoup | Tests/SwiftSoupTests/TagTest.swift | 1 | 2783 | //
// TagTest.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 17/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import XCTest
import SwiftSoup
class TagTest: XCTestCase {
func testLinuxTestSuiteIncludesAllTests() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
func testIsCaseSensitive()throws {
let p1: Tag = try Tag.valueOf("P")
let p2: Tag = try Tag.valueOf("p")
XCTAssertFalse(p1.equals(p2))
}
func testCanBeInsensitive()throws {
let p1: Tag = try Tag.valueOf("P", ParseSettings.htmlDefault)
let p2: Tag = try Tag.valueOf("p", ParseSettings.htmlDefault)
XCTAssertEqual(p1, p2)
}
func testTrims()throws {
let p1: Tag = try Tag.valueOf("p")
let p2: Tag = try Tag.valueOf(" p ")
XCTAssertEqual(p1, p2)
}
func testEquality()throws {
let p1: Tag = try Tag.valueOf("p")
let p2: Tag = try Tag.valueOf("p")
XCTAssertTrue(p1.equals(p2))
XCTAssertTrue(p1 == p2)
}
func testDivSemantics()throws {
let div = try Tag.valueOf("div")
XCTAssertTrue(div.isBlock())
XCTAssertTrue(div.formatAsBlock())
}
func testPSemantics()throws {
let p = try Tag.valueOf("p")
XCTAssertTrue(p.isBlock())
XCTAssertFalse(p.formatAsBlock())
}
func testImgSemantics()throws {
let img = try Tag.valueOf("img")
XCTAssertTrue(img.isInline())
XCTAssertTrue(img.isSelfClosing())
XCTAssertFalse(img.isBlock())
}
func testDefaultSemantics()throws {
let foo = try Tag.valueOf("FOO") // not defined
let foo2 = try Tag.valueOf("FOO")
XCTAssertEqual(foo, foo2)
XCTAssertTrue(foo.isInline())
XCTAssertTrue(foo.formatAsBlock())
}
func testValueOfChecksNotEmpty() {
XCTAssertThrowsError(try Tag.valueOf(" "))
}
static var allTests = {
return [
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testIsCaseSensitive", testIsCaseSensitive),
("testCanBeInsensitive", testCanBeInsensitive),
("testTrims", testTrims),
("testEquality", testEquality),
("testDivSemantics", testDivSemantics),
("testPSemantics", testPSemantics),
("testImgSemantics", testImgSemantics),
("testDefaultSemantics", testDefaultSemantics),
("testValueOfChecksNotEmpty", testValueOfChecksNotEmpty)
]
}()
}
| mit | a6e9b49b0893c7248e43d98f9e099b7c | 27.979167 | 114 | 0.632638 | 4.234399 | false | true | false | false |
huonw/swift | test/SILGen/opaque_values_silgen_lib.swift | 3 | 4323 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
protocol EmptyP {}
struct String { var ptr: Builtin.NativeObject }
// Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil hidden @$Ss21s010______PAndS_casesyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type
// CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK: destroy_value [[EAPPLY]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '$Ss21s010______PAndS_casesyyF'
func s010______PAndS_cases() {
_ = PAndSEnum.A
}
// Test emitBuiltinReinterpretCast.
// ---
// CHECK-LABEL: sil hidden @$Ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T,
// CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[ARG]] : $T to $U
// CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U
// CHECK-NOT: destroy_value [[COPY]] : $T
// CHECK: return [[RET]] : $U
// CHECK-LABEL: } // end sil function '$Ss21s020__________bitCast_2toq_x_q_mtr0_lF'
func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U {
return Builtin.reinterpretCast(x)
}
// Test emitBuiltinCastReference
// ---
// CHECK-LABEL: sil hidden @$Ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : @trivial $@thick U.Type):
// CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T
// CHECK: [[SRC:%.*]] = alloc_stack $T
// CHECK: store [[COPY]] to [init] [[SRC]] : $*T
// CHECK: [[DEST:%.*]] = alloc_stack $U
// CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U
// CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U
// CHECK: dealloc_stack [[DEST]] : $*U
// CHECK: dealloc_stack [[SRC]] : $*T
// CHECK-NOT: destroy_value [[ARG]] : $T
// CHECK: return [[LOAD]] : $U
// CHECK-LABEL: } // end sil function '$Ss21s030__________refCast_2toq_x_q_mtr0_lF'
func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
// Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil shared [transparent] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
// CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type):
// CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String)
// CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String)
// CHECK: return [[RETVAL]] : $PAndSEnum
// CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF'
// CHECK-LABEL: sil shared [transparent] [thunk] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum {
// CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type):
// CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$Ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]])
// CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc'
enum PAndSEnum { case A(EmptyP, String) }
| apache-2.0 | e7fc386deaa2d4abbe9bd03237864bfa | 55.881579 | 267 | 0.633356 | 3.230942 | false | false | false | false |
sumitlni/LNITaskList | LNITaskListDemo/ViewController.swift | 1 | 2975 | //
// ViewController.swift
// LNITaskListDemo
//
// Created by Sumit Chawla on 6/9/16.
//
// The MIT License (MIT)
//
// Copyright © 2016 Loud Noise Inc.
//
// 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 ViewController: UIViewController {
@IBOutlet weak var switch1: UISwitch!
@IBOutlet weak var switch2: UISwitch!
@IBOutlet weak var switch3: UISwitch!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.textView.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func log(text:String) {
let newText = "\(self.textView.text)\n\(text)"
self.textView.text = newText
}
func asyncTaskWithAnswer(name:String, taskList:LNITaskList, answer:Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.log("Now executing \(name) with result = \(answer)")
taskList.markDone(answer)
}
}
@IBAction func startTasks(sender: AnyObject) {
textView.text = ""
// Form the task list
let taskList = LNITaskList()
taskList.onSuccess { () in
self.log("Success!")
}.onFailure {
self.log("Failed!")
}.addStep {
self.asyncTaskWithAnswer("Task 1", taskList: taskList, answer: self.switch1.on)
}.addStep {
self.asyncTaskWithAnswer("Task 2", taskList: taskList, answer: self.switch2.on)
}.addStep {
self.asyncTaskWithAnswer("Task 3", taskList: taskList, answer: self.switch3.on)
}.start()
}
}
| mit | b29a0220379681d3c6cc145df3b7ccaa | 36.175 | 95 | 0.647613 | 4.465465 | false | false | false | false |
ello/ElloOSSUIFonts | Pod/Classes/ElloOSSUIFonts.swift | 1 | 1912 | extension UIFont {
public class func loadFonts() {}
public class func defaultFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func defaultBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func defaultItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func regularFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func regularBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func regularBlackFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func regularBlackItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func regularLightFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func editorFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func editorItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func editorBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func editorBoldItalicFont(_ size: CGFloat = 14) -> UIFont {
let descriptor = UIFont.systemFont(ofSize: size).fontDescriptor.withSymbolicTraits([.traitBold, .traitItalic])
return UIFont(descriptor: descriptor!, size: size)
}
public class func printAvailableFonts() {
for familyName in UIFont.familyNames
{
print("Family Name: \(familyName)")
for fontName in UIFont.fontNames(forFamilyName: familyName)
{
print("--Font Name: \(fontName)")
}
}
}
}
| mit | 9d34897c680bb8de222b0a3e8aced5d0 | 60.677419 | 125 | 0.685146 | 4.674817 | false | false | false | false |
admkopec/BetaOS | Kernel/Modules/ACPI/AML/Type2Opcodes.swift | 1 | 30713 | //
// Type2Opcodes.swift
// Kernel
//
// Created by Adam Kopeć on 1/26/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
// ACPI Type 2 Opcodes
protocol AMLType2Opcode: AMLTermObj, AMLTermArg {
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg
}
private let AMLIntegerFalse = AMLInteger(0)
private let AMLIntegerTrue = AMLInteger(1)
private func AMLBoolean(_ bool: Bool) -> AMLInteger {
return bool ? AMLIntegerTrue : AMLIntegerFalse
}
func operandAsInteger(operand: AMLOperand, context: inout ACPI.AMLExecutionContext) -> AMLInteger {
guard let result = operand.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\(operand) does not evaluate to an integer")
}
return result.value
}
// AMLType2Opcode
typealias AMLTimeout = AMLWordData
struct AMLDefAcquire: AMLType2Opcode {
// AcquireOp MutexObject Timeout
let mutex: AMLMutexObject
let timeout: AMLTimeout
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLOperand = AMLTermArg // => Integer
struct AMLDefAdd: AMLType2Opcode {
// AddOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let result = AMLIntegerData(op1 + op2)
return result
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefAnd: AMLType2Opcode {
// AndOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let result = AMLIntegerData(op1 & op2)
target.updateValue(to: result, context: &context)
return result
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLBuffer: AMLBuffPkgStrObj, AMLType2Opcode, AMLComputationalData {
var isReadOnly: Bool { return true }
// BufferOp PkgLength BufferSize ByteList
let size: AMLTermArg // => Integer
let value: AMLByteList
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
guard let result = size.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\(size) does not evaluate to an integer")
}
return result
}
}
typealias AMLData = AMLTermArg // => ComputationalData
struct AMLDefConcat: AMLType2Opcode {
// ConcatOp Data Data Target
let data1: AMLData
let data2: AMLData
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLBufData = AMLTermArg // =>
struct AMLDefConcatRes: AMLType2Opcode {
// ConcatResOp BufData BufData Target
let data1: AMLBufData
let data2: AMLBufData
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
guard let buf1 = data1.evaluate(context: &context) as? AMLBuffer,
let buf2 = data2.evaluate(context: &context) as? AMLBuffer else {
fatalError("cant evaulate to buffers")
}
// Fixme, iterate validating the individual entries and add an endtag
let result = Array(buf1.value[0..<buf1.value.count-2]) + buf2.value
let newBuffer = AMLBuffer(size: AMLIntegerData(AMLInteger(result.count)), value: result)
target.updateValue(to: newBuffer, context: &context)
return newBuffer
}
}
///ObjReference := TermArg => ObjectReference | String
//ObjectReference := Integer
struct AMLDefCondRefOf: AMLType2Opcode {
// CondRefOfOp SuperName Target
let name: AMLSuperName
var target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let n = name as? AMLNameString else {
return AMLIntegerData(0)
}
guard let (obj, _) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: n) else {
return AMLIntegerData(0)
}
// FIXME, do the store into the target
//target.value = obj
kprint(String(describing: obj))
return AMLIntegerData(1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefCopyObject: AMLType2Opcode {
// CopyObjectOp TermArg SimpleName
let object: AMLTermArg
let target: AMLSimpleName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefDecrement: AMLType2Opcode {
// DecrementOp SuperName
let target: AMLSuperName
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let result = target.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\target) is not an integer")
}
return AMLIntegerData(result.value &- 1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefDerefOf: AMLType2Opcode, AMLType6Opcode {
// DerefOfOp ObjReference
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("Cant update \(self) to \(to)")
}
}
typealias AMLDividend = AMLTermArg // => Integer
typealias AMLDivisor = AMLTermArg // => Integer
struct AMLDefDivide: AMLType2Opcode {
// DivideOp Dividend Divisor Remainder Quotient
let dividend: AMLDividend
let divisor: AMLDivisor
let remainder: AMLTarget
let quotient: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let d1 = operandAsInteger(operand: dividend, context: &context)
let d2 = operandAsInteger(operand: divisor, context: &context)
guard d2 != 0 else {
fatalError("divisor is 0")
}
let q = AMLIntegerData((d1 / d2))
return q
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let d1 = operandAsInteger(operand: dividend, context: &context)
let d2 = operandAsInteger(operand: divisor, context: &context)
guard d2 != 0 else {
fatalError("divisor is 0")
}
let q = AMLIntegerData((d1 / d2))
let r = AMLIntegerData((d1 % d2))
quotient.updateValue(to: q, context: &context)
remainder.updateValue(to: r, context: &context)
return q
}
}
struct AMLDefFindSetLeftBit: AMLType2Opcode {
// FindSetLeftBitOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefFindSetRightBit: AMLType2Opcode {
// FindSetRightBitOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLBCDValue = AMLTermArg //=> Integer
struct AMLDefFromBCD: AMLType2Opcode {
// FromBCDOp BCDValue Target
let value: AMLBCDValue
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefIncrement: AMLType2Opcode {
// IncrementOp SuperName
let target: AMLSuperName
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let result = target.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\target) is not an integer")
}
return AMLIntegerData(result.value &+ 1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefIndex: AMLType2Opcode, AMLType6Opcode {
// IndexOp BuffPkgStrObj IndexValue Target
let object: AMLBuffPkgStrObj // => Buffer, Package or String
let index: AMLTermArg // => Integer
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("Cant update \(self) to \(to)")
}
}
struct AMLDefLAnd: AMLType2Opcode {
// LandOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 != 0 && op2 != 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLEqual: AMLType2Opcode {
// LequalOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 == op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLGreater: AMLType2Opcode {
// LgreaterOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 < op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLGreaterEqual: AMLType2Opcode {
// LgreaterEqualOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 >= op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLLess: AMLType2Opcode {
// LlessOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 < op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLLessEqual: AMLType2Opcode {
// LlessEqualOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 <= op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLNot: AMLType2Opcode {
// LnotOp Operand
let operand: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let value = AMLBoolean(op == 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLNotEqual: AMLType2Opcode {
// LnotEqualOp Operand Operand
let operand1: AMLTermArg
let operand2: AMLTermArg
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefLoadTable: AMLType2Opcode {
// LoadTableOp TermArg TermArg TermArg TermArg TermArg TermArg
let arg1: AMLTermArg
let arg2: AMLTermArg
let arg3: AMLTermArg
let arg4: AMLTermArg
let arg5: AMLTermArg
let arg6: AMLTermArg
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefLOr: AMLType2Opcode {
// LorOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 != 0 || op2 != 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefMatch: AMLType2Opcode {
enum AMLMatchOpcode: AMLByteData {
case mtr = 0
case meq = 1
case mle = 2
case mlt = 3
case mge = 4
case mgt = 5
}
// MatchOp SearchPkg MatchOpcode Operand MatchOpcode Operand StartIndex
let package: AMLTermArg // => Package
let matchOpcode1: AMLMatchOpcode
let operand1: AMLOperand
let matchOpcode2: AMLMatchOpcode
let operand2: AMLOperand
let startIndex: AMLTermArg // => Integer
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMid: AMLType2Opcode {
// MidOp MidObj TermArg TermArg Target
let obj: AMLTermArg // => Buffer | String
let arg1: AMLTermArg
let arg2: AMLTermArg
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMod: AMLType2Opcode {
// ModOp Dividend Divisor Target
let dividend: AMLDividend
let divisor: AMLDivisor
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMultiply: AMLType2Opcode {
// MultiplyOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNAnd: AMLType2Opcode {
// NandOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNOr: AMLType2Opcode {
// NorOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNot: AMLType2Opcode {
// NotOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
return AMLIntegerData(~op)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefObjectType: AMLType2Opcode {
// ObjectTypeOp <SimpleName | DebugObj | DefRefOf | DefDerefOf | DefIndex>
let object: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefOr: AMLType2Opcode {
// OrOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
return AMLIntegerData(op1 | op2)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
typealias AMLPackageElement = AMLDataRefObject
typealias AMLPackageElementList = [AMLPackageElement]
struct AMLDefPackage: AMLBuffPkgStrObj, AMLType2Opcode, AMLDataObject, AMLTermArg {
func canBeConverted(to: AMLDataRefObject) -> Bool {
return false
}
var isReadOnly: Bool { return false }
// PackageOp PkgLength NumElements PackageElementList
//let pkgLength: AMLPkgLength
let numElements: AMLByteData
let elements: AMLPackageElementList
var value: AMLPackageElementList { return elements }
let asInteger: AMLInteger? = nil
let resultAsInteger: AMLInteger? = nil
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLDefVarPackage = AMLDataRefObject
struct AMLDefRefOf: AMLType2Opcode, AMLType6Opcode {
// RefOfOp SuperName
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("cant update \(self) to \(to)")
}
}
typealias AMLShiftCount = AMLTermArg //=> Integer
struct AMLDefShiftLeft: AMLType2Opcode {
// ShiftLeftOp Operand ShiftCount Target
let operand: AMLOperand
let count: AMLShiftCount
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let shiftCount = operandAsInteger(operand: count, context: &context)
let value = op << shiftCount
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefShiftRight: AMLType2Opcode {
// ShiftRightOp Operand ShiftCount Target
let operand: AMLOperand
let count: AMLShiftCount
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let shiftCount = operandAsInteger(operand: count, context: &context)
let value = op >> shiftCount
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefSizeOf: AMLType2Opcode {
// SizeOfOp SuperName
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg{
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefStore: AMLType2Opcode {
// StoreOp TermArg SuperName
let arg: AMLTermArg
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
var source = arg
if let args2 = arg as? AMLArgObj {
guard args2.argIdx < context.args.count else {
fatalError("Tried to access arg \(args2.argIdx) but only have \(context.args.count) args")
}
source = context.args[Int(args2.argIdx)]
}
let v = source.evaluate(context: &context)
if let obj = name as? AMLDataRefObject {
//obj.updateValue(to: source, context: &context)
//return source
obj.updateValue(to: v, context: &context)
return v
}
if let localObj = name as? AMLLocalObj {
context.localObjects[localObj.argIdx] = v
return v
}
guard let sname = name as? AMLNameString else {
throw AMLError.invalidData(reason: "\(name) is not a string")
}
guard let (dest, fullPath) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: sname) else {
fatalError("Can't find \(sname)")
}
// guard let target = dest.object as? AMLDataRefObject else {
// fatalError("dest not an AMLDataRefObject")
// }
// FIXME: Shouldn't be here
//guard var namedObject = dest.object else {
// fatalError("Cant find namedObj: \(sname)")
//}
// guard source.canBeConverted(to: target) else {
// fatalError("\(source) can not be converted to \(target)")
// }
let resolvedScope = AMLNameString(fullPath).removeLastSeg()
var tmpContext = ACPI.AMLExecutionContext(scope: resolvedScope,
args: context.args,
globalObjects: context.globalObjects)
if let no = dest.object as? AMLNamedObj {
no.updateValue(to: source, context: &tmpContext)
}
else if let no = dest.object as? AMLDataRefObject {
no.updateValue(to: source, context: &tmpContext)
} else if let no = dest.object as? AMLDefName {
no.value.updateValue(to: source, context: &tmpContext)
} else {
fatalError("Cant store \(source) into \(String(describing: dest.object))")
}
return v
}
}
struct AMLDefSubtract: AMLType2Opcode {
// SubtractOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = op1 &- op2
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
//target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefTimer: AMLType2Opcode {
// TimerOp
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToBCD: AMLType2Opcode {
// ToBCDOp Operand Target
let operand: AMLOperand
let target: AMLTarget
var description: String { return "ToBCD(\(operand), \(target)" }
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToBuffer: AMLType2Opcode {
// ToBufferOp Operand Target
let operand: AMLOperand
let target: AMLTarget
var description: String { return "ToBuffer(\(operand), \(target)" }
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToDecimalString: AMLType2Opcode {
// ToDecimalStringOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToHexString: AMLType2Opcode {
// ToHexStringOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToInteger: AMLType2Opcode {
// ToIntegerOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToString: AMLType2Opcode {
// ToStringOp TermArg LengthArg Target
let arg: AMLTermArg
let length: AMLTermArg // => Integer
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefWait: AMLType2Opcode {
// WaitOp EventObject Operand
let object: AMLEventObject
let operand: AMLOperand
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefXor: AMLType2Opcode {
// XorOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
var target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = op1 ^ op2
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg{
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLMethodInvocation: AMLType2Opcode {
// NameString TermArgList
let method: AMLNameString
let args: AMLTermArgList
init?(method: AMLNameString, args: AMLTermArgList) /*throws*/ {
guard args.count < 8 else {
// throw AMLError.invalidData(reason: "More than 7 args")
return nil
}
self.method = method
self.args = args
}
init?(method: AMLNameString, _ args: AMLTermArg...) /*throws*/ {
/*try*/ self.init(method: method, args: args)
}
private func _invokeMethod(invocation: AMLMethodInvocation,
context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg? {
let name = invocation.method.value
if name == "\\_OSI" || name == "_OSI" {
return try ACPI._OSI_Method(invocation.args)
}
guard let (obj, fullPath) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: invocation.method) else {
throw AMLError.invalidMethod(reason: "Cant find method: \(name)")
}
guard let method = obj.object as? AMLMethod else {
throw AMLError.invalidMethod(reason: "\(name) [\(String(describing:obj.object))] is not an AMLMethod")
}
let termList = try method.termList()
let newArgs = invocation.args.map { $0.evaluate(context: &context) }
var newContext = ACPI.AMLExecutionContext(scope: AMLNameString(fullPath),
args: newArgs,
globalObjects: context.globalObjects)
try newContext.execute(termList: termList)
context.returnValue = newContext.returnValue
return context.returnValue
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let returnValue = try _invokeMethod(invocation: self, context: &context)
context.returnValue = returnValue
guard let retval = returnValue else {
return AMLIntegerData(0)
}
return retval
}
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
do {
if let result = try _invokeMethod(invocation: self, context: &context) {
return result
}
} catch {
fatalError("cant evaluate: \(self): \(error)")
}
fatalError("Failed to evaluate \(self)")
}
}
| apache-2.0 | 92a4ecd5a66c0373f5c7e91b3f2cbad8 | 28.303435 | 134 | 0.651319 | 4.752399 | false | false | false | false |
austinzheng/swift | stdlib/public/core/StringComparable.swift | 3 | 2787 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension StringProtocol {
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func == <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .equal)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func != <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs == rhs)
}
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func < <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .less)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func > <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return rhs < lhs
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func <= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(rhs < lhs)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func >= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs < rhs)
}
}
extension String : Equatable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func == (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .equal)
}
}
extension String : Comparable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func < (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .less)
}
}
extension Substring : Equatable {}
| apache-2.0 | 7a3190b8671dbad3ea29a3f2df379514 | 32.578313 | 80 | 0.63258 | 4.184685 | false | false | false | false |
nutts/SwiftForms | SwiftForms/SwiftyJSON.swift | 1 | 36126 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error.memory = aError
}
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
:param: jsonDictionary A Swift dictionary of JSON objects
:returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: AnyObject]()
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
private var rawArray: [AnyObject] = []
private var rawDictionary: [String : AnyObject] = [:]
private var rawString: String = ""
private var rawNumber: NSNumber = 0
private var rawNull: NSNull = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError? = nil
/// Object in JSON
public var object: AnyObject {
get {
switch self.type {
case .Array:
return self.rawArray
case .Dictionary:
return self.rawDictionary
case .String:
return self.rawString
case .Number:
return self.rawNumber
case .Bool:
return self.rawNumber
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
self.rawNumber = number
case let string as String:
_type = .String
self.rawString = string
case _ as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
self.rawArray = array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
self.rawDictionary = dictionary
default:
_type = .Unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
@available(*, unavailable, renamed="null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
// MARK: - CollectionType, SequenceType, Indexable
extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
public typealias Generator = JSONGenerator
public typealias Index = JSONIndex
public var startIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.startIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
default:
return JSONIndex()
}
}
public var endIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.endIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
default:
return JSONIndex()
}
}
public subscript (position: JSON.Index) -> JSON.Generator.Element {
switch self.type {
case .Array:
return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
case .Dictionary:
let (key, value) = self.rawDictionary[position.dictionaryIndex!]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return self.rawArray.isEmpty
case .Dictionary:
return self.rawDictionary.isEmpty
default:
return true
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
switch self.type {
case .Array:
return self.rawArray.count
case .Dictionary:
return self.rawDictionary.count
default:
return 0
}
}
public func underestimateCount() -> Int {
switch self.type {
case .Array:
return self.rawArray.underestimateCount()
case .Dictionary:
return self.rawDictionary.underestimateCount()
default:
return 0
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of JSON.
*/
public func generate() -> JSON.Generator {
return JSON.Generator(self)
}
}
public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
let arrayIndex: Int?
let dictionaryIndex: DictionaryIndex<String, AnyObject>?
let type: Type
init(){
self.arrayIndex = nil
self.dictionaryIndex = nil
self.type = .Unknown
}
init(arrayIndex: Int) {
self.arrayIndex = arrayIndex
self.dictionaryIndex = nil
self.type = .Array
}
init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
self.arrayIndex = nil
self.dictionaryIndex = dictionaryIndex
self.type = .Dictionary
}
public func successor() -> JSONIndex {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.arrayIndex!.successor())
case .Dictionary:
return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
default:
return JSONIndex()
}
}
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex == rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex == rhs.dictionaryIndex
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex < rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex < rhs.dictionaryIndex
default:
return false
}
}
public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex <= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex <= rhs.dictionaryIndex
default:
return false
}
}
public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex >= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex >= rhs.dictionaryIndex
default:
return false
}
}
public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex > rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex > rhs.dictionaryIndex
default:
return false
}
}
public struct JSONGenerator : GeneratorType {
public typealias Element = (String, JSON)
private let type: Type
private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
private var arrayGenerate: IndexingGenerator<[AnyObject]>?
private var arrayIndex: Int = 0
init(_ json: JSON) {
self.type = json.type
if type == .Array {
self.arrayGenerate = json.rawArray.generate()
}else {
self.dictionayGenerate = json.rawDictionary.generate()
}
}
public mutating func next() -> JSONGenerator.Element? {
switch self.type {
case .Array:
if let o = self.arrayGenerate!.next() {
return (String(self.arrayIndex++), JSON(o))
} else {
return nil
}
case .Dictionary:
if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() {
return (k, JSON(v))
} else {
return nil
}
default:
return nil
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol JSONSubscriptType {}
extension Int: JSONSubscriptType {}
extension String: JSONSubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .Array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .Dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .Dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: JSONSubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.removeAtIndex(0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
var d = dictionary
d[element.0] = element.1
return d
})
}
}
extension JSON: Swift.ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: Swift.NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) as? String
} catch _ {
return nil
}
case .String:
return self.rawString
case .Number:
return self.rawNumber.stringValue
case .Bool:
return self.rawNumber.boolValue.description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.Printable, Swift.DebugPrintable {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .Dictionary {
return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
var d = dictionary
d[element.0] = JSON(element.1)
return d
}
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: Swift.BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.rawNumber.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.rawNumber
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as! NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber == rhs.rawNumber
case (.String, .String):
return lhs.rawString == rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber <= rhs.rawNumber
case (.String, .String):
return lhs.rawString <= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber >= rhs.rawNumber
case (.String, .String):
return lhs.rawString >= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber > rhs.rawNumber
case (.String, .String):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber < rhs.rawNumber
case (.String, .String):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Swift.Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
|| (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
} | mit | 8c1299ae7078ed64cda0c298ff236352 | 25.920268 | 264 | 0.536124 | 4.806546 | false | false | false | false |
0x0c/RDImageViewerController | RDImageViewerController/Classes/View/PagingView/PagingView.swift | 1 | 13600 | //
// RDPagingView.swift
// Pods-RDImageViewerController
//
// Created by Akira Matsuda on 2019/04/07.
//
import UIKit
public protocol PagingViewDataSource {
func pagingView(pagingView: PagingView, preloadItemAt index: Int)
func pagingView(pagingView: PagingView, cancelPreloadingItemAt index: Int)
}
public protocol PagingViewDelegate {
func pagingView(pagingView: PagingView, willChangeViewSize size: CGSize, duration: TimeInterval, visibleViews: [UIView])
func pagingView(pagingView: PagingView, willChangeIndexTo index: PagingView.VisibleIndex, currentIndex: PagingView.VisibleIndex)
func pagingView(pagingView: PagingView, didChangeIndexTo index: PagingView.VisibleIndex)
func pagingView(pagingView: PagingView, didScrollToPosition position: CGFloat)
func pagingView(pagingView: PagingView, didEndDisplaying view: UIView & PageViewRepresentation, index: Int)
func pagingViewWillBeginDragging(pagingView: PagingView)
func pagingViewDidEndDragging(pagingView: PagingView, willDecelerate decelerate: Bool)
func pagingViewWillBeginDecelerating(pagingView: PagingView)
func pagingViewDidEndDecelerating(pagingView: PagingView)
func pagingViewDidEndScrollingAnimation(pagingView: PagingView)
}
open class PagingView: UICollectionView {
public enum ForwardDirection {
case right
case left
case up
case down
}
public enum VisibleIndex {
case single(index: Int)
case double(indexes: [Int])
}
public weak var pagingDataSource: (PagingViewDataSource & UICollectionViewDataSource)?
public weak var pagingDelegate: (PagingViewDelegate & UICollectionViewDelegate & UICollectionViewDelegateFlowLayout)?
public var numberOfPages: Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(self, numberOfItemsInSection: 0)
}
public var preloadCount: Int = 3
private var _isRotating: Bool = false
public func beginRotate() {
_isRotating = true
}
public func endRotate() {
_isRotating = false
}
public func beginChangingBarState() {
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.ignoreTargetContentOffset = true
}
}
public func endChangingBarState() {
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.ignoreTargetContentOffset = false
}
}
public var isDoubleSpread: Bool = false {
didSet {
currentPageIndex = currentPageIndex.convert(double: isDoubleSpread)
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.isDoubleSpread = isDoubleSpread
}
}
}
func setLayoutIndex(_ index: VisibleIndex) {
if let flowLayout = collectionViewLayout as? PagingViewFlowLayout {
flowLayout.currentPageIndex = index
}
}
public var scrollDirection: ForwardDirection
private var _currentPageIndex: VisibleIndex = .single(index: 0)
public var currentPageIndex: VisibleIndex {
set {
_currentPageIndex = newValue
scrollTo(index: newValue.primaryIndex())
}
get {
if isDoubleSpread {
return .double(indexes: visiblePageIndexes)
}
return _currentPageIndex
}
}
public var visiblePageIndexes: [Int] {
indexPathsForVisibleItems.map { (indexPath) -> Int in
Int(indexPath.row)
}
}
public var isLegacyLayoutSystem: Bool {
if #available(iOS 11.0, *) {
return false
}
else if scrollDirection == .left {
return true
}
else {
return false
}
}
public init(frame: CGRect, forwardDirection: ForwardDirection) {
scrollDirection = forwardDirection
if forwardDirection == .left {
super.init(frame: frame, collectionViewLayout: PagingViewRightToLeftFlowLayout())
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
else {
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
else if forwardDirection == .right {
super.init(frame: frame, collectionViewLayout: PagingViewHorizontalFlowLayout())
}
else if forwardDirection == .up {
super.init(frame: frame, collectionViewLayout: PagingViewBottomToTopLayout())
}
else { // .down
super.init(frame: frame, collectionViewLayout: PagingViewVerticalFlowLayout())
}
delegate = self
dataSource = self
}
@available(*, unavailable)
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func scrollTo(index: Int, animated: Bool = false) {
if index > numberOfPages - 1 || index < 0 {
return
}
var position: UICollectionView.ScrollPosition {
if scrollDirection.isHorizontal {
if isDoubleSpread {
if index % 2 == 0 {
return .left
}
return .right
}
return .centeredHorizontally
}
else {
return .centeredVertically
}
}
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.currentPageIndex = currentPageIndex
}
scrollToItem(at: IndexPath(row: index, section: 0), at: position, animated: animated)
}
public func resizeVisiblePages() {
collectionViewLayout.invalidateLayout()
for cell in visibleCells {
if let view = cell as? PageViewRepresentation {
view.resize(pageIndex: cell.rd_pageIndex, scrollDirection: scrollDirection, traitCollection: traitCollection, isDoubleSpread: isDoubleSpread)
}
}
}
public func changeDirection(_ forwardDirection: ForwardDirection) {
scrollDirection = forwardDirection
if forwardDirection == .left {
collectionViewLayout = PagingViewRightToLeftFlowLayout()
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
else {
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
else {
transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
if forwardDirection == .right {
collectionViewLayout = PagingViewHorizontalFlowLayout()
}
else if forwardDirection == .up {
collectionViewLayout = PagingViewBottomToTopLayout()
}
else { // .down
collectionViewLayout = PagingViewVerticalFlowLayout()
}
}
reloadData()
}
override open func reloadData() {
collectionViewLayout.invalidateLayout()
super.reloadData()
}
override open func layoutSubviews() {
beginChangingBarState()
super.layoutSubviews()
endChangingBarState()
if isLegacyLayoutSystem {
for cell in visibleCells {
cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
}
}
extension PagingView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if _isRotating {
return
}
guard let pagingDelegate = pagingDelegate else {
return
}
let position = scrollView.contentOffset.x / scrollView.frame.width
if scrollDirection.isHorizontal {
pagingDelegate.pagingView(pagingView: self, didScrollToPosition: position)
if isDoubleSpread {
let newIndex: VisibleIndex = .double(indexes: visiblePageIndexes)
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
else {
let to = Int(position + 0.5)
let newIndex: VisibleIndex = to.rd_single()
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
}
else {
pagingDelegate.pagingView(pagingView: self, didScrollToPosition: scrollView.contentOffset.y)
if let index = indexPathsForVisibleItems.sorted().rd_middle {
let to = index.row
let newIndex: VisibleIndex = to.rd_convert(double: isDoubleSpread)
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
}
setLayoutIndex(_currentPageIndex)
}
public func scrollViewWillBeginDragging(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewWillBeginDragging(pagingView: self)
}
}
public func scrollViewDidEndDragging(_: UIScrollView, willDecelerate decelerate: Bool) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndDragging(pagingView: self, willDecelerate: decelerate)
if decelerate == false {
pagingDelegate.pagingView(pagingView: self, didChangeIndexTo: currentPageIndex)
}
}
}
public func scrollViewWillBeginDecelerating(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewWillBeginDecelerating(pagingView: self)
}
}
public func scrollViewDidEndDecelerating(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndDecelerating(pagingView: self)
pagingDelegate.pagingView(pagingView: self, didChangeIndexTo: currentPageIndex)
}
}
public func scrollViewDidEndScrollingAnimation(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndScrollingAnimation(pagingView: self)
}
}
}
extension PagingView: UICollectionViewDelegate {}
extension PagingView: UICollectionViewDataSource {
override open func numberOfItems(inSection section: Int) -> Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(self, numberOfItemsInSection: section)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(collectionView, numberOfItemsInSection: section)
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let pagingDataSource = pagingDataSource else {
return UICollectionViewCell(frame: CGRect.zero)
}
let cell = pagingDataSource.collectionView(collectionView, cellForItemAt: indexPath)
cell._rd_pageIndex = indexPath.row
if isLegacyLayoutSystem {
cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
// prefetch
let prefetchStartIndex = max(0, indexPath.row - preloadCount)
let prefetchEndIndex = min(numberOfPages - 1, indexPath.row + preloadCount)
for i in prefetchStartIndex ..< prefetchEndIndex {
pagingDataSource.pagingView(pagingView: self, preloadItemAt: i)
}
// cancel
let cancelStartIndex = min(max(0, indexPath.row - preloadCount - 1), numberOfPages - 1)
let cancelEndIndex = max(min(numberOfPages - 1, indexPath.row + preloadCount + 1), 0)
for i in cancelStartIndex ..< prefetchStartIndex {
pagingDataSource.pagingView(pagingView: self, cancelPreloadingItemAt: i)
}
for i in prefetchEndIndex ..< cancelEndIndex {
pagingDataSource.pagingView(pagingView: self, cancelPreloadingItemAt: i)
}
return cell
}
public func collectionView(_: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let pagingDelegate = pagingDelegate, let view = cell as? (UIView & PageViewRepresentation) else {
return
}
pagingDelegate.pagingView(pagingView: self, didEndDisplaying: view, index: indexPath.row)
}
}
extension PagingView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let pagingDelegate = pagingDelegate else {
return .zero
}
return pagingDelegate.collectionView?(
collectionView,
layout: collectionViewLayout,
sizeForItemAt: indexPath
) ?? .zero
}
}
| mit | 78a3f0e8be84598f60ebb898b5637503 | 35.363636 | 167 | 0.636544 | 5.928509 | false | false | false | false |
yaobanglin/viossvc | viossvc/Scenes/Order/CustomView/OrderListCell.swift | 1 | 4620 | //
// Created by yaowang on 2016/11/1.
// Copyright (c) 2016 ywwlcom.yundian. All rights reserved.
//
import UIKit
class OrderListCell : OEZTableViewCell {
@IBOutlet weak var headPicImageView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var serviceLabel: UILabel!
@IBOutlet weak var moneyLabel: UILabel!
@IBOutlet weak var orderTypeLabel: UILabel!
let statusDict:Dictionary<OrderStatus, String> = [.WaittingAccept: "等待接受",//等待服务者接受
.Reject: "已拒绝",//服务者拒绝
.Accept: "已接受",//服务者接受
.WaittingPay: "等待支付",//等待消费者支付
.Paid: "支付完成",//已经支付
.Cancel: "已取消",//取消
.OnGoing: "进行中",//订单进行中
.Completed: "已完成",//服务者确定完成
.InvoiceMaking: "已完成",
.InvoiceMaked: "已完成"]
let statusColor:Dictionary<OrderStatus, UIColor> = [.WaittingAccept: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.Reject: UIColor.redColor(),
.Accept: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.WaittingPay: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.Paid: UIColor.greenColor(),
.Cancel: UIColor.grayColor(),
.OnGoing: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),//订单进行中
.Completed: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.InvoiceMaking: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.InvoiceMaked: UIColor.greenColor()]
private var dateFormatter:NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
return dateFormatter
}()
@IBAction func didSelectAction(sender: AnyObject) {
didSelectRowAction(AppConst.Action.HandleOrder.rawValue, data: nil)
}
override func update(data: AnyObject!) {
let orderListModel = data as! OrderListModel
if orderListModel.from_url!.hasPrefix("http"){
headPicImageView.kf_setImageWithURL(NSURL(string: orderListModel.from_url!), placeholderImage: UIImage(named: "head_giry"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
orderTypeLabel.text = orderListModel.order_type == 0 ? "邀约" : "预约"
nicknameLabel.text = orderListModel.from_name
serviceLabel.text = orderListModel.service_name
moneyLabel.text = "\(Float(orderListModel.order_price)/100)元"
statusLabel.text = statusDict[OrderStatus(rawValue: (orderListModel.order_status))!]
statusLabel.textColor = statusColor[OrderStatus(rawValue: (orderListModel.order_status))!]
timeLabel.text = dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(orderListModel.start_time)))
// + "-" + dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(orderListModel.end_time)))
}
}
| apache-2.0 | fdc7aa825b04c59139592b6a00f257f1 | 53.268293 | 197 | 0.462022 | 5.611602 | false | false | false | false |
UniTN-Mechatronics/NoTremor | Container/MXChart.swift | 1 | 11230 | //
// MXChartView.swift
//
//
// Created by Paolo Bosetti on 07/10/14.
// Copyright (c) 2014 University of Trento. All rights reserved.
//
import UIKit
class MXDataSeries : NSObject {
var data = Array<CGPoint>()
var name = String()
var lineColor: UIColor = UIColor.redColor()
var lineWidth: CGFloat = 1
var capacity: Int? {
didSet {
if let capa = capacity {
data = Array(count: capa, repeatedValue: CGPointMake(0, 0))
self.data.reserveCapacity(capa + 1)
}
}
}
init(name: String) {
self.name = name
}
func count() -> Int {
return self.data.count
}
func randomFill(from: CGFloat, to: CGFloat, length: Int) {
var x, y: CGFloat
let rng = to - from
for i in 0...length {
x = from + (CGFloat(i) / CGFloat(length)) * rng
y = CGFloat(rand()) / CGFloat(RAND_MAX)
data.append(CGPointMake(x, y))
}
}
func append(x: CGFloat, y: CGFloat) {
let p = CGPointMake(x, y)
data.append(p)
if let capa = self.capacity {
data.removeRange(0..<1)
}
}
func addFromString(data: String, xCol: Int, yCol: Int) {
let lines = split(data) { $0 == "\n" }
for line in lines {
if !line.hasPrefix("#") {
let cols = split(line) { $0 == " " }
let x = cols[xCol] as NSString
let y = cols[yCol] as NSString
self.append(CGFloat(x.floatValue), y: CGFloat(y.floatValue))
}
}
}
func range() -> CGRect {
if let first = data.first {
let (y0, y1) = data.reduce((first.y, first.y)) { (min($0.0, $1.y), max($0.1, $1.y)) }
let (x0, x1) = (first.x, data.last!.x)
return CGRectMake(x0, y0, x1 - x0, y1 - y0)
}
else {
return CGRectMake(0, 0, 1, 1)
}
}
}
@IBDesignable class MXChart : UIView {
@IBInspectable var borderColor: UIColor = UIColor.blackColor()
@IBInspectable var fillColor: UIColor = UIColor.clearColor()
@IBInspectable var defaultPlotColor: UIColor = UIColor.redColor()
@IBInspectable var axesColor: UIColor = UIColor.grayColor()
@IBInspectable var textColor: UIColor = UIColor.blackColor()
@IBInspectable var borderWidth: CGFloat = 1
@IBInspectable var cornerRadius: CGFloat = 3
@IBInspectable var range: CGRect = CGRectMake(-1, -2, 20, 4) {
didSet {
if (self.range.width <= 0 || self.range.height <= 0) {
range = CGRectMake(range.origin.x, range.origin.y, 20, 4)
}
}
}
@IBInspectable var xLabel: String = "X axis"
@IBInspectable var yLabel: String = "Y axis"
@IBInspectable var showXAxis: Bool = true
@IBInspectable var showYAxis: Bool = true
@IBInspectable var showLegend: Bool = true
@IBInspectable var legendLineOffset: CGFloat = 15
var series = Dictionary<String,MXDataSeries>()
override func awakeFromNib() {
super.awakeFromNib()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
drawChartView(fillColor, rectangle: self.bounds, strokeWidth: borderWidth, radius: cornerRadius, xLabelText: xLabel, yLabelText: yLabel)
}
override func prepareForInterfaceBuilder() {
var x, s, c: CGFloat
let n = 100
series.removeAll(keepCapacity: false)
series["sin"] = MXDataSeries(name: "Sine")
series["sin"]!.lineColor = self.defaultPlotColor
series["sin"]!.lineWidth = 1
series["cos"] = MXDataSeries(name: "Cosine")
series["cos"]!.lineColor = UIColor.blueColor()
series["cos"]!.lineWidth = 1
for i in 0...n {
x = CGFloat(CGFloat(i) * CGFloat(range.width) / CGFloat(n) + CGFloat(range.origin.x))
s = CGFloat(sin(x))
c = CGFloat(cos(x))
series["sin"]?.append(x, y: s)
series["cos"]?.append(x, y: c)
}
series["rnd"] = MXDataSeries(name: "Random")
series["rnd"]?.randomFill(range.origin.x, to: range.origin.x + range.width, length: n)
series["rnd"]!.lineColor = UIColor.greenColor()
series["rnd"]!.lineWidth = 2
}
func reset() {
series.removeAll(keepCapacity: false)
}
func cleanup() {
for (n, s) in series {
s.data.removeAll(keepCapacity: true)
}
}
func remap(point: CGPoint, fromRect: CGRect, toRect: CGRect) -> CGPoint {
var p = CGPointMake(0, 0)
p.x = ((point.x - fromRect.origin.x) / fromRect.width) * toRect.width + toRect.origin.x
p.y = ((point.y - fromRect.origin.y) / fromRect.height) * toRect.height + toRect.origin.y
p.y = -p.y + toRect.height
return p
}
func addSeries(key: String, withLabel: String) {
series[key] = MXDataSeries(name: withLabel)
}
func counts() -> Dictionary<String, Int> {
var result = Dictionary<String, Int>()
for (k, v) in series {
result[k] = v.count()
}
return result
}
func addPointToSerie(serie: String, x: CGFloat, y: CGFloat) {
self.series[serie]?.append(x, y: y)
self.setNeedsDisplay()
}
func autoRescaleOnSerie(serie: String, xAxis: Bool, yAxis: Bool) {
autoRescaleOnSerie(serie, axes: (x: xAxis, y: yAxis))
}
func autoRescaleOnSerie(serie: String, axes: (x: Bool, y: Bool) ) {
let s = self.series[serie]
let rect = s!.range()
let (x, y, width, height) = (rect.origin.x, rect.origin.y, rect.width, rect.height)
switch axes {
case (true, true):
self.range.origin.x = x
self.range.size.width = width
self.range.origin.y = y
self.range.size.height = height
case (true, false):
self.range.origin.x = x
self.range.size.width = width
case (false, true):
self.range.origin.y = y
self.range.size.height = height
default:
return
}
self.setNeedsDisplay()
}
func drawPlot(inRect: CGRect, atOffset: CGPoint) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextTranslateCTM(context, atOffset.x, atOffset.y)
for (name, serie) in series {
var bezierPath = UIBezierPath()
if let startPoint = serie.data.first {
var p = remap(startPoint, fromRect: range, toRect: inRect)
bezierPath.moveToPoint(p)
for element in serie.data {
p = remap(element, fromRect: range, toRect: inRect)
bezierPath.addLineToPoint(p)
}
serie.lineColor.setStroke()
bezierPath.lineWidth = serie.lineWidth
bezierPath.stroke()
}
}
if (showXAxis) {
var xAxisPath = UIBezierPath()
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [4, 2], 2)
xAxisPath.moveToPoint(remap(CGPointMake(range.origin.x, 0), fromRect: range, toRect: inRect))
xAxisPath.addLineToPoint(remap(CGPointMake(range.origin.x + range.width, 0), fromRect: range, toRect: inRect))
self.axesColor.setStroke()
xAxisPath.stroke()
CGContextRestoreGState(context)
}
if (showYAxis) {
var yAxisPath = UIBezierPath()
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [4, 2], 2)
yAxisPath.moveToPoint(remap(CGPointMake(0, range.origin.y), fromRect: range, toRect: inRect))
yAxisPath.addLineToPoint(remap(CGPointMake(0, range.origin.y + range.height), fromRect: range, toRect: inRect))
self.axesColor.setStroke()
yAxisPath.stroke()
CGContextRestoreGState(context)
}
CGContextRestoreGState(context)
}
func drawChartView(fillColor: UIColor, rectangle: CGRect, strokeWidth: CGFloat, radius: CGFloat, xLabelText: String, yLabelText: String) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Variable Declarations
let labelHeight: CGFloat = 15
let rectWidth = rectangle.width - labelHeight - strokeWidth
let rectHeight = rectangle.height - labelHeight - strokeWidth
let rectOffset = CGPointMake(rectangle.origin.x, rectangle.origin.y + strokeWidth / 2.0)
//// Chart Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
let chartRect = CGRectMake(labelHeight + strokeWidth / 2.0, 0, rectWidth, rectHeight)
let chartPath = UIBezierPath(roundedRect: chartRect, cornerRadius: radius)
fillColor.setFill()
borderColor.setStroke()
chartPath.fill()
chartPath.lineWidth = strokeWidth
chartPath.stroke()
CGContextRestoreGState(context)
//// Draw data
drawPlot(chartRect, atOffset: rectOffset)
//// Label styles
let labelFont = UIFont(name: "Helvetica", size: 9)!
let cLabelStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
let lLabelStyle: NSMutableParagraphStyle = cLabelStyle.mutableCopy() as! NSMutableParagraphStyle
let rLabelStyle: NSMutableParagraphStyle = cLabelStyle.mutableCopy() as! NSMutableParagraphStyle
cLabelStyle.alignment = NSTextAlignment.Center
lLabelStyle.alignment = NSTextAlignment.Left
rLabelStyle.alignment = NSTextAlignment.Right
//// Legend drawing
if self.showLegend {
var offset: CGFloat = 0
let labelMargin = cornerRadius + borderWidth
CGContextSaveGState(context)
for (k, v) in self.series {
let text2Rect = CGRectMake(labelHeight + labelMargin, offset + labelMargin, 112, 20)
let text2FontAttributes = [NSFontAttributeName: UIFont(name: "Helvetica", size: 12)!, NSForegroundColorAttributeName: v.lineColor, NSParagraphStyleAttributeName: lLabelStyle]
v.name.drawInRect(text2Rect, withAttributes: text2FontAttributes);
offset += legendLineOffset
}
CGContextRestoreGState(context)
}
let labelColor = self.textColor
let labelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: cLabelStyle]
let minLabelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: lLabelStyle]
let maxLabelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: rLabelStyle]
//// xLabel Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
let xLabelRect = CGRectMake(labelHeight, rectHeight + strokeWidth / 2.0, rectWidth + strokeWidth, labelHeight)
NSString(string: xLabelText).drawInRect(xLabelRect, withAttributes: labelFontAttributes);
NSString(string: "\(range.origin.x)").drawInRect(xLabelRect, withAttributes: minLabelFontAttributes);
NSString(string: "\(range.origin.x + range.width)").drawInRect(xLabelRect, withAttributes: maxLabelFontAttributes);
CGContextRestoreGState(context)
//// yLabel Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let yLabelRect = CGRectMake(-rectHeight, 0, rectHeight, labelHeight)
NSString(string: yLabelText).drawInRect(yLabelRect, withAttributes: labelFontAttributes);
NSString(string: "\(range.origin.y)").drawInRect(yLabelRect, withAttributes: minLabelFontAttributes);
NSString(string: "\(range.origin.y + range.height)").drawInRect(yLabelRect, withAttributes: maxLabelFontAttributes);
CGContextRestoreGState(context)
}
}
| gpl-2.0 | e85e2975ac5ade393aef4aa552835c3e | 32.522388 | 182 | 0.673197 | 4.130195 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Home/TipOff/TipOffViewController.swift | 1 | 3809 | //
// TipOffViewController.swift
// HiPDA
//
// Created by leizh007 on 2017/7/22.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class TipOffViewController: BaseViewController {
@IBOutlet fileprivate weak var sendButton: UIButton!
@IBOutlet fileprivate weak var textView: UITextView!
@IBOutlet fileprivate weak var containerBottomConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var tipOffLabel: UILabel!
var user: User!
fileprivate var viewModel: TipOffViewModel!
override func viewDidLoad() {
super.viewDidLoad()
textView.layer.borderWidth = 1
textView.layer.borderColor = #colorLiteral(red: 0.831372549, green: 0.831372549, blue: 0.831372549, alpha: 1).cgColor
tipOffLabel.text = "举报: \(user.name)"
configureKeyboard()
viewModel = TipOffViewModel(user: user)
textView.rx.text.orEmpty.map { !$0.isEmpty }.bindTo(sendButton.rx.isEnabled).disposed(by: disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
show()
}
fileprivate func configureKeyboard() {
KeyboardManager.shared.keyboardChanged.drive(onNext: { [weak self, unowned keyboardManager = KeyboardManager.shared] transition in
guard let `self` = self else { return }
guard transition.toVisible.boolValue else {
self.containerBottomConstraint.constant = -176
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
return
}
let keyboardFrame = keyboardManager.convert(transition.toFrame, to: self.view)
self.containerBottomConstraint.constant = keyboardFrame.size.height
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}).addDisposableTo(disposeBag)
}
@IBAction fileprivate func cancelButtonPressed(_ sender: UIButton) {
dismiss()
}
@IBAction fileprivate func sendButtonPressed(_ sender: UIButton) {
guard let window = UIApplication.shared.windows.last else { return }
showPromptInformation(of: .loading("正在发送..."), in: window)
viewModel.sendMessage(textView.text ?? "") { [weak self] result in
self?.hidePromptInformation(in: window)
switch result {
case .success(let info):
self?.showPromptInformation(of: .success(info), in: window)
delay(seconds: 0.25) {
self?.dismiss()
}
case .failure(let error):
self?.showPromptInformation(of: .failure(error.localizedDescription), in: window)
}
}
}
@IBAction fileprivate func backgroundDidTapped(_ sender: Any) {
dismiss()
}
private func show() {
textView.becomeFirstResponder()
UIView.animate(withDuration: C.UI.animationDuration) {
self.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4)
}
}
private func dismiss() {
view.endEditing(true)
UIView.animate(withDuration: C.UI.animationDuration, animations: {
self.view.backgroundColor = .clear
}, completion: { _ in
self.presentingViewController?.dismiss(animated: false, completion: nil)
})
}
}
// MARK: - StoryboardLoadable
extension TipOffViewController: StoryboardLoadable { }
| mit | 0bc98cc8e02f9b6210b0cfa09084cdd3 | 36.94 | 138 | 0.636795 | 4.857875 | false | false | false | false |
domenicosolazzo/practice-swift | CoreData/Boosting Data Access in Table Views/Boosting Data Access in Table Views/AppDelegate.swift | 1 | 6471 | //
// AppDelegate.swift
// Boosting Data Access in Table Views
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Boosting_Data_Access_in_Table_Views" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Boosting_Data_Access_in_Table_Views", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Boosting_Data_Access_in_Table_Views.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | 8d5bf85ecd9879afacf5e10b218d9d2f | 52.479339 | 290 | 0.697883 | 5.686292 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Timer.swift | 30 | 4058 | //
// Timer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where E : RxAbstractInteger {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
}
extension ObservableType where E: RxAbstractInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType)
-> Observable<E> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
final fileprivate class TimerSink<O: ObserverType> : Sink<O> where O.E : RxAbstractInteger {
typealias Parent = Timer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.schedulePeriodic(0 as O.E, startAfter: _parent._dueTime, period: _parent._period!) { state in
self.forwardOn(.next(state))
return state &+ 1
}
}
}
final fileprivate class TimerOneOffSink<O: ObserverType> : Sink<O> where O.E : RxAbstractInteger {
typealias Parent = Timer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRelative(self, dueTime: _parent._dueTime) { (`self`) -> Disposable in
self.forwardOn(.next(0))
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
}
}
final fileprivate class Timer<E: RxAbstractInteger>: Producer<E> {
fileprivate let _scheduler: SchedulerType
fileprivate let _dueTime: RxTimeInterval
fileprivate let _period: RxTimeInterval?
init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) {
_scheduler = scheduler
_dueTime = dueTime
_period = period
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
if let _ = _period {
let sink = TimerSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
else {
let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
}
| mit | 2e94ae80fb4a0cca5341ad6945bf8243 | 35.54955 | 174 | 0.649002 | 4.745029 | false | false | false | false |
hughbe/swift | test/SILGen/specialize_attr.swift | 13 | 4910 | // RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s
// CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float)
// CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
@_specialize(where T == Int, U == Float)
func specializeThis<T, U>(_ t: T, u: U) {}
public protocol PP {
associatedtype PElt
}
public protocol QQ {
associatedtype QElt
}
public struct RR : PP {
public typealias PElt = Float
}
public struct SS : QQ {
public typealias QElt = Int
}
public struct GG<T : PP> {}
// CHECK-LABEL: public class CC<T> where T : PP {
// CHECK-NEXT: @_specialize(exported: false, kind: full, where T == RR, U == SS)
// CHECK-NEXT: @inline(never) public func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ
public class CC<T : PP> {
@inline(never)
@_specialize(where T == RR, U == SS)
public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4Thisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
// -----------------------------------------------------------------------------
// Test user-specialized subscript accessors.
public protocol TestSubscriptable {
associatedtype Element
subscript(i: Int) -> Element { get set }
}
public class ASubscriptable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
get {
return storage[i]
}
@_specialize(where Element == Int)
set(rhs) {
storage[i] = rhs
}
}
}
// ASubscriptable.subscript.getter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
// ASubscriptable.subscript.setter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
// ASubscriptable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr14ASubscriptableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
public class Addressable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
unsafeAddress {
return UnsafePointer<Element>(storage + i)
}
@_specialize(where Element == Int)
unsafeMutableAddress {
return UnsafeMutablePointer<Element>(storage + i)
}
}
}
// Addressable.subscript.getter with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
// Addressable.subscript.unsafeAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicflu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
// Addressable.subscript.setter with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
// Addressable.subscript.unsafeMutableAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicfau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
// Addressable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
| apache-2.0 | 8f1a18690b06573fe601cc86a87652c1 | 44.462963 | 287 | 0.702037 | 3.854003 | false | false | false | false |
laerador/barista | Barista/Application/AboutPreferencesView.swift | 1 | 1061 | //
// AboutPreferencesView.swift
// Barista
//
// Created by Franz Greiling on 23.07.18.
// Copyright © 2018 Franz Greiling. All rights reserved.
//
import Cocoa
class AboutPreferencesView: NSView {
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var aboutTextView: NSTextView!
override func awakeFromNib() {
super.awakeFromNib()
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let buildnr = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
versionLabel.stringValue = "Version \(version) (\(buildnr))"
aboutTextView.readRTFD(fromFile: Bundle.main.path(forResource: "About", ofType: "rtf")!)
aboutTextView.font = NSFont.systemFont(ofSize: NSFont.systemFontSize)
aboutTextView.textColor = NSColor.labelColor
if #available(OSX 10.14, *) {
aboutTextView.linkTextAttributes?[.foregroundColor] = NSColor.controlAccentColor
}
}
}
| bsd-2-clause | 0e29656ae7dcc379f8cecef086f5c431 | 30.176471 | 103 | 0.671698 | 4.884793 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Site Settings/DiscussionSettingsViewController.swift | 1 | 25702 | import Foundation
import CocoaLumberjack
import WordPressShared
/// The purpose of this class is to render the Discussion Settings associated to a site, and
/// allow the user to tune those settings, as required.
///
open class DiscussionSettingsViewController: UITableViewController {
// MARK: - Initializers / Deinitializers
@objc public convenience init(blog: Blog) {
self.init(style: .grouped)
self.blog = blog
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
setupTableView()
setupNotificationListeners()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadSelectedRow()
tableView.deselectSelectedRowWithAnimation(true)
refreshSettings()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
saveSettingsIfNeeded()
}
// MARK: - Setup Helpers
fileprivate func setupNavBar() {
title = NSLocalizedString("Discussion", comment: "Title for the Discussion Settings Screen")
}
fileprivate func setupTableView() {
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
// Note: We really want to handle 'Unselect' manually.
// Reason: we always reload previously selected rows.
clearsSelectionOnViewWillAppear = false
}
fileprivate func setupNotificationListeners() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(DiscussionSettingsViewController.handleContextDidChange(_:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: settings.managedObjectContext)
}
// MARK: - Persistance!
fileprivate func refreshSettings() {
let service = BlogService(managedObjectContext: settings.managedObjectContext!)
service.syncSettings(for: blog,
success: { [weak self] in
self?.tableView.reloadData()
DDLogInfo("Reloaded Settings")
},
failure: { (error: Error) in
DDLogError("Error while sync'ing blog settings: \(error)")
})
}
fileprivate func saveSettingsIfNeeded() {
if !settings.hasChanges {
return
}
let service = BlogService(managedObjectContext: settings.managedObjectContext!)
service.updateSettings(for: blog,
success: nil,
failure: { (error: Error) -> Void in
DDLogError("Error while persisting settings: \(error)")
})
}
@objc open func handleContextDidChange(_ note: Foundation.Notification) {
guard let context = note.object as? NSManagedObjectContext else {
return
}
if !context.updatedObjects.contains(settings) {
return
}
saveSettingsIfNeeded()
}
// MARK: - UITableViewDataSoutce Methods
open override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rowAtIndexPath(indexPath)
let cell = cellForRow(row, tableView: tableView)
switch row.style {
case .Switch:
configureSwitchCell(cell as! SwitchTableViewCell, row: row)
default:
configureTextCell(cell as! WPTableViewCell, row: row)
}
return cell
}
open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].headerText
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footerText
}
open override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionFooter(view)
}
// MARK: - UITableViewDelegate Methods
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rowAtIndexPath(indexPath).handler?(tableView)
}
// MARK: - Cell Setup Helpers
fileprivate func rowAtIndexPath(_ indexPath: IndexPath) -> Row {
return sections[indexPath.section].rows[indexPath.row]
}
fileprivate func cellForRow(_ row: Row, tableView: UITableView) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: row.style.rawValue) {
return cell
}
switch row.style {
case .Value1:
return WPTableViewCell(style: .value1, reuseIdentifier: row.style.rawValue)
case .Switch:
return SwitchTableViewCell(style: .default, reuseIdentifier: row.style.rawValue)
}
}
fileprivate func configureTextCell(_ cell: WPTableViewCell, row: Row) {
cell.textLabel?.text = row.title ?? String()
cell.detailTextLabel?.text = row.details ?? String()
cell.accessoryType = .disclosureIndicator
WPStyleGuide.configureTableViewCell(cell)
}
fileprivate func configureSwitchCell(_ cell: SwitchTableViewCell, row: Row) {
cell.name = row.title ?? String()
cell.on = row.boolValue ?? true
cell.onChange = { (newValue: Bool) in
row.handler?(newValue as AnyObject?)
}
}
// MARK: - Row Handlers
fileprivate func pressedCommentsAllowed(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsAllowed = enabled
}
fileprivate func pressedPingbacksInbound(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.pingbackInboundEnabled = enabled
}
fileprivate func pressedPingbacksOutbound(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.pingbackOutboundEnabled = enabled
}
fileprivate func pressedRequireNameAndEmail(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsRequireNameAndEmail = enabled
}
fileprivate func pressedRequireRegistration(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsRequireRegistration = enabled
}
fileprivate func pressedCloseCommenting(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Close commenting", comment: "Close Comments Title")
pickerViewController.switchVisible = true
pickerViewController.switchOn = settings.commentsCloseAutomatically
pickerViewController.switchText = NSLocalizedString("Automatically Close", comment: "Discussion Settings")
pickerViewController.selectionText = NSLocalizedString("Close after", comment: "Close comments after a given number of days")
pickerViewController.selectionFormat = NSLocalizedString("%d days", comment: "Number of days")
pickerViewController.pickerHint = NSLocalizedString("Automatically close comments on content after a certain number of days.", comment: "Discussion Settings: Comments Auto-close")
pickerViewController.pickerFormat = NSLocalizedString("%d days", comment: "Number of days")
pickerViewController.pickerMinimumValue = commentsAutocloseMinimumValue
pickerViewController.pickerMaximumValue = commentsAutocloseMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsCloseAutomaticallyAfterDays as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsCloseAutomatically = enabled
self?.settings.commentsCloseAutomaticallyAfterDays = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedSortBy(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Sort By", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsSortOrder
settingsViewController.titles = CommentsSorting.allTitles
settingsViewController.values = CommentsSorting.allValues
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newSortOrder = CommentsSorting(rawValue: selected as! Int) else {
return
}
self?.settings.commentsSorting = newSortOrder
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedThreading(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Threading", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsThreading.rawValue as NSObject
settingsViewController.titles = CommentsThreading.allTitles
settingsViewController.values = CommentsThreading.allValues
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newThreadingDepth = CommentsThreading(rawValue: selected as! Int) else {
return
}
self?.settings.commentsThreading = newThreadingDepth
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedPaging(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Paging", comment: "Comments Paging")
pickerViewController.switchVisible = true
pickerViewController.switchOn = settings.commentsPagingEnabled
pickerViewController.switchText = NSLocalizedString("Paging", comment: "Discussion Settings")
pickerViewController.selectionText = NSLocalizedString("Comments per page", comment: "A label title.")
pickerViewController.pickerHint = NSLocalizedString("Break comment threads into multiple pages.", comment: "Text snippet summarizing what comment paging does.")
pickerViewController.pickerMinimumValue = commentsPagingMinimumValue
pickerViewController.pickerMaximumValue = commentsPagingMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsPageSize as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsPagingEnabled = enabled
self?.settings.commentsPageSize = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedAutomaticallyApprove(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Automatically Approve", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsAutoapproval.rawValue as NSObject
settingsViewController.titles = CommentsAutoapproval.allTitles
settingsViewController.values = CommentsAutoapproval.allValues
settingsViewController.hints = CommentsAutoapproval.allHints
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newApprovalStatus = CommentsAutoapproval(rawValue: selected as! Int) else {
return
}
self?.settings.commentsAutoapproval = newApprovalStatus
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedLinksInComments(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Links in comments", comment: "Comments Paging")
pickerViewController.switchVisible = false
pickerViewController.selectionText = NSLocalizedString("Links in comments", comment: "A label title")
pickerViewController.pickerHint = NSLocalizedString("Require manual approval for comments that include more than this number of links.", comment: "An explaination of a setting.")
pickerViewController.pickerMinimumValue = commentsLinksMinimumValue
pickerViewController.pickerMaximumValue = commentsLinksMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsMaximumLinks as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsMaximumLinks = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedModeration(_ payload: AnyObject?) {
let moderationKeys = settings.commentsModerationKeys
let settingsViewController = SettingsListEditorViewController(collection: moderationKeys)
settingsViewController.title = NSLocalizedString("Hold for Moderation", comment: "Moderation Keys Title")
settingsViewController.insertTitle = NSLocalizedString("New Moderation Word", comment: "Moderation Keyword Insertion Title")
settingsViewController.editTitle = NSLocalizedString("Edit Moderation Word", comment: "Moderation Keyword Edition Title")
settingsViewController.footerText = NSLocalizedString("When a comment contains any of these words in its content, name, URL, e-mail or IP, it will be held in the moderation queue. You can enter partial words, so \"press\" will match \"WordPress\".",
comment: "Text rendered at the bottom of the Discussion Moderation Keys editor")
settingsViewController.onChange = { [weak self] (updated: Set<String>) in
self?.settings.commentsModerationKeys = updated
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedBlocklist(_ payload: AnyObject?) {
let blocklistKeys = settings.commentsBlocklistKeys
let settingsViewController = SettingsListEditorViewController(collection: blocklistKeys)
settingsViewController.title = NSLocalizedString("Blocklist", comment: "Blocklist Title")
settingsViewController.insertTitle = NSLocalizedString("New Blocklist Word", comment: "Blocklist Keyword Insertion Title")
settingsViewController.editTitle = NSLocalizedString("Edit Blocklist Word", comment: "Blocklist Keyword Edition Title")
settingsViewController.footerText = NSLocalizedString("When a comment contains any of these words in its content, name, URL, e-mail, or IP, it will be marked as spam. You can enter partial words, so \"press\" will match \"WordPress\".",
comment: "Text rendered at the bottom of the Discussion Blocklist Keys editor")
settingsViewController.onChange = { [weak self] (updated: Set<String>) in
self?.settings.commentsBlocklistKeys = updated
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
// MARK: - Computed Properties
fileprivate var sections: [Section] {
return [postsSection, commentsSection, otherSection]
}
fileprivate var postsSection: Section {
let headerText = NSLocalizedString("Defaults for New Posts", comment: "Discussion Settings: Posts Section")
let footerText = NSLocalizedString("You can override these settings for individual posts.", comment: "Discussion Settings: Footer Text")
let rows = [
Row(style: .Switch,
title: NSLocalizedString("Allow Comments", comment: "Settings: Comments Enabled"),
boolValue: self.settings.commentsAllowed,
handler: { [weak self] in
self?.pressedCommentsAllowed($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Send Pingbacks", comment: "Settings: Sending Pingbacks"),
boolValue: self.settings.pingbackOutboundEnabled,
handler: { [weak self] in
self?.pressedPingbacksOutbound($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Receive Pingbacks", comment: "Settings: Receiving Pingbacks"),
boolValue: self.settings.pingbackInboundEnabled,
handler: { [weak self] in
self?.pressedPingbacksInbound($0)
})
]
return Section(headerText: headerText, footerText: footerText, rows: rows)
}
fileprivate var commentsSection: Section {
let headerText = NSLocalizedString("Comments", comment: "Settings: Comment Sections")
let rows = [
Row(style: .Switch,
title: NSLocalizedString("Require name and email", comment: "Settings: Comments Approval settings"),
boolValue: self.settings.commentsRequireNameAndEmail,
handler: { [weak self] in
self?.pressedRequireNameAndEmail($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Require users to log in", comment: "Settings: Comments Approval settings"),
boolValue: self.settings.commentsRequireRegistration,
handler: { [weak self] in
self?.pressedRequireRegistration($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Close Commenting", comment: "Settings: Close comments after X period"),
details: self.detailsForCloseCommenting,
handler: { [weak self] in
self?.pressedCloseCommenting($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Sort By", comment: "Settings: Comments Sort Order"),
details: self.detailsForSortBy,
handler: { [weak self] in
self?.pressedSortBy($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Threading", comment: "Settings: Comments Threading preferences"),
details: self.detailsForThreading,
handler: { [weak self] in
self?.pressedThreading($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Paging", comment: "Settings: Comments Paging preferences"),
details: self.detailsForPaging,
handler: { [weak self] in
self?.pressedPaging($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Automatically Approve", comment: "Settings: Comments Approval settings"),
details: self.detailsForAutomaticallyApprove,
handler: { [weak self] in
self?.pressedAutomaticallyApprove($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Links in comments", comment: "Settings: Comments Approval settings"),
details: self.detailsForLinksInComments,
handler: { [weak self] in
self?.pressedLinksInComments($0)
}),
]
return Section(headerText: headerText, rows: rows)
}
fileprivate var otherSection: Section {
let rows = [
Row(style: .Value1,
title: NSLocalizedString("Hold for Moderation", comment: "Settings: Comments Moderation"),
handler: self.pressedModeration),
Row(style: .Value1,
title: NSLocalizedString("Blocklist", comment: "Settings: Comments Blocklist"),
handler: self.pressedBlocklist)
]
return Section(rows: rows)
}
// MARK: - Row Detail Helpers
fileprivate var detailsForCloseCommenting: String {
if !settings.commentsCloseAutomatically {
return NSLocalizedString("Off", comment: "Disabled")
}
let numberOfDays = settings.commentsCloseAutomaticallyAfterDays ?? 0
let format = NSLocalizedString("%@ days", comment: "Number of days after which comments should autoclose")
return String(format: format, numberOfDays)
}
fileprivate var detailsForSortBy: String {
return settings.commentsSorting.description
}
fileprivate var detailsForThreading: String {
if !settings.commentsThreadingEnabled {
return NSLocalizedString("Off", comment: "Disabled")
}
let levels = settings.commentsThreadingDepth ?? 0
let format = NSLocalizedString("%@ levels", comment: "Number of Threading Levels")
return String(format: format, levels)
}
fileprivate var detailsForPaging: String {
if !settings.commentsPagingEnabled {
return NSLocalizedString("None", comment: "Disabled")
}
let pageSize = settings.commentsPageSize ?? 0
let format = NSLocalizedString("%@ comments", comment: "Number of Comments per Page")
return String(format: format, pageSize)
}
fileprivate var detailsForAutomaticallyApprove: String {
switch settings.commentsAutoapproval {
case .disabled:
return NSLocalizedString("None", comment: "No comment will be autoapproved")
case .everything:
return NSLocalizedString("All", comment: "Autoapprove every comment")
case .fromKnownUsers:
return NSLocalizedString("Known Users", comment: "Autoapprove only from known users")
}
}
fileprivate var detailsForLinksInComments: String {
guard let numberOfLinks = settings.commentsMaximumLinks else {
return String()
}
let format = NSLocalizedString("%@ links", comment: "Number of Links")
return String(format: format, numberOfLinks)
}
// MARK: - Private Nested Classes
fileprivate class Section {
let headerText: String?
let footerText: String?
let rows: [Row]
init(headerText: String? = nil, footerText: String? = nil, rows: [Row]) {
self.headerText = headerText
self.footerText = footerText
self.rows = rows
}
}
fileprivate class Row {
let style: Style
let title: String?
let details: String?
let handler: Handler?
var boolValue: Bool?
init(style: Style, title: String? = nil, details: String? = nil, boolValue: Bool? = nil, handler: Handler? = nil) {
self.style = style
self.title = title
self.details = details
self.boolValue = boolValue
self.handler = handler
}
typealias Handler = ((AnyObject?) -> Void)
enum Style: String {
case Value1 = "Value1"
case Switch = "SwitchCell"
}
}
// MARK: - Private Properties
fileprivate var blog: Blog!
// MARK: - Computed Properties
fileprivate var settings: BlogSettings {
return blog.settings!
}
// MARK: - Typealiases
fileprivate typealias CommentsSorting = BlogSettings.CommentsSorting
fileprivate typealias CommentsThreading = BlogSettings.CommentsThreading
fileprivate typealias CommentsAutoapproval = BlogSettings.CommentsAutoapproval
// MARK: - Constants
fileprivate let commentsPagingMinimumValue = 1
fileprivate let commentsPagingMaximumValue = 100
fileprivate let commentsLinksMinimumValue = 1
fileprivate let commentsLinksMaximumValue = 100
fileprivate let commentsAutocloseMinimumValue = 1
fileprivate let commentsAutocloseMaximumValue = 120
}
| gpl-2.0 | 1caf6bbedf175af9aaffd6cbb16d9684 | 42.636672 | 263 | 0.641234 | 5.842692 | false | false | false | false |
Shivam0911/IOS-Training-Projects | ListViewToGridViewConverter/ListViewToGridViewConverter/ListToGridVC.swift | 1 | 6140 | //
// ListToGridVC.swift
// ListViewToGridViewConverter
//
// Created by MAC on 13/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class ListToGridVC: UIViewController {
var flag = 0
let carData = CarData()
let indexCount = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
@IBOutlet weak var appInventivLogo: UIImageView!
@IBOutlet weak var listButtonOutlet: UIButton!
@IBOutlet weak var gridButtonOutlet: UIButton!
@IBOutlet weak var imageViewCollectionOutlet: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
imageViewCollectionOutlet.dataSource = self
imageViewCollectionOutlet.delegate = self
let listcellnib = UINib(nibName: "listViewCell", bundle: nil)
imageViewCollectionOutlet.register(listcellnib, forCellWithReuseIdentifier: "ListID")
let gridcellnib = UINib(nibName: "GridViewCell", bundle: nil)
imageViewCollectionOutlet.register(gridcellnib, forCellWithReuseIdentifier: "GridCellID")
appInventivLogo.layer.cornerRadius = appInventivLogo.layer.bounds.width/2
// self.listButtonOutlet.layer.borderWidth = 1
// self.listButtonOutlet.layer.borderColor = UIColor.black.cgColor
// self.gridButtonOutlet.layer.borderWidth = 1
// self.gridButtonOutlet.layer.borderColor = UIColor.black.cgColor
// Do any additional setup after loading the view.
}
}
extension ListToGridVC : UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.carData.car.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
if indexPath.row < carData.car.count {
if flag == 0 {
let cell1 = returnGridCell(collectionView,indexPath)
return cell1
}
else {
let cell2 = returnListCell(collectionView,indexPath)
return cell2
}
}
else {
fatalError("no cell to display")
}
}
// MARK: UICollectionViewDelegateFlowLayout Methods
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: 30, height: 30)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if flag == 0 {
let width = 170.0
return CGSize(width: width, height: width + 20.0)
}
else {
let width = 400 //self.imageViewCollectionOutlet.frame.width
return CGSize(width: width, height: 70)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK : GridButtonAction
@IBAction func gridButtonPressed(_ sender: UIButton) {
flag = 0
imageViewCollectionOutlet.reloadData()
sender.backgroundColor = UIColor.gray
sender.titleLabel?.textColor = UIColor.white
listButtonOutlet.backgroundColor = UIColor.lightGray
// imageViewCollectionOutlet.performBatchUpdates({ }, completion: nil)
}
//MARK : ListButtonAction
@IBAction func listButtonPressed(_ sender: UIButton) {
flag = 1
imageViewCollectionOutlet.reloadData()
sender.backgroundColor = UIColor.gray
sender.titleLabel?.textColor = UIColor.white
gridButtonOutlet.backgroundColor = UIColor.lightGray
// imageViewCollectionOutlet.performBatchUpdates({ }, completion: nil)
}
}
extension ListToGridVC {
//MARK : ReturnGridCell Method
func returnGridCell(_ collectionView: UICollectionView,_ indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GridCellID", for: indexPath) as? GridViewCell else{
fatalError("Cell Not Found !")
}
cell.populateTheDataInGridView(carData.car[indexPath.item] as! [String : String])
return cell
}
//MARK: ReturnListCell Method
func returnListCell(_ collectionView: UICollectionView,_ indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListID", for: indexPath) as? listViewCell else{
fatalError("Cell Not Found !")
}
cell.populateTheData(carData.car[indexPath.item] as! [String : String])
return cell
}
}
| mit | 3dd0b20619d8a39a37c9e437918543f3 | 46.223077 | 179 | 0.647337 | 5.530631 | false | false | false | false |
powerytg/Accented | Accented/Core/Storage/Models/CommentCollectionModel.swift | 1 | 750 | //
// CommentCollectionModel.swift
// Accented
//
// Collection model that represents a specific photo's comments and replies
//
// Created by Tiangong You on 5/23/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class CommentCollectionModel: CollectionModel<CommentModel> {
// Parent photo id
var photoId : String
init(photoId : String) {
self.photoId = photoId
super.init()
// Generate an uuid
self.modelId = photoId
}
override func copy(with zone: NSZone? = nil) -> Any {
let clone = CommentCollectionModel(photoId : photoId)
clone.totalCount = self.totalCount
clone.items = items
return clone
}
}
| mit | d6fe59b77660f977b399b139c5539fc4 | 23.16129 | 76 | 0.627503 | 4.48503 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground | Pages/Slither.xcplaygroundpage/Contents.swift | 1 | 3570 | /*:
### Joint 예제
*
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
let pi:CGFloat = CGFloat(M_PI)
override func didMove(to view: SKView) {
if self.contentCreated != true {
self.physicsWorld.speed = 1.0
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
var prevNode : SKNode?
for i in 0..<10 {
let currentNode = addBall(CGPoint(x: 40 + 20 * CGFloat(i), y: 240))
if let prevNode = prevNode {
// anchorA, anchorB의 좌표는 scene이 된다.
let limitJoint = SKPhysicsJointLimit.joint(withBodyA: prevNode.physicsBody!, bodyB: currentNode.physicsBody!, anchorA: prevNode.position, anchorB: currentNode.position)
limitJoint.maxLength = 30.0
self.physicsWorld.add(limitJoint)
}
prevNode = currentNode
}
// 마지막 노드 1개에만 힘을 가한다.
prevNode?.physicsBody?.applyForce(CGVector(dx: 0, dy: -9.8))
// let head = prevNode as! SKShapeNode
// do {
// head.name = "head"
// head.strokeColor = [#Color(colorLiteralRed: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 1)#]
// head.position = CGPointMake(280, 100)
// }
self.contentCreated = true
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let nodes = self.nodes(at: location)
for node in nodes {
if node.name == "head" {
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let nodes = self.nodes(at: location)
for node in nodes {
if node.name == "head" {
}
}
}
}
func addBall(_ position:CGPoint) -> SKNode {
let radius = CGFloat(20.0)
let ball = SKShapeNode(circleOfRadius: radius)
ball.position = position
ball.physicsBody = SKPhysicsBody(circleOfRadius: radius)
ball.physicsBody?.categoryBitMask = 0x1
ball.physicsBody?.collisionBitMask = 0x2
addChild(ball)
return ball
}
func angularImpulse() -> SKAction {
let waitAction = SKAction.wait(forDuration: 2.0)
let impulse = SKAction.applyAngularImpulse(0.7, duration: 3.0)
let delayImpulse = SKAction.sequence([waitAction, impulse])
return delayImpulse
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size: CGSize(width: 320, height: 480))
do {
scene.scaleMode = .aspectFit
}
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
do {
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.presentScene(scene)
}
self.view.addSubview(skView)
}
}
PlaygroundHelper.showViewController(ViewController())
| isc | 22eec0630f0572dca39f3b7e186a018b | 27.208 | 188 | 0.55814 | 4.396509 | false | false | false | false |
ronp001/SwiftRedis | SwiftRedis/RedisResponse.swift | 1 | 6473 | //
// RedisResponse.swift
// ActivityKeeper
//
// Created by Ron Perry on 11/7/15.
// Copyright © 2015 ronp001. All rights reserved.
//
import Foundation
class RedisResponse : CustomStringConvertible {
enum ResponseType { case int, string, data, error, array, unknown }
class ParseError : NSError {
init(msg: String) {
super.init(domain: "RedisResponse", code: 0, userInfo: ["message": msg])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let responseType: ResponseType
var intVal: Int?
fileprivate var stringValInternal: String?
var stringVal: String? {
get {
switch responseType {
case .string:
return self.stringValInternal
case .data:
return String(describing: NSString(data: self.dataVal!, encoding: String.Encoding.utf8.rawValue))
case .int:
return String(describing: intVal)
case .error:
return nil
case .unknown:
return nil
case .array:
var ar: [String?] = []
for elem in arrayVal! {
ar += [elem.stringVal]
}
return String(describing: ar)
}
}
set(value) {
stringValInternal = value
}
}
var dataVal: Data?
var errorVal: String?
var arrayVal: [RedisResponse]?
var parseErrorMsg: String? = nil
init(intVal: Int? = nil, dataVal: Data? = nil, stringVal: String? = nil, errorVal: String? = nil, arrayVal: [RedisResponse]? = nil, responseType: ResponseType? = nil)
{
self.parseErrorMsg = nil
self.intVal = intVal
self.stringValInternal = stringVal
self.errorVal = errorVal
self.arrayVal = arrayVal
self.dataVal = dataVal
if intVal != nil { self.responseType = .int }
else if stringVal != nil { self.responseType = .string }
else if errorVal != nil { self.responseType = .error }
else if arrayVal != nil { self.responseType = .array }
else if dataVal != nil { self.responseType = .data }
else if responseType != nil { self.responseType = responseType! }
else { self.responseType = .unknown }
if self.responseType == .array && self.arrayVal == nil {
self.arrayVal = [RedisResponse]()
}
}
func parseError(_ msg: String)
{
NSLog("Parse error - \(msg)")
parseErrorMsg = msg
}
// should only be called if the current object responseType is .Array
func addArrayElement(_ response: RedisResponse)
{
self.arrayVal!.append(response)
}
var description: String {
var result = "RedisResponse(\(self.responseType):"
switch self.responseType {
case .error:
result += self.errorVal!
case .string:
result += self.stringVal!
case .int:
result += String(self.intVal!)
case .data:
result += "[Data - \(self.dataVal!.count) bytes]"
case .array:
result += "[Array - \(self.arrayVal!.count) elements]"
case .unknown:
result += "?"
break
}
result += ")"
return result
}
// reads data from the buffer according to own responseType
func readValueFromBuffer(_ buffer: RedisBuffer, numBytes: Int?) -> Bool?
{
let data = buffer.getNextDataOfSize(numBytes)
if data == nil { return nil }
if numBytes != nil { // ensure there is also a CRLF after the buffer
let crlfData = buffer.getNextDataUntilCRLF()
if crlfData == nil { // didn't find data
buffer.restoreRemovedData(data!)
return nil
}
// if the data was CRLF, it would have been removed by getNxtDataUntilCRLF, so buffer should be empty
if crlfData!.count != 0 {
buffer.restoreRemovedData(crlfData!)
return false
}
}
switch responseType {
case .data:
self.dataVal = data
return true
case .string:
self.stringVal = String(data: data!, encoding: String.Encoding.utf8)
if ( self.stringVal == nil ) {
parseError("Could not parse string")
return false
}
return true
case .error:
self.errorVal = String(data: data!, encoding: String.Encoding.utf8)
if ( self.errorVal == nil ) {
parseError("Could not parse string")
return false
}
return true
case .int:
let str = String(data: data!, encoding: String.Encoding.utf8)
if ( str == nil ) {
parseError("Could not parse string")
return false
}
self.intVal = Int(str!)
if ( self.intVal == nil ) {
parseError("Received '\(str)' when expecting Integer")
return false
}
return true
case .array:
parseError("Array parsing not supported yet")
return false
case .unknown:
parseError("Trying to parse when ResponseType == .Unknown")
return false
}
}
}
func != (left: RedisResponse, right: RedisResponse) -> Bool {
return !(left == right)
}
func == (left: RedisResponse, right: RedisResponse) -> Bool {
if left.responseType != right.responseType { return false }
switch left.responseType {
case .int:
return left.intVal == right.intVal
case .string:
return left.stringVal == right.stringVal
case .error:
return left.errorVal == right.errorVal
case .unknown:
return true
case .data:
return (left.dataVal! == right.dataVal!)
case .array:
if left.arrayVal!.count != right.arrayVal!.count { return false }
for i in 0 ... left.arrayVal!.count-1 {
if !(left.arrayVal![i] == right.arrayVal![i]) { return false }
}
return true
}
}
| mit | 09e0de3d37e798c2043f1e9681eb9c2b | 29.819048 | 170 | 0.530902 | 4.90303 | false | false | false | false |
neonichu/realm-cocoa | RealmSwift-swift2.0/Realm.swift | 2 | 22204 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `init(inMemoryIdentifier:)`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
- warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/**
The location of the default Realm as a string. Can be overridden.
`~/Library/Application Support/{bundle ID}/default.realm` on OS X.
`default.realm` in your application's documents directory on iOS.
- returns: Location of the default Realm.
*/
public class var defaultPath: String {
get {
return RLMRealm.defaultRealmPath()
}
set {
RLMRealm.setDefaultRealmPath(newValue)
}
}
// MARK: Initializers
/**
Obtains a Realm instance persisted at the specified file path. Defaults to
`Realm.defaultPath`
- parameter path: Path to the realm file.
*/
public convenience init(path: String = Realm.defaultPath) throws {
let rlmRealm = try RLMRealm(path: path, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance with persistence to a specific file path with
options.
Like `init(path:)`, but with the ability to open read-only realms and
encrypted realms.
- warning: Read-only Realms do not support changes made to the file while the
`Realm` exists. This means that you cannot open a Realm as both read-only
and read-write at the same time. Read-only Realms should normally only be used
on files which cannot be opened in read-write mode, and not just for enforcing
correctness in code that should not need to write to the Realm.
- parameter path: Path to the file you want the data saved in.
- parameter readOnly: Bool indicating if this Realm is read-only (must use for read-only files).
- parameter encryptionKey: 64-byte key to use to encrypt the data.
*/
public convenience init(path: String, readOnly: Bool, encryptionKey: NSData? = nil) throws {
let rlmRealm = try RLMRealm(path: path, key: encryptionKey, readOnly: readOnly, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
/**
Obtains a Realm instance for an un-persisted in-memory Realm. The identifier
used to create this instance can be used to access the same in-memory Realm from
multiple threads.
Because in-memory Realms are not persisted, you must be sure to hold on to a
reference to the `Realm` object returned from this for as long as you want
the data to last. Realm's internal cache of `Realm`s will not keep the
in-memory Realm alive across cycles of the run loop, so without a strong
reference to the `Realm` a new Realm will be created each time. Note that
`Object`s, `List`s, and `Results` that refer to objects persisted in a Realm have a
strong reference to the relevant `Realm`, as do `NotifcationToken`s.
- parameter identifier: A string used to identify a particular in-memory Realm.
*/
public convenience init(inMemoryIdentifier: String) {
self.init(RLMRealm.inMemoryRealmWithIdentifier(inMemoryIdentifier))
}
// MARK: Transactions
/**
Helper to perform actions contained within the given block inside a write transation.
- parameter block: The block to be executed inside a write transaction.
*/
public func write(block: (() -> Void)) {
rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction with throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction.
After this is called, the `Realm` reverts back to being read-only.
Calling this when not in a write transaction will throw an exception.
*/
public func commitWrite() {
rlmRealm.commitWriteTransaction()
}
/**
Revert all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not reinstate deleted
accessor objects. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all linked (child) objects referenced by this object will also be
added to the Realm if they are not already in it. If the object or any linked
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
- parameter object: Object to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
- see: add(object:update:)
- parameter objects: A sequence which contains objects to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given value.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- parameter type: The object type to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
// FIXME: use T.className()
let className = (T.self as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
- parameter type: The type of the objects to be returned.
- returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
// FIXME: use T.className()
return Results<T>(RLMGetObjects(rlmRealm, (T.self as Object.Type).className(), nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- parameter type: The type of the objects to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
// FIXME: use T.className()
return unsafeBitCast(RLMGetObject(rlmRealm, (T.self as Object.Type).className(), key), Optional<T>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
- returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
- parameter notificationToken: The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call -refresh on the Realm to
update it to get the latest version.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
- returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
- parameter path: Path to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws {
if let encryptionKey = encryptionKey {
try rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey)
} else {
try rlmRealm.writeCopyToPath(path)
}
}
// MARK: Encryption
/**
Set the encryption key to use when opening Realms at a certain path.
This can be used as an alternative to explicitly passing the key to
`Realm(path:, encryptionKey:, readOnly:, error:)` each time a Realm instance is
needed. The encryption key will be used any time a Realm is opened with
`Realm(path:)` or `Realm()`.
If you do not want Realm to hold on to your encryption keys any longer than
needed, then use `Realm(path:, encryptionKey:, readOnly:, error:)` rather than this
method.
- parameter encryptionKey: 64-byte encryption key to use, or `nil` to unset.
- parameter path: Realm path to set the encryption key for.
+*/
public class func setEncryptionKey(encryptionKey: NSData?, forPath: String = Realm.defaultPath) {
RLMRealm.setEncryptionKey(encryptionKey, forRealmsAtPath: forPath)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns whether the two realms are equal.
public func ==(lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange are posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`beginWriteTransaction()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notifcation has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
| apache-2.0 | 2e2b591b9500151bda2b2ed24fc258bf | 37.750436 | 133 | 0.683886 | 4.846977 | false | false | false | false |
slxl/ReactKit | Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Alamofire/Source/ServerTrustPolicy.swift | 2 | 13027 | //
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
- returns: The new `ServerTrustPolicyManager` instance.
*/
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/**
Returns the `ServerTrustPolicy` for the given host if applicable.
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
this method and implement more complex mapping implementations such as wildcards.
- parameter host: The host to use when searching for a matching policy.
- returns: The server trust policy for the given host if found.
*/
public func serverTrustPolicyForHost(_ host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
*/
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((serverTrust: SecTrust, host: String) -> Bool)
// MARK: - Bundle Location
/**
Returns all certificates within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `.cer` files.
- returns: All certificates within the given bundle.
*/
public static func certificatesInBundle(_ bundle: Bundle = Bundle.main()) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.pathsForResources(ofType: fileExtension, inDirectory: nil)
}.flatten())
for path in paths {
if let
certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)),
certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/**
Returns all public keys within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `*.cer` files.
- returns: All public keys within the given bundle.
*/
public static func publicKeysInBundle(_ bundle: Bundle = Bundle.main()) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificatesInBundle(bundle) {
if let publicKey = publicKeyForCertificate(certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/**
Evaluates whether the server trust is valid for the given host.
- parameter serverTrust: The server trust to evaluate.
- parameter host: The host of the challenge protection space.
- returns: Whether the server trust is valid.
*/
public func evaluateServerTrust(_ serverTrust: SecTrust, isValidForHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!] )
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!])
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!])
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateDataForTrust(_ trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateDataForCertificates(certificates)
}
private func certificateDataForCertificates(_ certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeysForTrust(_ trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let
certificate = SecTrustGetCertificateAtIndex(trust, index),
publicKey = publicKeyForCertificate(certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKeyForCertificate(_ certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust where trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
| mit | c292a64fead0717ae35f6ed05fef5e95 | 41.851974 | 121 | 0.65702 | 6.047818 | false | false | false | false |
ngageoint/mage-ios | Mage/StraightLineNav/StraightLineNavigation.swift | 1 | 7707 | //
// StraightLineNavigation.swift
// MAGE
//
// Created by Daniel Barela on 3/25/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
struct StraightLineNavigationNotification {
var image: UIImage? = nil
var imageURL: URL? = nil
var title: String? = nil
var coordinate: CLLocationCoordinate2D
var user: User? = nil
var feedItem: FeedItem? = nil
var observation: Observation? = nil
}
protocol StraightLineNavigationDelegate {
func cancelStraightLineNavigation();
}
class StraightLineNavigation: NSObject {
var delegate: StraightLineNavigationDelegate?;
weak var mapView: MKMapView?;
weak var mapStack: UIStackView?;
var navigationModeEnabled: Bool = false
var headingModeEnabled: Bool = false
var navView: StraightLineNavigationView?;
var headingPolyline: NavigationOverlay?;
var relativeBearingPolyline: NavigationOverlay?;
var relativeBearingColor: UIColor {
get {
return UserDefaults.standard.bearingTargetColor;
}
}
var headingColor: UIColor {
get {
return UserDefaults.standard.headingColor;
}
}
init(mapView: MKMapView, locationManager: CLLocationManager?, mapStack: UIStackView) {
self.mapView = mapView;
self.mapStack = mapStack;
}
deinit {
navView?.removeFromSuperview();
navView = nil
}
func startNavigation(manager: CLLocationManager, destinationCoordinate: CLLocationCoordinate2D, delegate: StraightLineNavigationDelegate?, image: UIImage?, imageURL: URL?, scheme: MDCContainerScheming? = nil) {
navigationModeEnabled = true;
headingModeEnabled = true;
navView = StraightLineNavigationView(locationManager: manager, destinationMarker: image, destinationCoordinate: destinationCoordinate, delegate: delegate, scheme: scheme, targetColor: relativeBearingColor, bearingColor: headingColor);
navView?.destinationMarkerUrl = imageURL
updateNavigationLines(manager: manager, destinationCoordinate: destinationCoordinate);
self.delegate = delegate;
mapStack?.addArrangedSubview(navView!);
}
func startHeading(manager: CLLocationManager) {
headingModeEnabled = true;
updateHeadingLine(manager: manager);
}
@discardableResult
func stopHeading() -> Bool {
if (!navigationModeEnabled && headingModeEnabled) {
headingModeEnabled = false;
if let headingPolyline = headingPolyline {
mapView?.removeOverlay(headingPolyline);
}
return true;
}
return false;
}
func stopNavigation() {
if let navView = navView {
navView.removeFromSuperview()
}
navigationModeEnabled = false;
if let relativeBearingPolyline = relativeBearingPolyline {
mapView?.removeOverlay(relativeBearingPolyline);
}
if let headingPolyline = headingPolyline {
mapView?.removeOverlay(headingPolyline);
}
}
func calculateBearingPoint(startCoordinate: CLLocationCoordinate2D, bearing: CLLocationDirection) -> CLLocationCoordinate2D {
var metersDistanceForBearing = 500000.0;
let span = mapView?.region.span ?? MKCoordinateSpan(latitudeDelta: 5, longitudeDelta: 5)
let center = mapView?.region.center ?? startCoordinate
let loc1 = CLLocation(latitude: center.latitude - span.latitudeDelta, longitude: center.longitude)
let loc2 = CLLocation(latitude: center.latitude + span.latitudeDelta, longitude: center.longitude)
let loc3 = CLLocation(latitude: center.latitude, longitude: center.longitude - span.longitudeDelta)
let loc4 = CLLocation(latitude: center.latitude, longitude: center.longitude + span.longitudeDelta)
metersDistanceForBearing = min(metersDistanceForBearing, max(loc1.distance(from: loc2), loc3.distance(from: loc4)) * 2.0)
let radDirection = bearing * (.pi / 180.0);
return locationWithBearing(bearing: radDirection, distanceMeters: metersDistanceForBearing, origin: startCoordinate)
}
func locationWithBearing(bearing:Double, distanceMeters:Double, origin:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let distRadians = distanceMeters / (6372797.6) // earth radius in meters
let lat1 = origin.latitude * .pi / 180
let lon1 = origin.longitude * .pi / 180
let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing))
let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))
return CLLocationCoordinate2D(latitude: lat2 * 180 / .pi, longitude: lon2 * 180 / .pi)
}
func updateHeadingLine(manager: CLLocationManager) {
if (self.headingModeEnabled) {
guard let location = manager.location else {
return;
}
guard let userCoordinate = manager.location?.coordinate else {
return;
}
// if the user is moving, use their direction of movement
var bearing = location.course;
let speed = location.speed;
if (bearing < 0 || speed <= 0 || location.courseAccuracy < 0 || location.courseAccuracy >= 180) {
// if the user is not moving, use the heading of the phone or the course accuracy is invalid
if let trueHeading = manager.heading?.trueHeading {
bearing = trueHeading;
} else {
return;
}
}
let bearingPoint = MKMapPoint(calculateBearingPoint(startCoordinate: userCoordinate, bearing: bearing));
let userLocationPoint = MKMapPoint(userCoordinate)
let coordinates: [MKMapPoint] = [userLocationPoint, bearingPoint]
if (headingPolyline != nil) {
mapView?.removeOverlay(headingPolyline!);
}
headingPolyline = NavigationOverlay(points: coordinates, count: 2, color: headingColor)
headingPolyline?.accessibilityLabel = "heading"
mapView?.addOverlay(headingPolyline!, level: .aboveLabels);
navView?.populate(relativeBearingColor: relativeBearingColor, headingColor: headingColor);
}
}
func updateNavigationLines(manager: CLLocationManager, destinationCoordinate: CLLocationCoordinate2D?) {
guard let userCoordinate = manager.location?.coordinate else {
return;
}
if navigationModeEnabled, let destinationCoordinate = destinationCoordinate {
let userLocationPoint = MKMapPoint(userCoordinate)
let endCoordinate = MKMapPoint(destinationCoordinate)
let coordinates: [MKMapPoint] = [userLocationPoint, endCoordinate]
if (relativeBearingPolyline != nil) {
mapView?.removeOverlay(relativeBearingPolyline!);
}
relativeBearingPolyline = NavigationOverlay(points: coordinates, count: 2, color: relativeBearingColor)
relativeBearingPolyline?.accessibilityLabel = "relative bearing"
mapView?.addOverlay(relativeBearingPolyline!);
navView?.populate(relativeBearingColor: relativeBearingColor, headingColor: headingColor, destinationCoordinate: destinationCoordinate);
}
updateHeadingLine(manager: manager);
}
}
| apache-2.0 | 6e0a59748537f052f6b4124419f712c3 | 40.880435 | 242 | 0.655463 | 5.457507 | false | false | false | false |
ngageoint/mage-ios | Mage/AttachmentCell.swift | 1 | 11384 | //
// AttachmentCell.m
// Mage
//
//
import UIKit
import Kingfisher
@objc class AttachmentCell: UICollectionViewCell {
private var button: MDCFloatingButton?;
private lazy var imageView: AttachmentUIImageView = {
let imageView: AttachmentUIImageView = AttachmentUIImageView(image: nil);
imageView.configureForAutoLayout();
imageView.clipsToBounds = true;
return imageView;
}();
override init(frame: CGRect) {
super.init(frame: frame);
self.configureForAutoLayout();
self.addSubview(imageView);
imageView.autoPinEdgesToSuperviewEdges();
setNeedsLayout();
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.imageView.kf.cancelDownloadTask();
self.imageView.image = nil;
for view in self.imageView.subviews{
view.removeFromSuperview()
}
button?.removeFromSuperview();
}
func getAttachmentUrl(attachment: Attachment) -> URL? {
if let localPath = attachment.localPath, FileManager.default.fileExists(atPath: localPath) {
return URL(fileURLWithPath: localPath);
} else if let url = attachment.url {
return URL(string: url);
}
return nil;
}
func getAttachmentUrl(size: Int, attachment: Attachment) -> URL? {
if let localPath = attachment.localPath, FileManager.default.fileExists(atPath: localPath) {
return URL(fileURLWithPath: localPath);
} else if let url = attachment.url {
return URL(string: String(format: "%@?size=%ld", url, size));
}
return nil;
}
override func removeFromSuperview() {
self.imageView.cancel();
}
@objc public func setImage(newAttachment: [String : AnyHashable], button: MDCFloatingButton? = nil, scheme: MDCContainerScheming? = nil) {
layoutSubviews();
self.button = button;
self.imageView.kf.indicatorType = .activity;
guard let contentType = newAttachment["contentType"] as? String, let localPath = newAttachment["localPath"] as? String else {
return
}
if (contentType.hasPrefix("image")) {
self.imageView.setImage(url: URL(fileURLWithPath: localPath), cacheOnly: !DataConnectionUtilities.shouldFetchAttachments());
self.imageView.accessibilityLabel = "attachment \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFill;
} else if (contentType.hasPrefix("video")) {
let provider: VideoImageProvider = VideoImageProvider(localPath: localPath);
self.imageView.contentMode = .scaleAspectFill;
DispatchQueue.main.async {
self.imageView.kf.setImage(with: provider, placeholder: UIImage(systemName: "play.circle.fill"), options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.transition(.fade(0.2)),
.scaleFactor(UIScreen.main.scale),
.processor(DownsamplingImageProcessor(size: self.imageView.frame.size)),
.cacheOriginalImage
], completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.contentMode = .scaleAspectFill;
self.imageView.accessibilityLabel = "local \(localPath) loaded";
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
case .failure(let error):
print(error);
self.imageView.backgroundColor = UIColor.init(white: 0, alpha: 0.06);
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
}
});
}
} else if (contentType.hasPrefix("audio")) {
self.imageView.image = UIImage(systemName: "speaker.wave.2.fill");
self.imageView.accessibilityLabel = "local \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
} else {
self.imageView.image = UIImage(systemName: "paperclip");
self.imageView.accessibilityLabel = "local \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
let label = UILabel.newAutoLayout()
label.text = newAttachment["contentType"] as? String
label.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6)
label.font = scheme?.typographyScheme.overline
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.autoSetDimension(.height, toSize: label.font.pointSize)
imageView.addSubview(label)
label.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), excludingEdge: .bottom)
}
self.backgroundColor = scheme?.colorScheme.surfaceColor
if let button = button {
self.addSubview(button);
button.autoPinEdge(.bottom, to: .bottom, of: self.imageView, withOffset: -8);
button.autoPinEdge(.right, to: .right, of: self.imageView, withOffset: -8);
}
}
@objc public func setImage(attachment: Attachment, formatName:NSString, button: MDCFloatingButton? = nil, scheme: MDCContainerScheming? = nil) {
layoutSubviews();
self.button = button;
self.imageView.kf.indicatorType = .activity;
if (attachment.contentType?.hasPrefix("image") ?? false) {
self.imageView.setAttachment(attachment: attachment);
self.imageView.tintColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87);
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loading";
self.imageView.showThumbnail(cacheOnly: !DataConnectionUtilities.shouldFetchAttachments(),
completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
NSLog("Loaded the image \(self.imageView.accessibilityLabel ?? "")")
case .failure(let error):
print(error);
}
});
} else if (attachment.contentType?.hasPrefix("video") ?? false) {
guard let url = self.getAttachmentUrl(attachment: attachment) else {
self.imageView.contentMode = .scaleAspectFit;
self.imageView.image = UIImage(named: "upload");
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
return;
}
var localPath: String? = nil;
if (attachment.localPath != nil && FileManager.default.fileExists(atPath: attachment.localPath!)) {
localPath = attachment.localPath;
}
let provider: VideoImageProvider = VideoImageProvider(url: url, localPath: localPath);
self.imageView.contentMode = .scaleAspectFit;
DispatchQueue.main.async {
self.imageView.kf.setImage(with: provider, placeholder: UIImage(systemName: "play.circle.fill"), options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.transition(.fade(0.2)),
.scaleFactor(UIScreen.main.scale),
.processor(DownsamplingImageProcessor(size: self.imageView.frame.size)),
.cacheOriginalImage
], completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.contentMode = .scaleAspectFill;
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
case .failure(let error):
print(error);
}
});
}
} else if (attachment.contentType?.hasPrefix("audio") ?? false) {
self.imageView.image = UIImage(systemName: "speaker.wave.2.fill");
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
} else {
self.imageView.image = UIImage(systemName: "paperclip");
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
let label = UILabel.newAutoLayout()
label.text = attachment.name
label.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6)
label.font = scheme?.typographyScheme.overline
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.autoSetDimension(.height, toSize: label.font.pointSize)
imageView.addSubview(label)
label.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), excludingEdge: .bottom)
}
self.backgroundColor = scheme?.colorScheme.backgroundColor
if let button = button {
self.addSubview(button);
button.autoPinEdge(.bottom, to: .bottom, of: self.imageView, withOffset: -8);
button.autoPinEdge(.right, to: .right, of: self.imageView, withOffset: -8);
}
}
}
| apache-2.0 | c703bfc8ac8bd5f14a8615d4adf857ff | 51.220183 | 148 | 0.579058 | 5.644026 | false | false | false | false |
takayoshiotake/SevenSegmentSampler_swift | SevenSegmentViewSampler/BBSevenSegmentView.swift | 1 | 4547 | //
// BBSevenSegmentView.swift
// SevenSegmentViewSampler
//
// Created by Takayoshi Otake on 2015/11/08.
// Copyright © 2015 Takayoshi Otake. All rights reserved.
//
import UIKit
@IBDesignable
class BBSevenSegmentView: UIView {
enum Pins {
case A
case B
case C
case D
case E
case F
case G
case DP
case QM
static let Values: [Pins] = [.A, .B, .C, .D, .E, .F, .G, .DP, .QM]
}
// protected
var switchesOnPins: [Pins: Bool] = [.A: false, .B: false, .C: false, .D: false, .E: false, .F: false, .G: false, .DP: false, .QM: false]
@IBInspectable
var pinA: Bool {
set {
switchesOnPins[Pins.A] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.A]!
}
}
@IBInspectable
var pinB: Bool {
set {
switchesOnPins[Pins.B] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.B]!
}
}
@IBInspectable
var pinC: Bool {
set {
switchesOnPins[Pins.C] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.C]!
}
}
@IBInspectable
var pinD: Bool {
set {
switchesOnPins[Pins.D] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.D]!
}
}
@IBInspectable
var pinE: Bool {
set {
switchesOnPins[Pins.E] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.E]!
}
}
@IBInspectable
var pinF: Bool {
set {
switchesOnPins[Pins.F] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.F]!
}
}
@IBInspectable
var pinG: Bool {
set {
switchesOnPins[Pins.G] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.G]!
}
}
@IBInspectable
var pinDP: Bool {
set {
switchesOnPins[Pins.DP] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.DP]!
}
}
@IBInspectable
var pinQM: Bool {
set {
switchesOnPins[Pins.QM] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.QM]!
}
}
@IBInspectable
var pinBits: Int16 {
set {
switchesOnPins[Pins.A] = (newValue >> 0) & 1 == 1
switchesOnPins[Pins.B] = (newValue >> 1) & 1 == 1
switchesOnPins[Pins.C] = (newValue >> 2) & 1 == 1
switchesOnPins[Pins.D] = (newValue >> 3) & 1 == 1
switchesOnPins[Pins.E] = (newValue >> 4) & 1 == 1
switchesOnPins[Pins.F] = (newValue >> 5) & 1 == 1
switchesOnPins[Pins.G] = (newValue >> 6) & 1 == 1
switchesOnPins[Pins.DP] = (newValue >> 7) & 1 == 1
switchesOnPins[Pins.QM] = (newValue >> 8) & 1 == 1
setNeedsDisplay()
}
get {
var value: Int16 = 0
value |= (switchesOnPins[Pins.A]! ? 1 : 0) << 0
value |= (switchesOnPins[Pins.B]! ? 1 : 0) << 1
value |= (switchesOnPins[Pins.C]! ? 1 : 0) << 2
value |= (switchesOnPins[Pins.D]! ? 1 : 0) << 3
value |= (switchesOnPins[Pins.E]! ? 1 : 0) << 4
value |= (switchesOnPins[Pins.F]! ? 1 : 0) << 5
value |= (switchesOnPins[Pins.G]! ? 1 : 0) << 6
value |= (switchesOnPins[Pins.DP]! ? 1 : 0) << 7
value |= (switchesOnPins[Pins.QM]! ? 1 : 0) << 8
return value
}
}
@IBInspectable
var onColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var offColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
onColor = tintColor
offColor = tintColor.colorWithAlphaComponent(0.05)
self.backgroundColor = UIColor.clearColor()
}
}
| mit | 675b79f1e8f19c9e9fe5d91f90e34aa6 | 22.926316 | 140 | 0.474043 | 4.375361 | false | false | false | false |
hyperoslo/Catalog | Source/Models/Card.swift | 1 | 239 | import Foundation
public class Card: NSObject {
public var item: Item?
public var relatedItems = [Item]()
public init(item: Item? = nil, relatedItems: [Item] = []) {
self.item = item
self.relatedItems = relatedItems
}
}
| mit | 054e76e1382279508c61c7818cc716a6 | 18.916667 | 61 | 0.661088 | 3.676923 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Internals/Microtonality/TuningTable+Scala.swift | 2 | 8985 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
extension TuningTable {
/// Use a Scala file to write the tuning table. Returns notes per octave or nil when file couldn't be read.
public func scalaFile(_ filePath: String) -> Int? {
guard
let contentData = FileManager.default.contents(atPath: filePath),
let contentStr = String(data: contentData, encoding: .utf8) else {
Log("can't read filePath: \(filePath)")
return nil
}
if let scalaFrequencies = frequencies(fromScalaString: contentStr) {
let npo = tuningTable(fromFrequencies: scalaFrequencies)
return npo
}
// error
return nil
}
fileprivate func stringTrimmedForLeadingAndTrailingWhiteSpacesFromString(_ inputString: String?) -> String? {
guard let string = inputString else {
return nil
}
let leadingTrailingWhiteSpacesPattern = "(?:^\\s+)|(?:\\s+$)"
let regex: NSRegularExpression
do {
try regex = NSRegularExpression(pattern: leadingTrailingWhiteSpacesPattern,
options: .caseInsensitive)
} catch let error as NSError {
Log("ERROR: create regex: \(error)")
return nil
}
let stringRange = NSRange(location: 0, length: string.count)
let trimmedString = regex.stringByReplacingMatches(in: string,
options: .reportProgress,
range: stringRange,
withTemplate: "$1")
return trimmedString
}
/// Get frequencies from a Scala string
public func frequencies(fromScalaString rawStr: String?) -> [Frequency]? {
guard let inputStr = rawStr else {
return nil
}
// default return value is [1.0]
var scalaFrequencies = [Frequency(1)]
var actualFrequencyCount = 1
var frequencyCount = 1
var parsedScala = true
var parsedFirstCommentLine = false
let values = inputStr.components(separatedBy: .newlines)
var parsedFirstNonCommentLine = false
var parsedAllFrequencies = false
// REGEX match for a cents or ratio
// (RATIO |CENTS )
// ( a / b |- a . b |- . b |- a .|- a )
let regexStr = "(\\d+\\/\\d+|-?\\d+\\.\\d+|-?\\.\\d+|-?\\d+\\.|-?\\d+)"
let regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: regexStr,
options: .caseInsensitive)
} catch let error as NSError {
Log("ERROR: cannot parse scala file: \(error)")
return scalaFrequencies
}
for rawLineStr in values {
var lineStr = stringTrimmedForLeadingAndTrailingWhiteSpacesFromString(rawLineStr) ?? rawLineStr
if lineStr.isEmpty { continue }
if lineStr.hasPrefix("!") {
if !parsedFirstCommentLine {
parsedFirstCommentLine = true
#if false
// currently not using the scala file name embedded in the file
let components = lineStr.components(separatedBy: "!")
if components.count > 1 {
proposedScalaFilename = components[1]
}
#endif
}
continue
}
if !parsedFirstNonCommentLine {
parsedFirstNonCommentLine = true
#if false
// currently not using the scala short description embedded in the file
scalaShortDescription = lineStr
#endif
continue
}
if parsedFirstNonCommentLine && !parsedAllFrequencies {
if let newFrequencyCount = Int(lineStr) {
frequencyCount = newFrequencyCount
if frequencyCount == 0 || frequencyCount > 127 {
// #warning SPEC SAYS 0 notes is okay because 1/1 is implicit
Log("ERROR: number of notes in scala file: \(frequencyCount)")
parsedScala = false
break
} else {
parsedAllFrequencies = true
continue
}
}
}
if actualFrequencyCount > frequencyCount {
Log("actual frequency cont: \(actualFrequencyCount) > frequency count: \(frequencyCount)")
}
/* The first note of 1/1 or 0.0 cents is implicit and not in the files.*/
// REGEX defined above this loop
let rangeOfFirstMatch = regex.rangeOfFirstMatch(
in: lineStr,
options: .anchored,
range: NSRange(location: 0, length: lineStr.count))
if NSEqualRanges(rangeOfFirstMatch, NSRange(location: NSNotFound, length: 0)) == false {
let nsLineStr = lineStr as NSString?
let substringForFirstMatch = nsLineStr?.substring(with: rangeOfFirstMatch) as NSString? ?? ""
if substringForFirstMatch.range(of: ".").length != 0 {
if var scaleDegree = Frequency(lineStr) {
// ignore 0.0...same as 1.0, 2.0, etc.
if scaleDegree != 0 {
scaleDegree = fabs(scaleDegree)
// convert from cents to frequency
scaleDegree /= 1_200
scaleDegree = pow(2, scaleDegree)
scalaFrequencies.append(scaleDegree)
actualFrequencyCount += 1
continue
}
}
} else {
if substringForFirstMatch.range(of: "/").length != 0 {
if substringForFirstMatch.range(of: "-").length != 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
}
// Parse rational numerator/denominator
let slashPos = substringForFirstMatch.range(of: "/")
let numeratorStr = substringForFirstMatch.substring(to: slashPos.location)
let numerator = Int(numeratorStr) ?? 0
let denominatorStr = substringForFirstMatch.substring(from: slashPos.location + 1)
let denominator = Int(denominatorStr) ?? 0
if denominator == 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
} else {
let mt = Frequency(numerator) / Frequency(denominator)
if mt == 1.0 || mt == 2.0 {
// skip 1/1, 2/1
continue
} else {
scalaFrequencies.append(mt)
actualFrequencyCount += 1
continue
}
}
} else {
// a whole number, treated as a rational with a denominator of 1
if let whole = Int(substringForFirstMatch as String) {
if whole <= 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
} else if whole == 1 || whole == 2 {
// skip degrees of 1 or 2
continue
} else {
scalaFrequencies.append(Frequency(whole))
actualFrequencyCount += 1
continue
}
}
}
}
} else {
Log("ERROR: error parsing: \(lineStr)")
continue
}
}
if !parsedScala {
Log("FATAL ERROR: cannot parse Scala file")
return nil
}
Log("frequencies: \(scalaFrequencies)")
return scalaFrequencies
}
}
| mit | 507196f369eeff8ae1bf39199a367d18 | 41.785714 | 113 | 0.466667 | 6.287614 | false | false | false | false |
ustwo/mongolabkit-swift | MongoLabKit/Sources/Classes/MongoLabResponseParser.swift | 1 | 900 | //
// MongoLabResponseParser.swift
// MongoLabKit
//
// Created by luca strazzullo on 12/03/16.
// Copyright © 2016 ustwo. All rights reserved.
//
import Foundation
class MongoLabResponseParser {
func parse(_ data: Data?, response: URLResponse?, error: Error?) throws -> AnyObject {
guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
throw MongoLabError.connectionError
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) else {
throw MongoLabError.parserError
}
guard httpResponse.statusCode == 200 || httpResponse.statusCode == 201 else {
throw try MongoLabErrorParser().errorFrom(data, statusCode: httpResponse.statusCode)
}
return jsonObject as AnyObject
}
}
| mit | f200ffe20a63b0d66cab250a580ef24b | 30 | 144 | 0.679644 | 4.859459 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/通讯录/通讯录/HJDictToModelTool.swift | 1 | 1174 | //
// HJDictToModelTool.swift
// 通讯录
//
// Created by liuhj on 16/4/5.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
class HJDictToModelTool: NSObject {
//
// static func dataTool(dict : NSDictionary) ->AnyObject {
//
// let conn = HJConnect()
// conn.name = dict["name"] as? String
// conn.telNum = dict["telNum"] as? String
// conn.email = dict["email"] as? String
// conn.addr = dict["addr"] as? String
//
//
//
// return conn
// }
class func getConnArr() ->NSArray {
let connArray = NSMutableArray()
let path = NSBundle.mainBundle().pathForResource("ConnectList", ofType: "plist")
let arr = NSArray.init(contentsOfFile: path!)
for dict in arr! {
let conn = HJConnect()
conn.setValuesForKeysWithDictionary(dict as! [String : AnyObject])
connArray.addObject(conn)
}
return connArray.copy() as! NSArray
}
}
| apache-2.0 | 28eeee6dd46d59a1e908c4e7888f09b4 | 23.787234 | 92 | 0.493562 | 4.396226 | false | false | false | false |
jeden/kocomojo-kit | KocomojoKit/KocomojoKit/entities/Plan.swift | 1 | 1489 | //
// Plan.swift
// KocomojoKit
//
// Created by Antonio Bello on 1/26/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
import Foundation
public struct Plan {
public var recommended: Bool
public var nickName: String
public var name: String
public var description: String
public var monthlyFee: Double
public var features: [String]
init(recommended: Bool, nickName: String, name: String, description: String, monthlyFee: Double, features: [String]) {
self.recommended = recommended
self.nickName = nickName
self.name = name
self.description = description
self.monthlyFee = monthlyFee
self.features = features
}
}
extension Plan : JsonDecodable {
static func create(recommended: Bool)(nickName: String)(name: String)(description: String)(monthlyFee: Double)(features: [JsonType]) -> Plan {
return Plan(recommended: recommended, nickName: nickName, name: name, description: description, monthlyFee: monthlyFee, features: features as [String])
}
public static func decode(json: JsonType) -> Plan? {
let a = Plan.create <^> json["recommended"] >>> JsonBool
let b = a <&&> json["nick_name"] >>> JsonString
let c = b <&&> json["name"] >>> JsonString
let d = c <&&> json["description"] >>> JsonString
let e = d <&&> json["monthly_fee"] >>> JsonDouble
let f = e <&&> json["features"] >>> JsonArrayType
return f
}
}
| mit | 32ed6af32ce8bdf565a1aa006543fd09 | 33.627907 | 159 | 0.640027 | 4.254286 | false | false | false | false |
dkerzig/CAJ-Einschreibungen | CAJ-Einschreibungen/TableViewController.swift | 1 | 5303 | //
// ViewController.swift
// CAJ-Einschreibungen
//
// Contains Cocoa-Touch and Foundation
// Informations: https://goo.gl/g0H9Q1
import UIKit
// The ViewController of our Course-Table which is asked for the contents
// of the table by the table itself, because we have marked this class as
// 'UITableViewDataSource' in the Interface-Builder ('.storyboard'-file).
// It also cares about instantiating a 'CAJController'-instance, asking it
// to fetch 'CAJCourses' and handles the results as a 'CAJControllerDelegate'.
class TableViewController: UITableViewController, UITableViewDataSource, CAJControllerDelegate {
// MARK: - VARIABLES
// An array of all Courses which is empty by default
var courses: [CAJCourse] = []
// Our instance of 'CAJController' which fetches the data from the CAJ
var cajController: CAJController? = nil
// A "lazily" computed property which represents the modal-view which
// pops up and asks for username&password. Lazy means the closure will
// execute first just after the property is used it's first time.
// Informations: https://goo.gl/QNiQxr
lazy var loginAlertController: UIAlertController = { [unowned self] in
// Create Alert Controller with title and subtitle
let alertController = UIAlertController(title: "CAJ-Anmeldung", message: "Gib dein Nutzerkürzel mit entsprechendem Passwort ein, um fortzufahren.", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { $0.placeholder = "Benutzerkürzel" }
alertController.addTextFieldWithConfigurationHandler { $0.placeholder = "Passwort"; $0.secureTextEntry = true }
// Add "Anmelden"-Action
alertController.addAction(UIAlertAction(title: "Anmelden", style: .Default) { _ in
// Get Textfields
let nameField = alertController.textFields?[0] as! UITextField
let pwField = alertController.textFields?[1] as! UITextField
// Instantiate CAJController with username & password
self.cajController = CAJController(username: nameField.text, password: pwField.text)
self.cajController?.delegate = self
self.cajController?.loginAndGetCourses()
})
// Add "Abbrechen"-Action
alertController.addAction(UIAlertAction(title: "Abbrechen", style: .Destructive) { _ in })
return alertController
}()
// MARK: - VIEW-CONTROLLER-LIFECYCLE
// This function is called after the view-hierachy did
// loaded successfully from the memory
override func viewDidLoad() {
super.viewDidLoad()
// Start Loading
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: Selector("loadCAJCourses"), forControlEvents: .ValueChanged)
self.refreshControl?.beginRefreshing()
self.loadCAJCourses()
}
// MARK: - FETCH/GET CAJ-COURSES
// If we already passed in our password/username this method
// asks the 'cajController' to fetch again, otherwise the 'loginAlertController'
// is prompted, and it's completion-handler intantiates our
// 'cajController' and asks it to fetch the data from CAJ.
func loadCAJCourses() {
// Ask for Login and Passwort if nil, otherwise fetch again
if self.cajController == nil {
self.parentViewController?.presentViewController(self.loginAlertController, animated: true, completion: nil)
} else {
self.cajController!.loginAndGetCourses()
}
}
// Becourse web-requests should not be handled synchronously, we don't
// get any results from the 'loginAndGetCourses' function. Has the
// 'cajController' fetched everything successfully it's calling this
// method. The compiler knows that we implement this method because we
// conform to the 'CAJControllerDelegate'.
func didLoadCAJCourses(fetchedCourses: [CAJCourse]?) {
if fetchedCourses != nil {
self.courses = fetchedCourses!
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
// MARK: - UITableViewDataSource
// We return the number of rows which is equivalent to the number of courses
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses.count
}
// We create a new cell (actually we 'dequeue a reusable' one but don't care about that)
// and customize it to display the Course-Name, -Dozent, ... in it's labels.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CourseCell", forIndexPath: indexPath) as! UITableViewCell
let course = self.courses[indexPath.row]
let courseShortType = "[" + (course.typ as NSString).substringToIndex(1) + "]"
cell.textLabel?.text = "\(courseShortType) \(course.name) von \(course.dozent)"
cell.detailTextLabel?.text = "Ort: \(course.ort), Zeit: \(course.zeit)"
return cell
}
}
| mit | 3215cd572c5701af7b2e251839a4b04c | 41.071429 | 179 | 0.673646 | 4.854396 | false | false | false | false |
JeziL/WeekCount | WeekCount/StatusMenuController.swift | 1 | 5640 | //
// StatusMenuController.swift
// WeekCount
//
// Created by Li on 16/6/13.
// Copyright © 2016 Jinli Wang. All rights reserved.
//
import Cocoa
let DEFAULT_STARTDATE = Date()
let DEFAULT_LASTCOUNT = 18
let DEFAULT_DISPLAYFORMAT = "Week {W}"
let DEFAULT_FONTSIZE: Float = 14.2
class StatusMenuController: NSObject, PreferencesWindowDelegate {
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet weak var dateMenuItem: NSMenuItem!
var preferencesWindow: PreferencesWindow!
var aboutWindow: AboutWindow!
var startDate: Date!
var lastCount: Int!
var displayFormat: String!
var fontSize: Float!
var autoLaunch: Int!
var sem: Semester!
var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
override func awakeFromNib() {
preferencesWindow = PreferencesWindow()
aboutWindow = AboutWindow()
preferencesWindow.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.updateAll), name: NSNotification.Name(rawValue: "URLSchemesUpdate"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.showPreferencesWindow), name: NSNotification.Name(rawValue: "URLSchemesShowPreferences"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.quit), name: NSNotification.Name(rawValue: "URLSchemesQuit"), object: nil)
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(StatusMenuController.updateAll), userInfo: nil, repeats: true)
let loop = RunLoop.main
loop.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
statusMenu.items.last!.action = #selector(StatusMenuController.quit)
statusItem.menu = statusMenu
}
@IBAction func showPreferencesWindow(sender: NSMenuItem) {
NSApp.activate(ignoringOtherApps: true)
preferencesWindow.showWindow(nil)
}
@IBAction func showAboutWindow(sender: NSMenuItem) {
NSApp.activate(ignoringOtherApps: true)
aboutWindow.showWindow(nil)
}
@IBAction func quitApp(_ sender: NSMenuItem) {
quit()
}
@objc func quit() {
NSApplication.shared.terminate(self)
}
func resetPreferences() {
UserDefaults.standard.setPersistentDomain(["":""], forName: Bundle.main.bundleIdentifier!)
updateAll()
}
@objc func updateAll() {
let formatter = DateFormatter()
formatter.locale = NSLocale.autoupdatingCurrent
formatter.dateStyle = .full
dateMenuItem.title = formatter.string(from: Date())
updatePreferences()
updateDisplay()
}
func preferencesDidUpdate() {
updateAll()
}
func updatePreferences() {
let defaults = UserDefaults.standard
startDate = defaults.value(forKey: "startDate") as? Date ?? DEFAULT_STARTDATE
if let count = defaults.string(forKey: "lastCount") {
if let countNo = Int(count) {
lastCount = countNo
} else { lastCount = DEFAULT_LASTCOUNT }
} else { lastCount = DEFAULT_LASTCOUNT }
displayFormat = defaults.string(forKey: "displayFormat") ?? DEFAULT_DISPLAYFORMAT
if let size = defaults.string(forKey: "fontSize") {
if let sizeNo = Float(size) {
fontSize = sizeNo
} else { fontSize = DEFAULT_FONTSIZE }
} else { fontSize = DEFAULT_FONTSIZE }
sem = Semester.init(startDate: startDate, lastCount: lastCount)
}
func updateDisplay() {
if let button = statusItem.button {
button.attributedTitle = showWeekCount(count: sem.getWeekNo())
}
}
func convertToChinese(count: Int) -> String {
let hiDict = [0: "", 1: "十", 2: "二十", 3: "三十", 4: "四十", 5: "五十", 6: "六十", 7: "七十", 8: "八十", 9: "九十"]
let loDict = [0: "", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九"]
guard (count > 0 && count < 100) else { return "" }
let hi = count / 10
let lo = count % 10
return hiDict[hi]! + loDict[lo]!
}
func iso8601Format(str: String) -> String {
var str = str
let formatter = DateFormatter()
formatter.locale = NSLocale.autoupdatingCurrent
let supportedStrings = ["YYYY", "YY", "Y", "yyyy", "yy", "y", "MM", "M", "dd", "d", "EEEE", "eeee", "HH", "H", "hh", "h", "mm", "m", "ss", "s"]
for e in supportedStrings {
formatter.dateFormat = e
let convertedStr = formatter.string(from: Date())
str = str.replacingOccurrences(of: e, with: convertedStr)
}
str = str.replacingOccurrences(of: "星期", with: "周")
return str
}
func showWeekCount(count: Int) -> NSAttributedString {
let font = NSFont.systemFont(ofSize: CGFloat(fontSize))
if count > 0 {
var rawStr = displayFormat.replacingOccurrences(of: "{W}", with: String(count))
rawStr = rawStr.replacingOccurrences(of: "{zhW}", with: convertToChinese(count: count))
rawStr = iso8601Format(str: rawStr)
return NSAttributedString.init(string: rawStr, attributes: [NSAttributedStringKey.font: font])
} else {
return NSAttributedString.init(string: "WeekCount", attributes: [NSAttributedStringKey.font: font])
}
}
}
| gpl-2.0 | 4f862e067500fdd955b21f4d6cdd364e | 37.226027 | 196 | 0.624082 | 4.404893 | false | false | false | false |
nerdycat/Cupcake | Cupcake-Demo/Cupcake-Demo/AppStoreViewController.swift | 1 | 3902 | //
// AppStoreViewController.swift
// Cupcake-Demo
//
// Created by nerdycat on 2017/5/15.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
class AppStoreCell: UITableViewCell {
var iconView: UIImageView!
var actionButton: UIButton!
var indexLabel, titleLabel, categoryLabel: UILabel!
var ratingLabel, countLabel, iapLabel: UILabel!
func update(app: Dictionary<String, Any>, index: Int) {
indexLabel.str(index + 1)
iconView.img(app["iconName"] as! String)
titleLabel.text = app["title"] as? String
categoryLabel.text = app["category"] as? String
countLabel.text = Str("(%@)", app["commentCount"] as! NSNumber)
iapLabel.isHidden = !(app["iap"] as! Bool)
let rating = (app["rating"] as! NSNumber).intValue
var result = ""
for i in 0..<5 { result = result + (i < rating ? "★" : "☆") }
ratingLabel.text = result
let price = app["price"] as! String
actionButton.str( price.count > 0 ? "$" + price : "GET")
}
func setupUI() {
indexLabel = Label.font(17).color("darkGray").align(.center).pin(.w(44))
iconView = ImageView.pin(64, 64).radius(10).border(1.0 / UIScreen.main.scale, "#CCC")
titleLabel = Label.font(15).lines(2)
categoryLabel = Label.font(13).color("darkGray")
ratingLabel = Label.font(11).color("orange")
countLabel = Label.font(11).color("darkGray")
actionButton = Button.font("15").color("#0065F7").border(1, "#0065F7").radius(3)
actionButton.highColor("white").highBg("#0065F7").padding(5, 10)
iapLabel = Label.font(9).color("darkGray").lines(2).str("In-App\nPurchases").align(.center)
let ratingStack = HStack(ratingLabel, countLabel).gap(5)
let midStack = VStack(titleLabel, categoryLabel, ratingStack).gap(4)
let actionStack = VStack(actionButton, iapLabel).gap(4).align(.center)
HStack(indexLabel, iconView, 10, midStack, "<-->", 10, actionStack).embedIn(self.contentView, 10, 0, 10, 15)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class AppStoreViewController: UITableViewController {
var appList: Array<Dictionary<String, Any>>!
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AppStoreCell
let app = self.appList[indexPath.row]
cell.update(app: app, index: indexPath.row)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 84
self.tableView.register(AppStoreCell.self, forCellReuseIdentifier: "cell")
self.tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 34, right: 0)
let path = Bundle.main.path(forResource: "appList", ofType: "plist")
appList = NSArray(contentsOfFile: path!) as? Array<Dictionary<String, Any>>
for _ in 1..<5 { appList.append(contentsOf: appList) }
}
}
| mit | 5bc984b94a60c5aebfa08894b908ad19 | 37.584158 | 116 | 0.635874 | 4.325194 | false | false | false | false |
GuoMingJian/DouYuZB | DYZB/DYZB/Classes/Home/Controller/AmuseViewController.swift | 1 | 3867 | //
// AmuseViewController.swift
// DYZB
//
// Created by 郭明健 on 2017/12/22.
// Copyright © 2017年 com.joy.www. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - kItemMargin * 3) / 2
private let kItemNormalH = kItemW * 3 / 4
private let kItemPrettyH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kHeaderViewID = "kHeaderViewID"
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
class AmuseViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemNormalH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//2.创建collectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]//随着父控件缩小而缩小
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
//3.注册cell
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
return collectionView
}()
//MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK:- 设置UI界面
extension AmuseViewController {
fileprivate func setupUI() {
view.addSubview(collectionView)
}
}
//MARK:- 请求数据
extension AmuseViewController {
fileprivate func loadData() {
amuseVM.loadAmuseData {
self.collectionView.reloadData()
}
}
}
//MARK:- 遵守UICollectionView的数据源协议
extension AmuseViewController : UICollectionViewDataSource, UICollectionViewDelegate
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return amuseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return amuseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.取出模型对象
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
//2.给cell设置数据
cell.anchor = amuseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
//2.给HeaderView设置数据
headerView.group = amuseVM.anchorGroups[indexPath.section]
return headerView
}
}
| mit | 8aaaa1c964f02bdfd70a73f4ae59e2ad | 33.275229 | 186 | 0.722698 | 5.461988 | false | false | false | false |
lacklock/ReactiveCocoaExtension | Pods/ReactiveSwift/Sources/Flatten.swift | 2 | 34893 | //
// Flatten.swift
// ReactiveSwift
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case merge
/// The producers should be concatenated, so that their values are sent in
/// the order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed
/// of.
///
/// The resulting producer will complete only when the producer-of-producers
/// and the latest producer has completed.
case latest
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - note: `interrupted` events on inner producers will be treated like
/// `Completed events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner signal emits an error, the
/// returned signal will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned signal
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `signal` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init($0) }
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner signal emits an error, the
/// returned producer will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned producer
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` emits an error, the returned producer will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `producer` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init($0) }
}
}
extension SignalProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProducerProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted
/// from `signal`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers fail, the returned signal will
/// forward that failure immediately
///
/// - note: The returned signal completes only when `signal` and all
/// producers emitted from `signal` complete.
fileprivate func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeConcat(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = Atomic(ConcatState<Value.Value, Error>())
func startNextIfNeeded() {
while let producer = state.modify({ $0.dequeue() }) {
producer.startWithSignal { signal, inner in
let handle = disposable?.add(inner)
signal.observe { event in
switch event {
case .completed, .interrupted:
handle?.remove()
let shouldStart: Bool = state.modify {
$0.active = nil
return !$0.isStarting
}
if shouldStart {
startNextIfNeeded()
}
case .value, .failed:
observer.action(event)
}
}
}
state.modify { $0.isStarting = false }
}
}
return observe { event in
switch event {
case let .value(value):
state.modify { $0.queue.append(value.producer) }
startNextIfNeeded()
case let .failed(error):
observer.send(error: error)
case .completed:
state.modify { state in
state.queue.append(SignalProducer.empty.on(completed: observer.sendCompleted))
}
startNextIfNeeded()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted
/// from `producer`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers emit an error, the returned
/// producer will emit that error.
///
/// - note: The returned producer completes only when `producer` and all
/// producers emitted from `producer` complete.
fileprivate func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerProtocol {
/// `concat`s `next` onto `self`.
public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>([ self.producer, next ]).flatten(.concat)
}
/// `concat`s `value` onto `self`.
public func concat(value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
public func prefix<P: SignalProducerProtocol>(_ previous: P) -> SignalProducer<Value, Error>
where P.Value == Value, P.Error == Error
{
return previous.concat(self.producer)
}
/// `concat`s `self` onto initial `value`.
public func prefix(value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcatState<Value, Error: Swift.Error> {
typealias SignalProducer = ReactiveSwift.SignalProducer<Value, Error>
/// The active producer, if any.
var active: SignalProducer? = nil
/// The producers waiting to be started.
var queue: [SignalProducer] = []
/// Whether the active producer is currently starting.
/// Used to prevent deep recursion.
var isStarting: Bool = false
/// Dequeue the next producer if one should be started.
///
/// - note: The caller *must* set `isStarting` to false after the returned
/// producer has been started.
///
/// - returns: The `SignalProducer` to start or `nil` if no producer should
/// be started.
func dequeue() -> SignalProducer? {
if active != nil {
return nil
}
active = queue.first
if active != nil {
queue.removeFirst()
isStarting = true
}
return active
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeMerge(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let shouldComplete: Bool = inFlight.modify {
$0 -= 1
return $0 == 0
}
if shouldComplete {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .value(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 += 1 }
let handle = disposable.add(innerDisposable)
innerSignal.observe { event in
switch event {
case .completed, .interrupted:
handle.remove()
decrementInFlight()
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
decrementInFlight()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalProtocol {
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<Seq: Sequence, S: SignalProtocol>(_ signals: Seq) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer<S, Error>(signals)
.flatten(.merge)
.startAndRetrieveSignal()
}
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<S: SignalProtocol>(_ signals: S...) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error
{
return Signal.merge(signals)
}
}
extension SignalProducerProtocol {
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<Seq: Sequence, S: SignalProducerProtocol>(_ producers: Seq) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer(producers).flatten(.merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<S: SignalProducerProtocol>(_ producers: S...) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error
{
return SignalProducer.merge(producers)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
fileprivate func observeSwitchToLatest(_ observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .value(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents
// the generated Interrupted event from doing any work.
$0.replacingInnerSignal = true
}
latestInnerDisposable.inner = innerDisposable
state.modify {
$0.replacingInnerSignal = false
$0.innerSignalComplete = false
}
innerSignal.observe { event in
switch event {
case .interrupted:
// If interruption occurred as a result of a new
// producer arriving, we don't want to notify our
// observer.
let shouldComplete: Bool = state.modify { state in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return !state.replacingInnerSignal && state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.innerSignalComplete = true
return $0.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.outerSignalComplete = true
return $0.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable += latestInnerDisposable
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: Swift.Error> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalProtocol {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new property, then flattens the
/// resulting properties (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> Signal<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new property, then flattens the
/// resulting properties (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> SignalProducer<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol {
/// Catches any failure that may occur on the input signal, mapping to a new
/// producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
observer.send(value: value)
case let .failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.inner = disposable
signal.observe(observer)
}
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol {
/// Catches any failure that may occur on the input producer, mapping to a
/// new producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable += serialDisposable
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
_ = signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| mit | 217be06e5cd0c1d94878fb57fc675e35 | 35.383733 | 185 | 0.705405 | 4.104458 | false | false | false | false |
gabek/GitYourFeedback | Example/Pods/GRMustache.swift/Sources/ExpressionParser.swift | 2 | 19007 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
final class ExpressionParser {
func parse(_ string: String, empty outEmpty: inout Bool) throws -> Expression {
enum State {
// error
case error(String)
// Any expression can start
case waitingForAnyExpression
// Expression has started with a dot
case leadingDot
// Expression has started with an identifier
case identifier(identifierStart: String.Index)
// Parsing a scoping identifier
case scopingIdentifier(identifierStart: String.Index, baseExpression: Expression)
// Waiting for a scoping identifier
case waitingForScopingIdentifier(baseExpression: Expression)
// Parsed an expression
case doneExpression(expression: Expression)
// Parsed white space after an expression
case doneExpressionPlusWhiteSpace(expression: Expression)
}
var state: State = .waitingForAnyExpression
var filterExpressionStack: [Expression] = []
var i = string.startIndex
let end = string.endIndex
stringLoop: while i < end {
let c = string[i]
switch state {
case .error:
break stringLoop
case .waitingForAnyExpression:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
state = .leadingDot
case "(", ")", ",", "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .identifier(identifierStart: i)
}
case .leadingDot:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: Expression.implicitIterator)
case ".":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
filterExpressionStack.append(Expression.implicitIterator)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: Expression.implicitIterator)
}
case .identifier(identifierStart: let identifierStart):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substring(with: identifierStart..<i)
state = .doneExpressionPlusWhiteSpace(expression: Expression.identifier(identifier: identifier))
case ".":
let identifier = string.substring(with: identifierStart..<i)
state = .waitingForScopingIdentifier(baseExpression: Expression.identifier(identifier: identifier))
case "(":
let identifier = string.substring(with: identifierStart..<i)
filterExpressionStack.append(Expression.identifier(identifier: identifier))
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .doneExpressionPlusWhiteSpace(expression: scopedExpression)
case ".":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .waitingForScopingIdentifier(baseExpression: scopedExpression)
case "(":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(scopedExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .waitingForScopingIdentifier(let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .error("Unexpected white space character at index \(string.characters.distance(from: string.startIndex, to: i))")
case ".":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case ")":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case ",":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: baseExpression)
}
case .doneExpression(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: doneExpression)
case ".":
state = .waitingForScopingIdentifier(baseExpression: doneExpression)
case "(":
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
// Prevent "a .b"
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
// Accept "a (b)"
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
// Accept "a(b )"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
// Accept "a(b ,c)"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
}
i = string.index(after: i)
}
// Parsing done
enum FinalState {
case error(String)
case empty
case valid(expression: Expression)
}
let finalState: FinalState
switch state {
case .waitingForAnyExpression:
if filterExpressionStack.isEmpty {
finalState = .empty
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .leadingDot:
if filterExpressionStack.isEmpty {
finalState = .valid(expression: Expression.implicitIterator)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .identifier(identifierStart: let identifierStart):
if filterExpressionStack.isEmpty {
let identifier = string.substring(from: identifierStart)
finalState = .valid(expression: Expression.identifier(identifier: identifier))
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
if filterExpressionStack.isEmpty {
let identifier = string.substring(from: identifierStart)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
finalState = .valid(expression: scopedExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .waitingForScopingIdentifier:
finalState = .error("Missing identifier at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
case .doneExpression(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .error(let message):
finalState = .error(message)
}
// End
switch finalState {
case .empty:
outEmpty = true
throw MustacheError(kind: .parseError, message: "Missing expression")
case .error(let description):
outEmpty = false
throw MustacheError(kind: .parseError, message: "Invalid expression `\(string)`: \(description)")
case .valid(expression: let expression):
return expression
}
}
}
| mit | 0da38e86ad8ae28144116b49641bbf0f | 53.772334 | 200 | 0.55614 | 6.247863 | false | false | false | false |
red-spotted-newts-2014/rest-less-ios | Rest Less/http_post.playground/section-1.swift | 1 | 1321 | import Foundation
import XCPlayground
func HTTPostJSON(url: String,
jsonObj: AnyObject)
{
var request = NSMutableURLRequest(URL: NSURL(string: url))
var session = NSURLSession.sharedSession()
var jsonError:NSError?
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject( jsonObj, options: nil, error: &jsonError)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var subTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var jsonRError: NSError?
var json_response = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &jsonRError) as? NSDictionary
println(jsonRError)
jsonRError?
if jsonRError? != nil {
println(jsonRError!.localizedDescription)
}
else {
json_response
}
})
subTask.resume()
}
var params = ["workout_type":"weights"] as Dictionary
HTTPostJSON("http://secret-stream-5880.herokuapp.com/exercises", params)
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) | mit | de25c52b5ce809ef8254e980a455d991 | 32.897436 | 134 | 0.698713 | 4.768953 | false | false | false | false |
inacioferrarini/StoryboardFlowCoordinator | StoryboardFlowCoordinator/User/ViewController/UserPJDetails/UserPJDetailsViewController.swift | 1 | 1619 | //
// UserPJDetailsViewController.swift
// StoryboardFlowCoordinator
//
// Created by Inácio on 27/11/16.
// Copyright © 2016 com.inacioferrarini.gh. All rights reserved.
//
import UIKit
class UserPJDetailsViewController: UIViewController {
var delegate: UserPJDetailsViewControllerDelegate?
var userDetailsData: UserPJData?
@IBOutlet weak var name: UITextField!
@IBOutlet weak var cnpj: UITextField!
@IBOutlet weak var email: UITextField!
override func viewWillAppear(_ animated: Bool) {
self.setData(userDetailsData)
}
func setData(_ data: UserPJData?) {
self.name.text = data?.name ?? ""
self.cnpj.text = data?.cnpj ?? ""
self.email.text = data?.email ?? ""
}
func getUserData() -> UserPJData {
let data = UserPJData()
data.name = self.name.text ?? ""
data.cnpj = self.cnpj.text ?? ""
data.email = self.email.text ?? ""
return data
}
// MARK: - Actions
@IBAction func next() {
let userDetailsData = self.getUserData()
self.userDetailsData = userDetailsData
self.delegate?.didInformedPJUserData(userDetailsData)
}
}
extension UserPJDetailsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.name {
self.cnpj.becomeFirstResponder()
} else if textField == self.cnpj {
self.email.becomeFirstResponder()
} else {
next()
}
return true
}
}
| mit | fecea8c564738d09f21bde296fe86ab3 | 24.666667 | 66 | 0.607297 | 4.55493 | false | false | false | false |
xiaoxinghu/swift-org | Sources/Lexer.swift | 1 | 1242 | //
// Lexer.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 14/08/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
public enum LexerErrors: Error {
case tokenizeFailed(Int, String)
}
open class Lexer {
let lines: [String]
public init(lines theLines: [String]) {
lines = theLines
}
/// Tokenize one line, without considering the context
///
/// - Parameter line: the target line
/// - Returns: the token
class func tokenize(line: String) -> Token? {
defineTokens()
for td in tokenDescriptors {
guard let m = line.match(td.pattern, options: td.options) else { continue }
return td.generator(m)
}
return nil
}
func tokenize(cursor: Int = 0, tokens: [TokenInfo] = []) throws -> [TokenInfo] {
if lines.count == cursor { return tokens }
let line = lines[cursor]
guard let token = Lexer.tokenize(line: line) else {
throw LexerErrors.tokenizeFailed(cursor, line)
}
return try tokenize(
cursor: cursor + 1,
tokens: tokens + [(TokenMeta(raw: line, lineNumber: cursor), token)])
}
}
| mit | 99c0c31a0951e481ad3f132dc0eb0403 | 24.854167 | 87 | 0.575342 | 4.178451 | false | false | false | false |
chriswunsch00/CWCoreData | CWCoreData/Classes/CoreDataExtensions.swift | 1 | 6990 | //
// ManagedObjectHelpers.swift
// CoreDataHelper
//
// Created by Chris Wunsch on 17/10/2016.
// Copyright © 2016 Minty Water Ltd. All rights reserved.
//
import Foundation
import CoreData
public extension NSManagedObjectContext
{
/// Delete more than one managed object quickly and easily.
///
/// - Parameter objects: the objects to delete
func delete(allObjects objects : [NSManagedObject]) {
for object in objects {
delete(object)
}
}
}
public extension NSManagedObject
{
/// Insert a new record into the database. This will return the newly created managed object
///
/// - Parameter context: the context in which to insert the record
/// - Returns: a new NSManagedObject
class func insertNewInstance(withContext context : NSManagedObjectContext) -> NSManagedObject
{
return NSEntityDescription.insertNewObject(forEntityName: self.className, into: context)
}
/// The entity description for the object in the database
///
/// - Parameter context: the context in whch the entity exists
/// - Returns: the NSEntityDescription for the object
class func entityDescription(withContext context : NSManagedObjectContext) -> NSEntityDescription
{
return NSEntityDescription.entity(forEntityName: self.className, in: context)!
}
/// Create a fetch request with the provided context
///
/// - Parameter context: the context for which the fetch request should be created
/// - Returns: the NSFetchRequest
class func fetchRequest(withContext context : NSManagedObjectContext) -> NSFetchRequest<NSManagedObject>
{
let request : NSFetchRequest<NSManagedObject> = NSFetchRequest()
request.entity = entityDescription(withContext: context)
return request
}
/// Create a fetch request with a batch size and an offset.
///
/// - Parameters:
/// - context: the context for which the fetch request should be created
/// - batch: the size of the batch of objects to fetch
/// - offsetSize: the offset to use
/// - Returns: the NSFetchRequest
class func fetchRequest(withContext context : NSManagedObjectContext, batchSize batch : Int, offset offsetSize : Int = 0) -> NSFetchRequest<NSManagedObject>
{
let request = fetchRequest(withContext: context)
request.fetchBatchSize = batch
if offsetSize > 0
{
request.fetchOffset = offsetSize
}
return request;
}
/// Fetch a single object from the database using a predciate. Throws if more than one object is found with that predicate.
///
/// - Parameters:
/// - predicate: the predicate to use in the fetch
/// - managedContext: the context in which to execute the fetch request
/// - pendingChanges: whether to include pending changes
/// - Returns: a new NSManagedObject - nil if no object was found
/// - Throws: throws is the fetch request fails or if more than one object is found
class func fetchSingleObject(withPredicate predicate : NSPredicate, context managedContext : NSManagedObjectContext, includesPendingChanges pendingChanges : Bool) throws -> NSManagedObject?
{
let request = fetchRequest(withContext: managedContext)
request.includesPendingChanges = pendingChanges
request.predicate = predicate
request.sortDescriptors = []
var results : [NSManagedObject]
do
{
results = try managedContext.fetch(request)
}
catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
if results.count > 0
{
guard results.count == 1 else {
let error = NSError(domain: "CoreDataStackDomain", code: 9000, userInfo: ["Reason" : "Fetch single object with predicate found more than one. This is considered fatal as we now do not know which one should be returned..."])
throw error
}
return results.first
}
return nil
}
/// Fetch all the objects that match the predicate and sort them using the sort descriptor.
///
/// - Parameters:
/// - predicate: the predicate to use in the fetch
/// - sortDescriptors: the sort desciptor by which to sort the fetched objects
/// - managedContext: the context in which to execute the fetch request
/// - Returns: an array of NSManagedObjects
/// - Throws: Throws errors relating to executing the fetch request
class func fetchObjects(withPredicate predicate : NSPredicate?, descriptors sortDescriptors : [NSSortDescriptor], context managedContext : NSManagedObjectContext) throws -> [NSManagedObject]
{
let request = fetchRequest(withContext: managedContext)
request.sortDescriptors = sortDescriptors
if predicate != nil
{
request.predicate = predicate;
}
var results = [NSManagedObject]()
do
{
results = try managedContext.fetch(request)
} catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
return results
}
/// Fetch all the objects that match the predicate and sort them using the descriptor. This API has an extra parameter to limit the number of objects returned as well as to set the offset.
///
/// - Parameters:
/// - offset: the offset to use in the request
/// - requestPredicate: the predicate for the request
/// - fetchLimit: the maximum nunmber of objects to return
/// - sortDescriptiors: the sort decriptor to use when sorting the objects
/// - managedContext: the context in which to execute the fetch request
/// - Returns: an array of NSManagedObjects
/// - Throws: Throws errors relating to executing the fetch request
class func fetchObjects(withOffset offset : Int, predicate requestPredicate : NSPredicate?, limit fetchLimit : Int, descriptors sortDescriptiors : [NSSortDescriptor], context managedContext : NSManagedObjectContext) throws -> [NSManagedObject]
{
let request = fetchRequest(withContext: managedContext)
request.fetchOffset = offset
request.fetchLimit = fetchLimit
request.sortDescriptors = sortDescriptiors
if requestPredicate != nil
{
request.predicate = requestPredicate
}
var results = [NSManagedObject]()
do
{
results = try managedContext.fetch(request)
}
catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
return results
}
}
| mit | 910fea961c39ed86f6f72cb3641628d5 | 36.778378 | 247 | 0.643583 | 5.524901 | false | false | false | false |
phatblat/realm-cocoa | RealmSwift/Object.swift | 1 | 24182 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
`Object` is a class used to define Realm model objects.
In Realm you define your model classes by subclassing `Object` and adding properties to be managed.
You then instantiate and use your custom subclasses instead of using the `Object` class directly.
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var adopted: Bool
@Persisted var siblings: List<Dog>
}
```
### Supported property types
- `String`
- `Int`, `Int8`, `Int16`, `Int32`, `Int64`
- `Float`
- `Double`
- `Bool`
- `Date`
- `Data`
- `Decimal128`
- `ObjectId`
- `UUID`
- `AnyRealmValue`
- Any RawRepresentable enum whose raw type is a legal property type. Enums
must explicitly be marked as conforming to `PersistableEnum`.
- `Object` subclasses, to model many-to-one relationships
- `EmbeddedObject` subclasses, to model owning one-to-one relationships
All of the types above may also be `Optional`, with the exception of
`AnyRealmValue`. `Object` and `EmbeddedObject` subclasses *must* be Optional.
In addition to individual values, three different collection types are supported:
- `List<Element>`: an ordered mutable collection similar to `Array`.
- `MutableSet<Element>`: an unordered uniquing collection similar to `Set`.
- `Map<String, Element>`: an unordered key-value collection similar to `Dictionary`.
The Element type of collections may be any of the supported non-collection
property types listed above. Collections themselves may not be Optional, but
the values inside them may be, except for lists and sets of `Object` or
`EmbeddedObject` subclasses.
Finally, `LinkingObjects` properties can be used to track which objects link
to this one.
All properties which should be stored by Realm must be explicitly marked with
`@Persisted`. Any properties not marked with `@Persisted` will be ignored
entirely by Realm, and may be of any type.
### Querying
You can retrieve all objects of a given type from a Realm by calling the `objects(_:)` instance method.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public typealias Object = RealmSwiftObject
extension Object: RealmCollectionValue {
// MARK: Initializers
/**
Creates an unmanaged instance of a Realm object.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm.
- parameter value: The value used to populate the object.
*/
public convenience init(value: Any) {
self.init()
RLMInitializeWithValue(self, value, .partialPrivateShared())
}
// MARK: Properties
/// The Realm which manages the object, or `nil` if the object is unmanaged.
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The object schema which lists the managed properties for the object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self)!)
}
/// Indicates if the object can no longer be accessed because it is now invalid.
///
/// An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if
/// `invalidate()` is called on that Realm. This property is key-value observable.
@objc dynamic open override var isInvalidated: Bool { return super.isInvalidated }
/// A human-readable description of the object.
open override var description: String { return super.description }
/**
WARNING: This is an internal helper method not intended for public use.
It is not considered part of the public API.
:nodoc:
*/
public override final class func _getProperties() -> [RLMProperty] {
return ObjectUtil.getSwiftProperties(self)
}
// MARK: Object Customization
/**
Override this method to specify the name of a property to be used as the primary key.
Only properties of types `String`, `Int`, `ObjectId` and `UUID` can be
designated as the primary key. Primary key properties enforce uniqueness
for each value whenever the property is set, which incurs minor overhead.
Indexes are created automatically for primary key properties.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, use
`@Persisted(primaryKey: true)` instead.
- returns: The name of the property designated as the primary key, or
`nil` if the model has no primary key.
*/
@objc open class func primaryKey() -> String? { return nil }
/**
Override this method to specify the names of properties to ignore. These
properties will not be managed by the Realm that manages the object.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, any properties not
marked with `@Persisted` are automatically ignored.
- returns: An array of property names to ignore.
*/
@objc open class func ignoredProperties() -> [String] { return [] }
/**
Returns an array of property names for properties which should be indexed.
Only string, integer, boolean, `Date`, and `NSDate` properties are supported.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, use
`@Persisted(indexed: true)` instead.
- returns: An array of property names.
*/
@objc open class func indexedProperties() -> [String] { return [] }
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
@objc open subscript(key: String) -> Any? {
get {
RLMDynamicGetByName(self, key)
}
set {
dynamicSet(object: self, key: key, value: newValue)
}
}
// MARK: Notifications
/**
Registers a block to be called each time the object changes.
The block will be asynchronously called after each write transaction which
deletes the object or modifies any of the managed properties of the object,
including self-assignments that set a property to its existing value.
For write transactions performed on different threads or in different
processes, the block will be called when the managing Realm is
(auto)refreshed to a version including the changes, while for local write
transactions it will be called at some point in the future after the write
transaction is committed.
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var adopted: Bool
@Persisted var siblings: List<Dog>
}
// ... where `dog` is a managed Dog object.
dog.observe(keyPaths: ["adopted"], { changes in
// ...
})
```
- The above notification block fires for changes to the
`adopted` property, but not for any changes made to `name`.
- If the observed key path were `["siblings"]`, then any insertion,
deletion, or modification to the `siblings` list will trigger the block. A change to
`someSibling.name` would not trigger the block (where `someSibling`
is an element contained in `siblings`)
- If the observed key path were `["siblings.name"]`, then any insertion or
deletion to the `siblings` list would trigger the block. For objects
contained in the `siblings` list, only modifications to their `name` property
will trigger the block.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
If no queue is given, notifications are delivered via the standard run
loop, and so can't be delivered while the run loop is blocked by other
activity. If a queue is given, notifications are delivered to that queue
instead. When notifications can't be delivered instantly, multiple
notifications may be coalesced into a single notification.
Unlike with `List` and `Results`, there is no "initial" callback made after
you add a new notification block.
Only objects which are managed by a Realm can be observed in this way. You
must retain the returned token for as long as you want updates to be sent
to the block. To stop receiving updates, call `invalidate()` on the token.
It is safe to capture a strong reference to the observed object within the
callback block. There is no retain cycle due to that the callback is
retained by the returned token and not by the object itself.
- warning: This method cannot be called during a write transaction, or when
the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to call with information about changes to the object.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe<T: RLMObjectBase>(keyPaths: [String]? = nil,
on queue: DispatchQueue? = nil,
_ block: @escaping (ObjectChange<T>) -> Void) -> NotificationToken {
return _observe(keyPaths: keyPaths, on: queue, block)
}
// MARK: Dynamic list
/**
Returns a list of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A list of `DynamicObject`s.
:nodoc:
*/
public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! List<DynamicObject>
}
let list = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return List<DynamicObject>(objc: list._rlmCollection as! RLMArray<AnyObject>)
}
// MARK: Dynamic set
/**
Returns a set of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A set of `DynamicObject`s.
:nodoc:
*/
public func dynamicMutableSet(_ propertyName: String) -> MutableSet<DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! MutableSet<DynamicObject>
}
let set = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return MutableSet<DynamicObject>(objc: set._rlmCollection as! RLMSet<AnyObject>)
}
// MARK: Dynamic map
/**
Returns a map of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A map with a given key type with `DynamicObject` as the value.
:nodoc:
*/
public func dynamicMap<Key: _MapKey>(_ propertyName: String) -> Map<Key, DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! Map<Key, DynamicObject>
}
let base = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return Map<Key, DynamicObject>(objc: base._rlmCollection as! RLMDictionary<AnyObject, AnyObject>)
}
// MARK: Comparison
/**
Returns whether two Realm objects are the same.
Objects are considered the same if and only if they are both managed by the same
Realm and point to the same underlying object in the database.
- note: Equality comparison is implemented by `isEqual(_:)`. If the object type
is defined with a primary key, `isEqual(_:)` behaves identically to this
method. If the object type is not defined with a primary key,
`isEqual(_:)` uses the `NSObject` behavior of comparing object identity.
This method can be used to compare two objects for database equality
whether or not their object type defines a primary key.
- parameter object: The object to compare the receiver to.
*/
public func isSameObject(as object: Object?) -> Bool {
return RLMObjectBaseAreEqual(self, object)
}
}
extension Object: ThreadConfined {
/**
Indicates if this object is frozen.
- see: `Object.freeze()`
*/
public var isFrozen: Bool { return realm?.isFrozen ?? false }
/**
Returns a frozen (immutable) snapshot of this object.
The frozen copy is an immutable object which contains the same data as this
object currently contains, but will not update when writes are made to the
containing Realm. Unlike live objects, frozen objects can be accessed from any
thread.
- warning: Holding onto a frozen object for an extended period while performing write
transaction on the Realm may result in the Realm file growing to large sizes. See
`Realm.Configuration.maximumNumberOfActiveVersions` for more information.
- warning: This method can only be called on a managed object.
*/
public func freeze() -> Self {
guard let realm = realm else { throwRealmException("Unmanaged objects cannot be frozen.") }
return realm.freeze(self)
}
/**
Returns a live (mutable) reference of this object.
This method creates a managed accessor to a live copy of the same frozen object.
Will return self if called on an already live object.
*/
public func thaw() -> Self? {
guard let realm = realm else { throwRealmException("Unmanaged objects cannot be thawed.") }
return realm.thaw(self)
}
}
/**
Information about a specific property which changed in an `Object` change notification.
*/
@frozen public struct PropertyChange {
/**
The name of the property which changed.
*/
public let name: String
/**
Value of the property before the change occurred. This is not supplied if
the change happened on the same thread as the notification and for `List`
properties.
For object properties this will give the object which was previously
linked to, but that object will have its new values and not the values it
had before the changes. This means that `previousValue` may be a deleted
object, and you will need to check `isInvalidated` before accessing any
of its properties.
*/
public let oldValue: Any?
/**
The value of the property after the change occurred. This is not supplied
for `List` properties and will always be nil.
*/
public let newValue: Any?
}
/**
Information about the changes made to an object which is passed to `Object`'s
notification blocks.
*/
@frozen public enum ObjectChange<T: ObjectBase> {
/**
If an error occurs, notification blocks are called one time with a `.error`
result and an `NSError` containing details about the error. Currently the
only errors which can occur are when opening the Realm on a background
worker thread to calculate the change set. The callback will never be
called again after `.error` is delivered.
*/
case error(_ error: NSError)
/**
One or more of the properties of the object have been changed.
*/
case change(_: T, _: [PropertyChange])
/// The object has been deleted from the Realm.
case deleted
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
@objc(RealmSwiftDynamicObject)
@dynamicMemberLookup
public final class DynamicObject: Object {
public override subscript(key: String) -> Any? {
get {
let value = RLMDynamicGetByName(self, key).flatMap(coerceToNil)
if let array = value as? RLMArray<AnyObject> {
return List<DynamicObject>(objc: array)
}
if let set = value as? RLMSet<AnyObject> {
return MutableSet<DynamicObject>(objc: set)
}
if let dictionary = value as? RLMDictionary<AnyObject, AnyObject> {
return Map<String, DynamicObject>(objc: dictionary)
}
return value
}
set(value) {
RLMDynamicValidatedSet(self, key, value)
}
}
public subscript(dynamicMember member: String) -> Any? {
get {
self[member]
}
set(value) {
self[member] = value
}
}
/// :nodoc:
public override func value(forUndefinedKey key: String) -> Any? {
return self[key]
}
/// :nodoc:
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
override public class func sharedSchema() -> RLMObjectSchema? {
nil
}
}
/**
An enum type which can be stored on a Realm Object.
Only `@objc` enums backed by an Int can be stored on a Realm object, and the
enum type must explicitly conform to this protocol. For example:
```
@objc enum MyEnum: Int, RealmEnum {
case first = 1
case second = 2
case third = 7
}
class MyModel: Object {
@objc dynamic enumProperty = MyEnum.first
let optionalEnumProperty = RealmOptional<MyEnum>()
}
```
*/
public protocol RealmEnum: RealmOptionalType, _RealmSchemaDiscoverable {
/// :nodoc:
static func _rlmToRawValue(_ value: Any) -> Any
/// :nodoc:
static func _rlmFromRawValue(_ value: Any) -> Any?
}
// MARK: - Implementation
/// :nodoc:
public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _RealmSchemaDiscoverable {
static func _rlmToRawValue(_ value: Any) -> Any {
return (value as! Self).rawValue
}
static func _rlmFromRawValue(_ value: Any) -> Any? {
return Self(rawValue: value as! RawValue)
}
static func _rlmPopulateProperty(_ prop: RLMProperty) {
RawValue._rlmPopulateProperty(prop)
}
static var _rlmType: PropertyType { RawValue._rlmType }
}
internal func dynamicSet(object: ObjectBase, key: String, value: Any?) {
let bridgedValue: Any?
if let v1 = value, let v2 = v1 as? CustomObjectiveCBridgeable {
bridgedValue = v2.objCValue
} else if let v1 = value, let v2 = v1 as? RealmEnum {
bridgedValue = type(of: v2)._rlmToRawValue(v2)
} else {
bridgedValue = value
}
if RLMObjectBaseRealm(object) == nil {
object.setValue(bridgedValue, forKey: key)
} else {
RLMDynamicValidatedSet(object, key, bridgedValue)
}
}
// MARK: AssistedObjectiveCBridgeable
// FIXME: Remove when `as! Self` can be written
private func forceCastToInferred<T, V>(_ x: T) -> V {
return x as! V
}
extension Object: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self {
return forceCastToInferred(objectiveCValue)
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil)
}
}
// MARK: Key Path Strings
extension ObjectBase {
internal func prepareForRecording() {
let objectSchema = ObjectSchema(RLMObjectBaseObjectSchema(self)!)
(objectSchema.rlmObjectSchema.properties + objectSchema.rlmObjectSchema.computedProperties)
.map { (prop: $0, accessor: $0.swiftAccessor) }
.forEach { $0.accessor?.observe($0.prop, on: self) }
}
}
/**
Gets the components of a given key path as a string.
- warning: Objects that declare properties with the old `@objc dynamic` syntax are not fully supported
by this function, and it is recommened that you use `@Persisted` to declare your properties if you wish to use
this function to its full benefit.
Example:
```
let name = ObjectBase._name(for: \Person.dogs[0].name) // "dogs.name"
// Note that the above KeyPath expression is only supported with properties declared
// with `@Persisted`.
let nested = ObjectBase._name(for: \Person.address.city.zip) // "address.city.zip"
```
*/
public func _name<T: ObjectBase>(for keyPath: PartialKeyPath<T>) -> String {
if let name = keyPath._kvcKeyPathString {
return name
}
let traceObject = T()
traceObject.lastAccessedNames = NSMutableArray()
traceObject.prepareForRecording()
let value = traceObject[keyPath: keyPath]
if let collection = value as? PropertyNameConvertible,
let propertyInfo = collection.propertyInformation,
propertyInfo.isLegacy {
traceObject.lastAccessedNames?.add(propertyInfo.key)
}
if let storage = value as? RLMSwiftValueStorage {
traceObject.lastAccessedNames?.add(RLMSwiftValueStorageGetPropertyName(storage))
}
return traceObject.lastAccessedNames!.componentsJoined(by: ".")
}
| apache-2.0 | d1709cfe90a13d306f2465161dd4d409 | 37.506369 | 119 | 0.677405 | 4.758363 | false | false | false | false |
hejunbinlan/Operations | Operations/Conditions/Permissions/CalendarCondition.swift | 1 | 3120 | //
// CalendarCondition.swift
// Operations
//
// Created by Daniel Thorpe on 09/08/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import EventKit
public protocol EventKitAuthorizationManagerType {
func authorizationStatusForEntityType(entityType: EKEntityType) -> EKAuthorizationStatus
func requestAccessToEntityType(entityType: EKEntityType, completion: EKEventStoreRequestAccessCompletionHandler)
}
private struct EventKitAuthorizationManager: EventKitAuthorizationManagerType {
var store = EKEventStore()
func authorizationStatusForEntityType(entityType: EKEntityType) -> EKAuthorizationStatus {
return EKEventStore.authorizationStatusForEntityType(entityType)
}
func requestAccessToEntityType(entityType: EKEntityType, completion: EKEventStoreRequestAccessCompletionHandler) {
store.requestAccessToEntityType(entityType, completion: completion)
}
}
public struct CalendarCondition: OperationCondition {
public enum Error: ErrorType {
case AuthorizationFailed(status: EKAuthorizationStatus)
}
public let name = "Calendar"
public let isMutuallyExclusive = false
let entityType: EKEntityType
let manager: EventKitAuthorizationManagerType
public init(type: EKEntityType) {
self.init(type: type, authorizationManager: EventKitAuthorizationManager())
}
/**
Testing Interface
Instead use
init(type: EKEntityType)
*/
init(type: EKEntityType, authorizationManager: EventKitAuthorizationManagerType) {
entityType = type
manager = authorizationManager
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return CalendarPermissionOperation(type: entityType, authorizationManager: manager)
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
let status = manager.authorizationStatusForEntityType(entityType)
switch status {
case .Authorized:
completion(.Satisfied)
default:
completion(.Failed(Error.AuthorizationFailed(status: status)))
}
}
}
public func ==(a: CalendarCondition.Error, b: CalendarCondition.Error) -> Bool {
switch (a, b) {
case let (.AuthorizationFailed(aStatus), .AuthorizationFailed(bStatus)):
return aStatus == bStatus
}
}
class CalendarPermissionOperation: Operation {
let entityType: EKEntityType
let manager: EventKitAuthorizationManagerType
init(type: EKEntityType, authorizationManager: EventKitAuthorizationManagerType = EventKitAuthorizationManager()) {
entityType = type
manager = authorizationManager
}
override func execute() {
switch manager.authorizationStatusForEntityType(entityType) {
case .NotDetermined:
dispatch_async(Queue.Main.queue, request)
default:
finish()
}
}
func request() {
manager.requestAccessToEntityType(entityType) { (granted, error) in
self.finish()
}
}
}
| mit | ffd755de9144ce7d971e6c8c505b0e1d | 29 | 119 | 0.714103 | 5.875706 | false | false | false | false |
BellAppLab/Defines | Sources/Defines/Defines+OS.swift | 1 | 2554 | /*
Copyright (c) 2018 Bell App Lab <[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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#endif
#if os(watchOS)
import WatchKit
#endif
#if os(macOS)
import AppKit
#endif
//MARK: - Main
public extension Defines.OS
{
/// The version of the OS currently running your app (aka `UIDevice.current.systemVersion`)
public static let version: Defines.Version = {
#if os(iOS) || os(tvOS)
return Defines.Version(versionString: UIDevice.current.systemVersion)
#endif
#if os(watchOS)
return Defines.Version(versionString: WKInterfaceDevice.current().systemVersion)
#endif
#if os(macOS)
return Defines.Version(operatingSystemVersion: ProcessInfo.processInfo.operatingSystemVersion)
#endif
}()
/// Returns true when running on iOS.
public static let isiOS: Bool = {
#if os(iOS)
return true
#else
return false
#endif
}()
/// Returns true when running on watchOS.
public static let isWatchOS: Bool = {
#if os(watchOS)
return true
#else
return false
#endif
}()
/// Returns true when running on tvOS.
public static let istvOS: Bool = {
#if os(tvOS)
return true
#else
return false
#endif
}()
/// Returns true when running on macOS.
public static let isMacOS: Bool = {
#if os(macOS)
return true
#else
return false
#endif
}()
}
| mit | 0cbe0a40925bfc960e01d15b8ed0c345 | 29.047059 | 102 | 0.676977 | 4.560714 | false | false | false | false |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/UILibrary/DataManagers/SFTableManager.swift | 1 | 13608 | //
// SFTableManager.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 30/04/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
import DeepDiff
public protocol SFTableAdapterDelegate: class {
func didSelectCell<DataType: SFDataType>(with item: DataType, at indexPath: IndexPath, tableView: SFTableView)
func heightForRow(at indexPath: IndexPath, tableView: SFTableView) -> CGFloat?
func prepareCell<DataType: SFDataType>(_ cell: SFTableViewCell, at indexPath: IndexPath, with item: DataType)
var useCustomHeader: Bool { get }
func prepareHeader<DataType: SFDataType>(_ view: SFTableViewHeaderView, with section: SFDataSection<DataType>, at index: Int)
var useCustomFooter: Bool { get }
func prepareFooter<DataType: SFDataType>(_ view: SFTableViewFooterView, with section: SFDataSection<DataType>, at index: Int)
func prefetch<DataType: SFDataType>(item: DataType, at indexPath: IndexPath)
func deleted<DataType: SFDataType>(item: DataType, at indexPath: IndexPath)
}
public extension SFTableAdapterDelegate {
func didSelectCell<DataType: SFDataType>(with item: DataType, at indexPath: IndexPath, tableView: SFTableView) {}
func heightForRow(at indexPath: IndexPath, tableView: SFTableView) -> CGFloat? { return nil }
var useCustomHeader: Bool { return false }
func prepareHeader<DataType: SFDataType>(_ view: SFTableViewHeaderView, with section: SFDataSection<DataType>, at index: Int) {}
var useCustomFooter: Bool { return false }
func prepareFooter<DataType: SFDataType>(_ view: SFTableViewFooterView, with section: SFDataSection<DataType>, at index: Int) {}
func prefetch<DataType: SFDataType>(item: DataType, at indexPath: IndexPath) {}
func deleted<DataType: SFDataType>(item: DataType, at indexPath: IndexPath) {}
}
public final class SFTableAdapter
<DataType: SFDataType, CellType: SFTableViewCell, HeaderType: SFTableViewHeaderView, FooterType: SFTableViewFooterView>
: NSObject, UITableViewDataSource, UITableViewDelegate, UITableViewDataSourcePrefetching {
// MARK: - Instance Properties
public weak var delegate: SFTableAdapterDelegate? {
didSet {
registerHeightForViews()
}
}
public weak var tableView: SFTableView?
public weak var dataManager: SFDataManager<DataType>?
public var insertAnimation: UITableView.RowAnimation = .automatic
public var deleteAnimation: UITableView.RowAnimation = .automatic
public var updateAnimation: UITableView.RowAnimation = .automatic
public var addIndexList: Bool = false
public var enableEditing: Bool = false
public func configure(tableView: SFTableView, dataManager: SFDataManager<DataType>) {
self.dataManager = dataManager
self.tableView = tableView
dataManager.delegate = self
tableView.dataSource = self
tableView.delegate = self
tableView.prefetchDataSource = self
registerViews()
registerHeightForViews()
}
private func registerViews() {
tableView?.register(CellType.self, forCellReuseIdentifier: CellType.identifier)
tableView?.register(HeaderType.self, forHeaderFooterViewReuseIdentifier: HeaderType.identifier)
tableView?.register(FooterType.self, forHeaderFooterViewReuseIdentifier: FooterType.identifier)
}
private func registerHeightForViews() {
tableView?.rowHeight = CellType.height
if let delegate = delegate {
tableView?.sectionHeaderHeight = delegate.useCustomHeader ? HeaderType.height : 0.0
tableView?.sectionFooterHeight = delegate.useCustomFooter ? FooterType.height : 0.0
}
if tableView?.style == .grouped {
// Create a frame close to zero, but no 0 because there is a bug in UITableView(or feature?)
let frame = CGRect(x: 0, y: 0, width: CGFloat.leastNonzeroMagnitude, height: CGFloat.leastNonzeroMagnitude)
tableView?.tableHeaderView = UIView(frame: frame)
tableView?.tableFooterView = UIView(frame: frame)
tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -20, right: 0)
}
}
private var temporarySearchData: [DataType]?
public func search(_ isIncluded: (DataType) -> Bool) {
temporarySearchData = dataManager?.flatData.filter(isIncluded)
tableView?.reloadData()
}
public func clearSearch() {
temporarySearchData = nil
tableView?.reloadData()
}
// MARK: - UITableViewDataSource
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if temporarySearchData != nil { return nil }
if addIndexList {
return dataManager?.compactMap({ $0.identifier })
} else {
return nil
}
}
public func numberOfSections(in tableView: UITableView) -> Int {
guard let dataManager = dataManager else { return 0 }
return temporarySearchData == nil ? dataManager.count : 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let dataManager = dataManager else { return 0 }
return temporarySearchData?.count ?? dataManager[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CellType.identifier, for: indexPath) as? CellType else {
return UITableViewCell()
}
guard let dataManager = dataManager else { return UITableViewCell() }
if let temporarySearchData = temporarySearchData {
delegate?.prepareCell(cell, at: indexPath, with: temporarySearchData[indexPath.row])
} else {
delegate?.prepareCell(cell, at: indexPath, with: dataManager.getItem(at: indexPath))
}
return cell
}
// MARK: - UITableViewDelegate
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return temporarySearchData != nil ? false : enableEditing
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let item = dataManager?.getItem(at: indexPath) else { return }
dataManager?.deleteItem(at: indexPath)
delegate?.deleted(item: item, at: indexPath)
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let tableView = tableView as? SFTableView,
let dataManager = dataManager
else { return }
if let temporarySearchData = temporarySearchData {
let item = temporarySearchData[indexPath.row]
delegate?.didSelectCell(with: item, at: indexPath, tableView: tableView)
} else {
let item = dataManager[indexPath.section].content[indexPath.row]
delegate?.didSelectCell(with: item, at: indexPath, tableView: tableView)
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let tableView = self.tableView else { return 0 }
return delegate?.heightForRow(at: indexPath, tableView: tableView) ?? tableView.rowHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if temporarySearchData != nil { return 0.0 }
if let delegate = delegate {
return delegate.useCustomHeader ? HeaderType.height : 0.0
} else {
return 0.0
}
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let delegate = delegate else { return nil }
if temporarySearchData != nil { return nil }
if delegate.useCustomHeader {
guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderType.identifier) as? HeaderType else {
return nil
}
guard let dataManager = dataManager else { return nil }
delegate.prepareHeader(view, with: dataManager[section], at: section)
view.updateColors()
return view
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if temporarySearchData != nil { return 0.0 }
if let delegate = delegate {
return delegate.useCustomFooter ? FooterType.height : 0.0
} else {
return 0.0
}
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let delegate = delegate else { return nil }
if temporarySearchData != nil { return nil }
if delegate.useCustomFooter {
guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: FooterType.identifier) as? FooterType else {
return nil
}
guard let dataManager = dataManager else { return nil }
delegate.prepareFooter(view, with: dataManager[section], at: section)
view.updateColors()
return view
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let view = view as? HeaderType
view?.updateColors()
}
public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let view = view as? FooterType
view?.updateColors()
}
// MARK: - UITableViewDataSourcePrefetching
public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
guard let dataManager = dataManager else { return }
indexPaths.forEach { (indexPath) in
delegate?.prefetch(item: dataManager.getItem(at: indexPath), at: indexPath)
}
}
}
extension SFTableAdapter: SFDataManagerDelegate {
public func updateSection<DataType>(with changes: [Change<DataType>], index: Int) where DataType: SFDataType {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.reload(changes: changes, section: index, insertionAnimation: insertAnimation, deletionAnimation: deleteAnimation, replacementAnimation: updateAnimation, updateData: {
}, completion: nil)
}
}
public func forceUpdate() {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.reloadData()
}
}
// MARK: - Sections
public func insertSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.insertSections(IndexSet(integer: index), with: insertAnimation)
}, completion: nil)
}
}
public func moveSection(from: Int, to: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.moveSection(from, toSection: to)
}, completion: nil)
}
}
public func deleteSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.deleteSections(IndexSet(integer: index), with: deleteAnimation)
}, completion: nil)
}
}
public func updateSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.reloadSections(IndexSet(integer: index), with: updateAnimation)
}, completion: nil)
}
}
// MARK: - Items
public func insertItem(at indexPath: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.insertRows(at: [indexPath], with: insertAnimation)
}, completion: nil)
}
}
public func moveItem(from: IndexPath, to: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.moveRow(at: from, to: to)
}, completion: nil)
}
}
public func deleteItem(at indexPath: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.deleteRows(at: [indexPath], with: deleteAnimation)
}, completion: nil)
}
}
public func updateItem(at index: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.reloadRows(at: [index], with: updateAnimation)
}, completion: nil)
}
}
}
| mit | 2144d456d31d4a5f9ff45a8027796e50 | 36.902507 | 189 | 0.636511 | 5.549347 | false | false | false | false |
sumnerevans/wireless-debugging | mobile/ios/WirelessDebug/WirelessDebugger/WebSocket.swift | 2 | 68930 | /*
* SwiftWebSocket (websocket.swift)
*
* Copyright (C) Josh Baker. All Rights Reserved.
* Contact: @tidwall, [email protected]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import Foundation
private let windowBufferSize = 0x2000
private class Payload {
var ptr : UnsafeMutableRawPointer
var cap : Int
var len : Int
init(){
len = 0
cap = windowBufferSize
ptr = malloc(cap)
}
deinit{
free(ptr)
}
var count : Int {
get {
return len
}
set {
if newValue > cap {
while cap < newValue {
cap *= 2
}
ptr = realloc(ptr, cap)
}
len = newValue
}
}
func append(_ bytes: UnsafePointer<UInt8>, length: Int){
let prevLen = len
count = len+length
memcpy(ptr+prevLen, bytes, length)
}
var array : [UInt8] {
get {
var array = [UInt8](repeating: 0, count: count)
memcpy(&array, ptr, count)
return array
}
set {
count = 0
append(newValue, length: newValue.count)
}
}
var nsdata : Data {
get {
return Data(bytes: ptr.assumingMemoryBound(to: UInt8.self), count: count)
}
set {
count = 0
append((newValue as NSData).bytes.bindMemory(to: UInt8.self, capacity: newValue.count), length: newValue.count)
}
}
var buffer : UnsafeBufferPointer<UInt8> {
get {
return UnsafeBufferPointer<UInt8>(start: ptr.assumingMemoryBound(to: UInt8.self), count: count)
}
set {
count = 0
append(newValue.baseAddress!, length: newValue.count)
}
}
}
private enum OpCode : UInt8, CustomStringConvertible {
case `continue` = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xA
var isControl : Bool {
switch self {
case .close, .ping, .pong:
return true
default:
return false
}
}
var description : String {
switch self {
case .`continue`: return "Continue"
case .text: return "Text"
case .binary: return "Binary"
case .close: return "Close"
case .ping: return "Ping"
case .pong: return "Pong"
}
}
}
/// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection.
public struct WebSocketEvents {
/// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
public var open : ()->() = {}
/// An event to be called when the WebSocket connection's readyState changes to .Closed.
public var close : (_ code : Int, _ reason : String, _ wasClean : Bool)->() = {(code, reason, wasClean) in}
/// An event to be called when an error occurs.
public var error : (_ error : Error)->() = {(error) in}
/// An event to be called when a message is received from the server.
public var message : (_ data : Any)->() = {(data) in}
/// An event to be called when a pong is received from the server.
public var pong : (_ data : Any)->() = {(data) in}
/// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
public var end : (_ code : Int, _ reason : String, _ wasClean : Bool, _ error : Error?)->() = {(code, reason, wasClean, error) in}
}
/// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection.
public enum WebSocketBinaryType : CustomStringConvertible {
/// The WebSocket should transmit [UInt8] objects.
case uInt8Array
/// The WebSocket should transmit NSData objects.
case nsData
/// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk.
case uInt8UnsafeBufferPointer
public var description : String {
switch self {
case .uInt8Array: return "UInt8Array"
case .nsData: return "NSData"
case .uInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer"
}
}
}
/// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection.
@objc public enum WebSocketReadyState : Int, CustomStringConvertible {
/// The connection is not yet open.
case connecting = 0
/// The connection is open and ready to communicate.
case open = 1
/// The connection is in the process of closing.
case closing = 2
/// The connection is closed or couldn't be opened.
case closed = 3
fileprivate var isClosed : Bool {
switch self {
case .closing, .closed:
return true
default:
return false
}
}
/// Returns a string that represents the ReadyState value.
public var description : String {
switch self {
case .connecting: return "Connecting"
case .open: return "Open"
case .closing: return "Closing"
case .closed: return "Closed"
}
}
}
private let defaultMaxWindowBits = 15
/// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection.
public struct WebSocketCompression {
/// Used to accept compressed messages from the server. Default is true.
public var on = false
/// request no context takeover.
public var noContextTakeover = false
/// request max window bits.
public var maxWindowBits = defaultMaxWindowBits
}
/// The WebSocketService options are used by the services property and manages the underlying socket services.
public struct WebSocketService : OptionSet {
public typealias RawValue = UInt
var value: UInt = 0
init(_ value: UInt) { self.value = value }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: WebSocketService { return self.init(0) }
static func fromMask(_ raw: UInt) -> WebSocketService { return self.init(raw) }
public var rawValue: UInt { return self.value }
/// No services.
public static var None: WebSocketService { return self.init(0) }
/// Allow socket to handle VoIP.
public static var VoIP: WebSocketService { return self.init(1 << 0) }
/// Allow socket to handle video.
public static var Video: WebSocketService { return self.init(1 << 1) }
/// Allow socket to run in background.
public static var Background: WebSocketService { return self.init(1 << 2) }
/// Allow socket to handle voice.
public static var Voice: WebSocketService { return self.init(1 << 3) }
}
private let atEndDetails = "streamStatus.atEnd"
private let timeoutDetails = "The operation couldn’t be completed. Operation timed out"
private let timeoutDuration : CFTimeInterval = 30
public enum WebSocketError : Error, CustomStringConvertible {
case memory
case needMoreInput
case invalidHeader
case invalidAddress
case network(String)
case libraryError(String)
case payloadError(String)
case protocolError(String)
case invalidResponse(String)
case invalidCompressionOptions(String)
public var description : String {
switch self {
case .memory: return "Memory"
case .needMoreInput: return "NeedMoreInput"
case .invalidAddress: return "InvalidAddress"
case .invalidHeader: return "InvalidHeader"
case let .invalidResponse(details): return "InvalidResponse(\(details))"
case let .invalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))"
case let .libraryError(details): return "LibraryError(\(details))"
case let .protocolError(details): return "ProtocolError(\(details))"
case let .payloadError(details): return "PayloadError(\(details))"
case let .network(details): return "Network(\(details))"
}
}
public var details : String {
switch self {
case .invalidResponse(let details): return details
case .invalidCompressionOptions(let details): return details
case .libraryError(let details): return details
case .protocolError(let details): return details
case .payloadError(let details): return details
case .network(let details): return details
default: return ""
}
}
}
private class UTF8 {
var text : String = ""
var count : UInt32 = 0 // number of bytes
var procd : UInt32 = 0 // number of bytes processed
var codepoint : UInt32 = 0 // the actual codepoint
var bcount = 0
init() { text = "" }
func append(_ byte : UInt8) throws {
if count == 0 {
if byte <= 0x7F {
text.append(String(UnicodeScalar(byte)))
return
}
if byte == 0xC0 || byte == 0xC1 {
throw WebSocketError.payloadError("invalid codepoint: invalid byte")
}
if byte >> 5 & 0x7 == 0x6 {
count = 2
} else if byte >> 4 & 0xF == 0xE {
count = 3
} else if byte >> 3 & 0x1F == 0x1E {
count = 4
} else {
throw WebSocketError.payloadError("invalid codepoint: frames")
}
procd = 1
codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6)
return
}
if byte >> 6 & 0x3 != 0x2 {
throw WebSocketError.payloadError("invalid codepoint: signature")
}
codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6)
if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) {
throw WebSocketError.payloadError("invalid codepoint: out of bounds")
}
procd += 1
if procd == count {
if codepoint <= 0x7FF && count > 2 {
throw WebSocketError.payloadError("invalid codepoint: overlong")
}
if codepoint <= 0xFFFF && count > 3 {
throw WebSocketError.payloadError("invalid codepoint: overlong")
}
procd = 0
count = 0
text.append(String.init(describing: UnicodeScalar(codepoint)!))
}
return
}
func append(_ bytes : UnsafePointer<UInt8>, length : Int) throws {
if length == 0 {
return
}
if count == 0 {
var ascii = true
for i in 0 ..< length {
if bytes[i] > 0x7F {
ascii = false
break
}
}
if ascii {
text += NSString(bytes: bytes, length: length, encoding: String.Encoding.ascii.rawValue)! as String
bcount += length
return
}
}
for i in 0 ..< length {
try append(bytes[i])
}
bcount += length
}
var completed : Bool {
return count == 0
}
static func bytes(_ string : String) -> [UInt8]{
let data = string.data(using: String.Encoding.utf8)!
return [UInt8](UnsafeBufferPointer<UInt8>(start: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), count: data.count))
}
static func string(_ bytes : [UInt8]) -> String{
if let str = NSString(bytes: bytes, length: bytes.count, encoding: String.Encoding.utf8.rawValue) {
return str as String
}
return ""
}
}
private class Frame {
var inflate = false
var code = OpCode.continue
var utf8 = UTF8()
var payload = Payload()
var statusCode = UInt16(0)
var finished = true
static func makeClose(_ statusCode: UInt16, reason: String) -> Frame {
let f = Frame()
f.code = .close
f.statusCode = statusCode
f.utf8.text = reason
return f
}
func copy() -> Frame {
let f = Frame()
f.code = code
f.utf8.text = utf8.text
f.payload.buffer = payload.buffer
f.statusCode = statusCode
f.finished = finished
f.inflate = inflate
return f
}
}
private class Delegate : NSObject, StreamDelegate {
@objc func stream(_ aStream: Stream, handle eventCode: Stream.Event){
manager.signal()
}
}
@_silgen_name("zlibVersion") private func zlibVersion() -> OpaquePointer
@_silgen_name("deflateInit2_") private func deflateInit2(_ strm : UnsafeMutableRawPointer, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateInit_") private func deflateInit(_ strm : UnsafeMutableRawPointer, level : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateEnd") private func deflateEnd(_ strm : UnsafeMutableRawPointer) -> CInt
@_silgen_name("deflate") private func deflate(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt
@_silgen_name("inflateInit2_") private func inflateInit2(_ strm : UnsafeMutableRawPointer, windowBits : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflateInit_") private func inflateInit(_ strm : UnsafeMutableRawPointer, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflate") private func inflateG(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt
@_silgen_name("inflateEnd") private func inflateEndG(_ strm : UnsafeMutableRawPointer) -> CInt
private func zerror(_ res : CInt) -> Error? {
var err = ""
switch res {
case 0: return nil
case 1: err = "stream end"
case 2: err = "need dict"
case -1: err = "errno"
case -2: err = "stream error"
case -3: err = "data error"
case -4: err = "mem error"
case -5: err = "buf error"
case -6: err = "version error"
default: err = "undefined error"
}
return WebSocketError.payloadError("zlib: \(err): \(res)")
}
private struct z_stream {
var next_in : UnsafePointer<UInt8>? = nil
var avail_in : CUnsignedInt = 0
var total_in : CUnsignedLong = 0
var next_out : UnsafeMutablePointer<UInt8>? = nil
var avail_out : CUnsignedInt = 0
var total_out : CUnsignedLong = 0
var msg : UnsafePointer<CChar>? = nil
var state : OpaquePointer? = nil
var zalloc : OpaquePointer? = nil
var zfree : OpaquePointer? = nil
var opaque : OpaquePointer? = nil
var data_type : CInt = 0
var adler : CUnsignedLong = 0
var reserved : CUnsignedLong = 0
}
private class Inflater {
var windowBits = 0
var strm = z_stream()
var tInput = [[UInt8]]()
var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF]
var bufferSize = windowBufferSize
var buffer = malloc(windowBufferSize)
init?(windowBits : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size))
if ret != 0 {
return nil
}
}
deinit{
_ = inflateEndG(&strm)
free(buffer)
}
func inflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){
var buf = buffer
var bufsiz = bufferSize
var buflen = 0
for i in 0 ..< 2{
if i == 0 {
strm.avail_in = CUnsignedInt(length)
strm.next_in = UnsafePointer<UInt8>(bufin)
} else {
if !final {
break
}
strm.avail_in = CUnsignedInt(inflateEnd.count)
strm.next_in = UnsafePointer<UInt8>(inflateEnd)
}
while true {
strm.avail_out = CUnsignedInt(bufsiz)
strm.next_out = buf?.assumingMemoryBound(to: UInt8.self)
_ = inflateG(&strm, flush: 0)
let have = bufsiz - Int(strm.avail_out)
bufsiz -= have
buflen += have
if strm.avail_out != 0{
break
}
if bufsiz == 0 {
bufferSize *= 2
let nbuf = realloc(buffer, bufferSize)
if nbuf == nil {
throw WebSocketError.payloadError("memory")
}
buffer = nbuf
buf = buffer?.advanced(by: Int(buflen))
bufsiz = bufferSize - buflen
}
}
}
return (buffer!.assumingMemoryBound(to: UInt8.self), buflen)
}
}
private class Deflater {
var windowBits = 0
var memLevel = 0
var strm = z_stream()
var bufferSize = windowBufferSize
var buffer = malloc(windowBufferSize)
init?(windowBits : Int, memLevel : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
self.memLevel = memLevel
let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size))
if ret != 0 {
return nil
}
}
deinit{
_ = deflateEnd(&strm)
free(buffer)
}
/*func deflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){
return (nil, 0, nil)
}*/
}
/// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection.
@objc public protocol WebSocketDelegate {
/// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
func webSocketOpen()
/// A function to be called when the WebSocket connection's readyState changes to .Closed.
func webSocketClose(_ code: Int, reason: String, wasClean: Bool)
/// A function to be called when an error occurs.
func webSocketError(_ error: NSError)
/// A function to be called when a message (string) is received from the server.
@objc optional func webSocketMessageText(_ text: String)
/// A function to be called when a message (binary) is received from the server.
@objc optional func webSocketMessageData(_ data: Data)
/// A function to be called when a pong is received from the server.
@objc optional func webSocketPong()
/// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
@objc optional func webSocketEnd(_ code: Int, reason: String, wasClean: Bool, error: NSError?)
}
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
private class InnerWebSocket: Hashable {
var id : Int
var mutex = pthread_mutex_t()
let request : URLRequest!
let subProtocols : [String]!
var frames : [Frame] = []
var delegate : Delegate
var inflater : Inflater!
var deflater : Deflater!
var outputBytes : UnsafeMutablePointer<UInt8>?
var outputBytesSize : Int = 0
var outputBytesStart : Int = 0
var outputBytesLength : Int = 0
var inputBytes : UnsafeMutablePointer<UInt8>?
var inputBytesSize : Int = 0
var inputBytesStart : Int = 0
var inputBytesLength : Int = 0
var createdAt = CFAbsoluteTimeGetCurrent()
var connectionTimeout = false
var eclose : ()->() = {}
var _eventQueue : DispatchQueue? = DispatchQueue.main
var _subProtocol = ""
var _compression = WebSocketCompression()
var _allowSelfSignedSSL = false
var _services = WebSocketService.None
var _event = WebSocketEvents()
var _eventDelegate: WebSocketDelegate?
var _binaryType = WebSocketBinaryType.uInt8Array
var _readyState = WebSocketReadyState.connecting
var _networkTimeout = TimeInterval(-1)
var url : String {
return request.url!.description
}
var subProtocol : String {
get { return privateSubProtocol }
}
var privateSubProtocol : String {
get { lock(); defer { unlock() }; return _subProtocol }
set { lock(); defer { unlock() }; _subProtocol = newValue }
}
var compression : WebSocketCompression {
get { lock(); defer { unlock() }; return _compression }
set { lock(); defer { unlock() }; _compression = newValue }
}
var allowSelfSignedSSL : Bool {
get { lock(); defer { unlock() }; return _allowSelfSignedSSL }
set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue }
}
var services : WebSocketService {
get { lock(); defer { unlock() }; return _services }
set { lock(); defer { unlock() }; _services = newValue }
}
var event : WebSocketEvents {
get { lock(); defer { unlock() }; return _event }
set { lock(); defer { unlock() }; _event = newValue }
}
var eventDelegate : WebSocketDelegate? {
get { lock(); defer { unlock() }; return _eventDelegate }
set { lock(); defer { unlock() }; _eventDelegate = newValue }
}
var eventQueue : DispatchQueue? {
get { lock(); defer { unlock() }; return _eventQueue; }
set { lock(); defer { unlock() }; _eventQueue = newValue }
}
var binaryType : WebSocketBinaryType {
get { lock(); defer { unlock() }; return _binaryType }
set { lock(); defer { unlock() }; _binaryType = newValue }
}
var readyState : WebSocketReadyState {
get { return privateReadyState }
}
var privateReadyState : WebSocketReadyState {
get { lock(); defer { unlock() }; return _readyState }
set { lock(); defer { unlock() }; _readyState = newValue }
}
func copyOpen(_ request: URLRequest, subProtocols : [String] = []) -> InnerWebSocket{
let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
ws.eclose = eclose
ws.compression = compression
ws.allowSelfSignedSSL = allowSelfSignedSSL
ws.services = services
ws.event = event
ws.eventQueue = eventQueue
ws.binaryType = binaryType
return ws
}
var hashValue: Int { return id }
init(request: URLRequest, subProtocols : [String] = [], stub : Bool = false){
pthread_mutex_init(&mutex, nil)
self.id = manager.nextId()
self.request = request
self.subProtocols = subProtocols
self.outputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize)
self.outputBytesSize = windowBufferSize
self.inputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize)
self.inputBytesSize = windowBufferSize
self.delegate = Delegate()
if stub{
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
_ = self
}
} else {
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
manager.add(self)
}
}
}
deinit{
if outputBytes != nil {
free(outputBytes)
}
if inputBytes != nil {
free(inputBytes)
}
pthread_mutex_init(&mutex, nil)
}
@inline(__always) fileprivate func lock(){
pthread_mutex_lock(&mutex)
}
@inline(__always) fileprivate func unlock(){
pthread_mutex_unlock(&mutex)
}
fileprivate var dirty : Bool {
lock()
defer { unlock() }
if exit {
return false
}
if connectionTimeout {
return true
}
if stage != .readResponse && stage != .handleFrames {
return true
}
if rd.streamStatus == .opening && wr.streamStatus == .opening {
return false;
}
if rd.streamStatus != .open || wr.streamStatus != .open {
return true
}
if rd.streamError != nil || wr.streamError != nil {
return true
}
if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 {
return true
}
if outputBytesLength > 0 && wr.hasSpaceAvailable{
return true
}
return false
}
enum Stage : Int {
case openConn
case readResponse
case handleFrames
case closeConn
case end
}
var stage = Stage.openConn
var rd : InputStream!
var wr : OutputStream!
var atEnd = false
var closeCode = UInt16(0)
var closeReason = ""
var closeClean = false
var closeFinal = false
var finalError : Error?
var exit = false
var more = true
func step(){
if exit {
return
}
do {
try stepBuffers(more)
try stepStreamErrors()
more = false
switch stage {
case .openConn:
try openConn()
stage = .readResponse
case .readResponse:
try readResponse()
privateReadyState = .open
fire {
self.event.open()
self.eventDelegate?.webSocketOpen()
}
stage = .handleFrames
case .handleFrames:
try stepOutputFrames()
if closeFinal {
privateReadyState = .closing
stage = .closeConn
return
}
let frame = try readFrame()
switch frame.code {
case .text:
fire {
self.event.message(data: frame.utf8.text)
self.eventDelegate?.webSocketMessageText?(frame.utf8.text)
}
case .binary:
fire {
switch self.binaryType {
case .uInt8Array:
self.event.message(data: frame.payload.array)
case .nsData:
self.event.message(data: frame.payload.nsdata)
// The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData.
self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata)
case .uInt8UnsafeBufferPointer:
self.event.message(data: frame.payload.buffer)
}
}
case .ping:
let nframe = frame.copy()
nframe.code = .pong
lock()
frames += [nframe]
unlock()
case .pong:
fire {
switch self.binaryType {
case .uInt8Array:
self.event.pong(data: frame.payload.array)
case .nsData:
self.event.pong(data: frame.payload.nsdata)
case .uInt8UnsafeBufferPointer:
self.event.pong(data: frame.payload.buffer)
}
self.eventDelegate?.webSocketPong?()
}
case .close:
lock()
frames += [frame]
unlock()
default:
break
}
case .closeConn:
if let error = finalError {
self.event.error(error)
self.eventDelegate?.webSocketError(error as NSError)
}
privateReadyState = .closed
if rd != nil {
closeConn()
fire {
self.eclose()
self.event.close(Int(self.closeCode), self.closeReason, self.closeFinal)
self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
}
}
stage = .end
case .end:
fire {
self.event.end(Int(self.closeCode), self.closeReason, self.closeClean, self.finalError)
self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as NSError?)
}
exit = true
manager.remove(self)
}
} catch WebSocketError.needMoreInput {
more = true
} catch {
if finalError != nil {
return
}
finalError = error
if stage == .openConn || stage == .readResponse {
stage = .closeConn
} else {
var frame : Frame?
if let error = error as? WebSocketError{
switch error {
case .network(let details):
if details == atEndDetails{
stage = .closeConn
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
atEnd = true
finalError = nil
}
case .protocolError:
frame = Frame.makeClose(1002, reason: "Protocol error")
case .payloadError:
frame = Frame.makeClose(1007, reason: "Payload error")
default:
break
}
}
if frame == nil {
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
}
if let frame = frame {
if frame.statusCode == 1007 {
self.lock()
self.frames = [frame]
self.unlock()
manager.signal()
} else {
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
self.lock()
self.frames += [frame]
self.unlock()
manager.signal()
}
}
}
}
}
}
func stepBuffers(_ more: Bool) throws {
if rd != nil {
if stage != .closeConn && rd.streamStatus == Stream.Status.atEnd {
if atEnd {
return;
}
throw WebSocketError.network(atEndDetails)
}
if more {
while rd.hasBytesAvailable {
var size = inputBytesSize
while size-(inputBytesStart+inputBytesLength) < windowBufferSize {
size *= 2
}
if size > inputBytesSize {
let ptr = realloc(inputBytes, size)
if ptr == nil {
throw WebSocketError.memory
}
inputBytes = ptr?.assumingMemoryBound(to: UInt8.self)
inputBytesSize = size
}
let n = rd.read(inputBytes!+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength)
if n > 0 {
inputBytesLength += n
}
}
}
}
if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 {
let n = wr.write(outputBytes!+outputBytesStart, maxLength: outputBytesLength)
if n > 0 {
outputBytesLength -= n
if outputBytesLength == 0 {
outputBytesStart = 0
} else {
outputBytesStart += n
}
}
}
}
func stepStreamErrors() throws {
if finalError == nil {
if connectionTimeout {
throw WebSocketError.network(timeoutDetails)
}
if let error = rd?.streamError {
throw WebSocketError.network(error.localizedDescription)
}
if let error = wr?.streamError {
throw WebSocketError.network(error.localizedDescription)
}
}
}
func stepOutputFrames() throws {
lock()
defer {
frames = []
unlock()
}
if !closeFinal {
for frame in frames {
try writeFrame(frame)
if frame.code == .close {
closeCode = frame.statusCode
closeReason = frame.utf8.text
closeFinal = true
return
}
}
}
}
@inline(__always) func fire(_ block: ()->()){
if let queue = eventQueue {
queue.sync {
block()
}
} else {
block()
}
}
var readStateSaved = false
var readStateFrame : Frame?
var readStateFinished = false
var leaderFrame : Frame?
func readFrame() throws -> Frame {
var frame : Frame
var finished : Bool
if !readStateSaved {
if leaderFrame != nil {
frame = leaderFrame!
finished = false
leaderFrame = nil
} else {
frame = try readFrameFragment(nil)
finished = frame.finished
}
if frame.code == .continue{
throw WebSocketError.protocolError("leader frame cannot be a continue frame")
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.needMoreInput
}
} else {
frame = readStateFrame!
finished = readStateFinished
if !finished {
let cf = try readFrameFragment(frame)
finished = cf.finished
if cf.code != .continue {
if !cf.code.isControl {
throw WebSocketError.protocolError("only ping frames can be interlaced with fragments")
}
leaderFrame = frame
return cf
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.needMoreInput
}
}
}
if !frame.utf8.completed {
throw WebSocketError.payloadError("incomplete utf8")
}
readStateSaved = false
readStateFrame = nil
readStateFinished = false
return frame
}
func closeConn() {
rd.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
wr.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
rd.delegate = nil
wr.delegate = nil
rd.close()
wr.close()
}
func openConn() throws {
var req = request!
req.setValue("websocket", forHTTPHeaderField: "Upgrade")
req.setValue("Upgrade", forHTTPHeaderField: "Connection")
if req.value(forHTTPHeaderField: "User-Agent") == nil {
req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent")
}
req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version")
if req.url == nil || req.url!.host == nil{
throw WebSocketError.invalidAddress
}
if req.url!.port == nil || req.url!.port! == 80 || req.url!.port! == 443 {
req.setValue(req.url!.host!, forHTTPHeaderField: "Host")
} else {
req.setValue("\(req.url!.host!):\(req.url!.port!)", forHTTPHeaderField: "Host")
}
let origin = req.value(forHTTPHeaderField: "Origin")
if origin == nil || origin! == ""{
req.setValue(req.url!.absoluteString, forHTTPHeaderField: "Origin")
}
if subProtocols.count > 0 {
req.setValue(subProtocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol")
}
if req.url!.scheme != "wss" && req.url!.scheme != "ws" {
throw WebSocketError.invalidAddress
}
if compression.on {
var val = "permessage-deflate"
if compression.noContextTakeover {
val += "; client_no_context_takeover; server_no_context_takeover"
}
val += "; client_max_window_bits"
if compression.maxWindowBits != 0 {
val += "; server_max_window_bits=\(compression.maxWindowBits)"
}
req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions")
}
let security: TCPConnSecurity
let port : Int
if req.url!.scheme == "wss" {
port = req.url!.port ?? 443
security = .negoticatedSSL
} else {
port = req.url!.port ?? 80
security = .none
}
var path = CFURLCopyPath(req.url! as CFURL!) as String
if path == "" {
path = "/"
}
if let q = req.url!.query {
if q != "" {
path += "?" + q
}
}
var reqs = "GET \(path) HTTP/1.1\r\n"
for key in req.allHTTPHeaderFields!.keys {
if let val = req.value(forHTTPHeaderField: key) {
reqs += "\(key): \(val)\r\n"
}
}
var keyb = [UInt32](repeating: 0, count: 4)
for i in 0 ..< 4 {
keyb[i] = arc4random()
}
let rkey = Data(bytes: UnsafePointer(keyb), count: 16).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
reqs += "Sec-WebSocket-Key: \(rkey)\r\n"
reqs += "\r\n"
var header = [UInt8]()
for b in reqs.utf8 {
header += [b]
}
let addr = ["\(req.url!.host!)", "\(port)"]
if addr.count != 2 || Int(addr[1]) == nil {
throw WebSocketError.invalidAddress
}
var (rdo, wro) : (InputStream?, OutputStream?)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, addr[0] as CFString!, UInt32(Int(addr[1])!), &readStream, &writeStream);
rdo = readStream!.takeRetainedValue()
wro = writeStream!.takeRetainedValue()
(rd, wr) = (rdo!, wro!)
rd.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey)
wr.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey)
if services.contains(.VoIP) {
rd.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Video) {
rd.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Background) {
rd.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Voice) {
rd.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if allowSelfSignedSSL {
let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(value: false)]
rd.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String))
wr.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String))
}
rd.delegate = delegate
wr.delegate = delegate
rd.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
wr.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
rd.open()
wr.open()
try write(header, length: header.count)
}
func write(_ bytes: UnsafePointer<UInt8>, length: Int) throws {
if outputBytesStart+outputBytesLength+length > outputBytesSize {
var size = outputBytesSize
while outputBytesStart+outputBytesLength+length > size {
size *= 2
}
let ptr = realloc(outputBytes, size)
if ptr == nil {
throw WebSocketError.memory
}
outputBytes = ptr?.assumingMemoryBound(to: UInt8.self)
outputBytesSize = size
}
memcpy(outputBytes!+outputBytesStart+outputBytesLength, bytes, length)
outputBytesLength += length
}
func readResponse() throws {
let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ]
let ptr = memmem(inputBytes!+inputBytesStart, inputBytesLength, end, 4)
if ptr == nil {
throw WebSocketError.needMoreInput
}
let buffer = inputBytes!+inputBytesStart
let bufferCount = ptr!.assumingMemoryBound(to: UInt8.self)-(inputBytes!+inputBytesStart)
let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: String.Encoding.utf8.rawValue, freeWhenDone: false) as String?
if string == nil {
throw WebSocketError.invalidHeader
}
let header = string!
var needsCompression = false
var serverMaxWindowBits = 15
let clientMaxWindowBits = 15
var key = ""
let trim : (String)->(String) = { (text) in return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)}
let eqval : (String,String)->(String) = { (line, del) in return trim(line.components(separatedBy: del)[1]) }
let lines = header.components(separatedBy: "\r\n")
for i in 0 ..< lines.count {
let line = trim(lines[i])
if i == 0 {
if !line.hasPrefix("HTTP/1.1 101"){
throw WebSocketError.invalidResponse(line)
}
} else if line != "" {
var value = ""
if line.hasPrefix("\t") || line.hasPrefix(" ") {
value = trim(line)
} else {
key = ""
if let r = line.range(of: ":") {
key = trim(line.substring(to: r.lowerBound))
value = trim(line.substring(from: r.upperBound))
}
}
switch key.lowercased() {
case "sec-websocket-subprotocol":
privateSubProtocol = value
case "sec-websocket-extensions":
let parts = value.components(separatedBy: ";")
for p in parts {
let part = trim(p)
if part == "permessage-deflate" {
needsCompression = true
} else if part.hasPrefix("server_max_window_bits="){
if let i = Int(eqval(line, "=")) {
serverMaxWindowBits = i
}
}
}
default:
break
}
}
}
if needsCompression {
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.invalidCompressionOptions("server_max_window_bits")
}
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.invalidCompressionOptions("client_max_window_bits")
}
inflater = Inflater(windowBits: serverMaxWindowBits)
if inflater == nil {
throw WebSocketError.invalidCompressionOptions("inflater init")
}
deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8)
if deflater == nil {
throw WebSocketError.invalidCompressionOptions("deflater init")
}
}
inputBytesLength -= bufferCount+4
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += bufferCount+4
}
}
class ByteReader {
var start : UnsafePointer<UInt8>
var end : UnsafePointer<UInt8>
var bytes : UnsafePointer<UInt8>
init(bytes: UnsafePointer<UInt8>, length: Int){
self.bytes = bytes
start = bytes
end = bytes+length
}
func readByte() throws -> UInt8 {
if bytes >= end {
throw WebSocketError.needMoreInput
}
let b = bytes.pointee
bytes += 1
return b
}
var length : Int {
return end - bytes
}
var position : Int {
get {
return bytes - start
}
set {
bytes = start + newValue
}
}
}
var fragStateSaved = false
var fragStatePosition = 0
var fragStateInflate = false
var fragStateLen = 0
var fragStateFin = false
var fragStateCode = OpCode.continue
var fragStateLeaderCode = OpCode.continue
var fragStateUTF8 = UTF8()
var fragStatePayload = Payload()
var fragStateStatusCode = UInt16(0)
var fragStateHeaderLen = 0
var buffer = [UInt8](repeating: 0, count: windowBufferSize)
var reusedPayload = Payload()
func readFrameFragment(_ leader : Frame?) throws -> Frame {
var inflate : Bool
var len : Int
var fin = false
var code : OpCode
var leaderCode : OpCode
var utf8 : UTF8
var payload : Payload
var statusCode : UInt16
var headerLen : Int
var leader = leader
let reader = ByteReader(bytes: inputBytes!+inputBytesStart, length: inputBytesLength)
if fragStateSaved {
// load state
reader.position += fragStatePosition
inflate = fragStateInflate
len = fragStateLen
fin = fragStateFin
code = fragStateCode
leaderCode = fragStateLeaderCode
utf8 = fragStateUTF8
payload = fragStatePayload
statusCode = fragStateStatusCode
headerLen = fragStateHeaderLen
fragStateSaved = false
} else {
var b = try reader.readByte()
fin = b >> 7 & 0x1 == 0x1
let rsv1 = b >> 6 & 0x1 == 0x1
let rsv2 = b >> 5 & 0x1 == 0x1
let rsv3 = b >> 4 & 0x1 == 0x1
if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) {
inflate = true
} else if rsv1 || rsv2 || rsv3 {
throw WebSocketError.protocolError("invalid extension")
} else {
inflate = false
}
code = OpCode.binary
if let c = OpCode(rawValue: (b & 0xF)){
code = c
} else {
throw WebSocketError.protocolError("invalid opcode")
}
if !fin && code.isControl {
throw WebSocketError.protocolError("unfinished control frame")
}
b = try reader.readByte()
if b >> 7 & 0x1 == 0x1 {
throw WebSocketError.protocolError("server sent masked frame")
}
var len64 = Int64(b & 0x7F)
var bcount = 0
if b & 0x7F == 126 {
bcount = 2
} else if len64 == 127 {
bcount = 8
}
if bcount != 0 {
if code.isControl {
throw WebSocketError.protocolError("invalid payload size for control frame")
}
len64 = 0
var i = bcount-1
while i >= 0 {
b = try reader.readByte()
len64 += Int64(b) << Int64(i*8)
i -= 1
}
}
len = Int(len64)
if code == .continue {
if code.isControl {
throw WebSocketError.protocolError("control frame cannot have the 'continue' opcode")
}
if leader == nil {
throw WebSocketError.protocolError("continue frame is missing it's leader")
}
}
if code.isControl {
if leader != nil {
leader = nil
}
if inflate {
throw WebSocketError.protocolError("control frame cannot be compressed")
}
}
statusCode = 0
if leader != nil {
leaderCode = leader!.code
utf8 = leader!.utf8
payload = leader!.payload
} else {
leaderCode = code
utf8 = UTF8()
payload = reusedPayload
payload.count = 0
}
if leaderCode == .close {
if len == 1 {
throw WebSocketError.protocolError("invalid payload size for close frame")
}
if len >= 2 {
let b1 = try reader.readByte()
let b2 = try reader.readByte()
statusCode = (UInt16(b1) << 8) + UInt16(b2)
len -= 2
if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) {
throw WebSocketError.protocolError("invalid status code for close frame")
}
}
}
headerLen = reader.position
}
let rlen : Int
let rfin : Bool
let chopped : Bool
if reader.length+reader.position-headerLen < len {
rlen = reader.length
rfin = false
chopped = true
} else {
rlen = len-reader.position+headerLen
rfin = fin
chopped = false
}
let bytes : UnsafeMutablePointer<UInt8>
let bytesLen : Int
if inflate {
(bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin)
} else {
(bytes, bytesLen) = (UnsafeMutablePointer<UInt8>.init(mutating: reader.bytes), rlen)
}
reader.bytes += rlen
if leaderCode == .text || leaderCode == .close {
try utf8.append(bytes, length: bytesLen)
} else {
payload.append(bytes, length: bytesLen)
}
if chopped {
// save state
fragStateHeaderLen = headerLen
fragStateStatusCode = statusCode
fragStatePayload = payload
fragStateUTF8 = utf8
fragStateLeaderCode = leaderCode
fragStateCode = code
fragStateFin = fin
fragStateLen = len
fragStateInflate = inflate
fragStatePosition = reader.position
fragStateSaved = true
throw WebSocketError.needMoreInput
}
inputBytesLength -= reader.position
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += reader.position
}
let f = Frame()
(f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin)
return f
}
var head = [UInt8](repeating: 0, count: 0xFF)
func writeFrame(_ f : Frame) throws {
if !f.finished{
throw WebSocketError.libraryError("cannot send unfinished frames")
}
var hlen = 0
let b : UInt8 = 0x80
var deflate = false
if deflater != nil {
if f.code == .binary || f.code == .text {
deflate = true
// b |= 0x40
}
}
head[hlen] = b | f.code.rawValue
hlen += 1
var payloadBytes : [UInt8]
var payloadLen = 0
if f.utf8.text != "" {
payloadBytes = UTF8.bytes(f.utf8.text)
} else {
payloadBytes = f.payload.array
}
payloadLen += payloadBytes.count
if deflate {
}
var usingStatusCode = false
if f.statusCode != 0 && payloadLen != 0 {
payloadLen += 2
usingStatusCode = true
}
if payloadLen < 126 {
head[hlen] = 0x80 | UInt8(payloadLen)
hlen += 1
} else if payloadLen <= 0xFFFF {
head[hlen] = 0x80 | 126
hlen += 1
var i = 1
while i >= 0 {
head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF)
hlen += 1
i -= 1
}
} else {
head[hlen] = UInt8((0x1 << 7) + 127)
hlen += 1
var i = 7
while i >= 0 {
head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF)
hlen += 1
i -= 1
}
}
let r = arc4random()
var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)]
for i in 0 ..< 4 {
head[hlen] = maskBytes[i]
hlen += 1
}
if payloadLen > 0 {
if usingStatusCode {
var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)]
for i in 0 ..< 2 {
sc[i] ^= maskBytes[i % 4]
}
head[hlen] = sc[0]
hlen += 1
head[hlen] = sc[1]
hlen += 1
for i in 2 ..< payloadLen {
payloadBytes[i-2] ^= maskBytes[i % 4]
}
} else {
for i in 0 ..< payloadLen {
payloadBytes[i] ^= maskBytes[i % 4]
}
}
}
try write(head, length: hlen)
try write(payloadBytes, length: payloadBytes.count)
}
func close(_ code : Int = 1000, reason : String = "Normal Closure") {
let f = Frame()
f.code = .close
f.statusCode = UInt16(truncatingBitPattern: code)
f.utf8.text = reason
sendFrame(f)
}
func sendFrame(_ f : Frame) {
lock()
frames += [f]
unlock()
manager.signal()
}
func send(_ message : Any) {
let f = Frame()
if let message = message as? String {
f.code = .text
f.utf8.text = message
} else if let message = message as? [UInt8] {
f.code = .binary
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.code = .binary
f.payload.append(message.baseAddress!, length: message.count)
} else if let message = message as? Data {
f.code = .binary
f.payload.nsdata = message
} else {
f.code = .text
f.utf8.text = "\(message)"
}
sendFrame(f)
}
func ping() {
let f = Frame()
f.code = .ping
sendFrame(f)
}
func ping(_ message : Any){
let f = Frame()
f.code = .ping
if let message = message as? String {
f.payload.array = UTF8.bytes(message)
} else if let message = message as? [UInt8] {
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.payload.append(message.baseAddress!, length: message.count)
} else if let message = message as? Data {
f.payload.nsdata = message
} else {
f.utf8.text = "\(message)"
}
sendFrame(f)
}
}
private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool {
return lhs.id == rhs.id
}
private enum TCPConnSecurity {
case none
case negoticatedSSL
var level: String {
switch self {
case .none: return StreamSocketSecurityLevel.none.rawValue
case .negoticatedSSL: return StreamSocketSecurityLevel.negotiatedSSL.rawValue
}
}
}
// Manager class is used to minimize the number of dispatches and cycle through network events
// using fewers threads. Helps tremendously with lowing system resources when many conncurrent
// sockets are opened.
private class Manager {
var queue = DispatchQueue(label: "SwiftWebSocketInstance", attributes: [])
var once = Int()
var mutex = pthread_mutex_t()
var cond = pthread_cond_t()
var websockets = Set<InnerWebSocket>()
var _nextId = 0
init(){
pthread_mutex_init(&mutex, nil)
pthread_cond_init(&cond, nil)
DispatchQueue(label: "SwiftWebSocket", attributes: []).async {
var wss : [InnerWebSocket] = []
while true {
var wait = true
wss.removeAll()
pthread_mutex_lock(&self.mutex)
for ws in self.websockets {
wss.append(ws)
}
for ws in wss {
self.checkForConnectionTimeout(ws)
if ws.dirty {
pthread_mutex_unlock(&self.mutex)
ws.step()
pthread_mutex_lock(&self.mutex)
wait = false
}
}
if wait {
_ = self.wait(250)
}
pthread_mutex_unlock(&self.mutex)
}
}
}
func checkForConnectionTimeout(_ ws : InnerWebSocket) {
if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .opening || ws.wr.streamStatus == .opening) {
let age = CFAbsoluteTimeGetCurrent() - ws.createdAt
if age >= timeoutDuration {
ws.connectionTimeout = true
}
}
}
func wait(_ timeInMs : Int) -> Int32 {
var ts = timespec()
var tv = timeval()
gettimeofday(&tv, nil)
ts.tv_sec = time(nil) + timeInMs / 1000;
let v1 = Int(tv.tv_usec * 1000)
let v2 = Int(1000 * 1000 * Int(timeInMs % 1000))
ts.tv_nsec = v1 + v2;
ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
ts.tv_nsec %= (1000 * 1000 * 1000);
return pthread_cond_timedwait(&self.cond, &self.mutex, &ts)
}
func signal(){
pthread_mutex_lock(&mutex)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func add(_ websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.insert(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func remove(_ websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.remove(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func nextId() -> Int {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
_nextId += 1
return _nextId
}
}
private let manager = Manager()
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
open class WebSocket: NSObject {
fileprivate var ws: InnerWebSocket
fileprivate var id = manager.nextId()
fileprivate var opened: Bool
open override var hashValue: Int { return id }
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(_ url: String){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(url: URL){
self.init(request: URLRequest(url: url), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public convenience init(_ url: String, subProtocols : [String]){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols)
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public convenience init(_ url: String, subProtocol : String){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol])
}
/// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols.
public init(request: URLRequest, subProtocols : [String] = []){
let hasURL = request.url != nil
opened = hasURL
ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: !hasURL)
super.init()
// weak/strong pattern from:
// http://stackoverflow.com/a/17105368/424124
// https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/
ws.eclose = { [weak self] in
if let strongSelf = self {
strongSelf.opened = false
}
}
}
/// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called.
public convenience override init(){
var request = URLRequest(url: URL(string: "http://apple.com")!)
request.url = nil
self.init(request: request, subProtocols: [])
}
/// The URL as resolved by the constructor. This is always an absolute URL. Read only.
open var url : String{ return ws.url }
/// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
open var subProtocol : String{ return ws.subProtocol }
/// The compression options of the WebSocket.
open var compression : WebSocketCompression{
get { return ws.compression }
set { ws.compression = newValue }
}
/// Allow for Self-Signed SSL Certificates. Default is false.
open var allowSelfSignedSSL : Bool{
get { return ws.allowSelfSignedSSL }
set { ws.allowSelfSignedSSL = newValue }
}
/// The services of the WebSocket.
open var services : WebSocketService{
get { return ws.services }
set { ws.services = newValue }
}
/// The events of the WebSocket.
open var event : WebSocketEvents{
get { return ws.event }
set { ws.event = newValue }
}
/// The queue for firing off events. default is main_queue
open var eventQueue : DispatchQueue?{
get { return ws.eventQueue }
set { ws.eventQueue = newValue }
}
/// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array.
open var binaryType : WebSocketBinaryType{
get { return ws.binaryType }
set { ws.binaryType = newValue }
}
/// The current state of the connection; this is one of the WebSocketReadyState constants. Read only.
open var readyState : WebSocketReadyState{
return ws.readyState
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
open func open(_ url: String){
open(request: URLRequest(url: URL(string: url)!), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
open func open(nsurl url: URL){
open(request: URLRequest(url: url), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
open func open(_ url: String, subProtocols : [String]){
open(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols)
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
open func open(_ url: String, subProtocol : String){
open(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol])
}
/// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols.
open func open(request: URLRequest, subProtocols : [String] = []){
if opened{
return
}
opened = true
ws = ws.copyOpen(request, subProtocols: subProtocols)
}
/// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket
open func open(){
open(request: ws.request, subProtocols: ws.subProtocols)
}
/**
Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing.
:param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed.
:param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).
*/
open func close(_ code : Int = 1000, reason : String = "Normal Closure"){
if !opened{
return
}
opened = false
ws.close(code, reason: reason)
}
/**
Transmits message to the server over the WebSocket connection.
:param: message The message to be sent to the server.
*/
open func send(_ message : Any){
if !opened{
return
}
ws.send(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
:param: optional message The data to be sent to the server.
*/
open func ping(_ message : Any){
if !opened{
return
}
ws.ping(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
*/
open func ping(){
if !opened{
return
}
ws.ping()
}
}
public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool {
return lhs.id == rhs.id
}
extension WebSocket {
/// The events of the WebSocket using a delegate.
public var delegate : WebSocketDelegate? {
get { return ws.eventDelegate }
set { ws.eventDelegate = newValue }
}
/**
Transmits message to the server over the WebSocket connection.
:param: text The message (string) to be sent to the server.
*/
@objc
public func send(text: String){
send(text)
}
/**
Transmits message to the server over the WebSocket connection.
:param: data The message (binary) to be sent to the server.
*/
@objc
public func send(data: Data){
send(data)
}
}
| apache-2.0 | f2c2c6c6857dd5238a8b385c1d8ac396 | 36.645003 | 225 | 0.553302 | 4.942847 | false | false | false | false |
gottesmm/swift | test/Serialization/function.swift | 2 | 5297 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
// RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT
// CHECK-NOT: UnknownCode
import def_func
func useEq<T: EqualOperator>(_ x: T, y: T) -> Bool {
return x == y
}
// SIL: sil @main
// SIL: [[RAW:%.+]] = global_addr @_T08function3rawSiv : $*Int
// SIL: [[ZERO:%.+]] = function_ref @_T08def_func7getZeroSiyF : $@convention(thin) () -> Int
// SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Int
var raw = getZero()
// Check that 'raw' is an Int
var cooked : Int = raw
// SIL: [[GET_INPUT:%.+]] = function_ref @_T08def_func8getInputSiSi1x_tF : $@convention(thin) (Int) -> Int
// SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
var raw2 = getInput(x: raw)
// SIL: [[GET_SECOND:%.+]] = function_ref @_T08def_func9getSecondSiSi_Si1ytF : $@convention(thin) (Int, Int) -> Int
// SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
var raw3 = getSecond(raw, y: raw2)
// SIL: [[USE_NESTED:%.+]] = function_ref @_T08def_func9useNestedySi1x_Si1yt_Si1ntF : $@convention(thin) (Int, Int, Int) -> ()
// SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
useNested((raw, raw2), n: raw3)
// SIL: [[VARIADIC:%.+]] = function_ref @_T08def_func8variadicySd1x_SaySiGdtF : $@convention(thin) (Double, @owned Array<Int>) -> ()
// SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
// SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
// SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @owned Array<Int>) -> ()
variadic(x: 2.5, 4, 5)
// SIL: [[VARIADIC:%.+]] = function_ref @_T08def_func9variadic2ySaySiG_Sd1xtF : $@convention(thin) (@owned Array<Int>, Double) -> ()
variadic2(1, 2, 3, x: 5.0)
// SIL: [[SLICE:%.+]] = function_ref @_T08def_func5sliceySaySiG1x_tF : $@convention(thin) (@owned Array<Int>) -> ()
// SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
// SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
// SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@owned Array<Int>) -> ()
slice(x: [2, 4, 5])
optional(x: .some(23))
optional(x: .none)
// SIL: [[MAKE_PAIR:%.+]] = function_ref @_T08def_func8makePair{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @in τ_0_1) -> (@out τ_0_0, @out τ_0_1)
// SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}})
var pair : (Int, Double) = makePair(a: 1, b: 2.5)
// SIL: [[DIFFERENT_A:%.+]] = function_ref @_T08def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT_B:%.+]] = function_ref @_T08def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
_ = different(a: 1, b: 2)
_ = different(a: false, b: false)
// SIL: [[DIFFERENT2_A:%.+]] = function_ref @_T08def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT2_B:%.+]] = function_ref @_T08def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
_ = different2(a: 1, b: 2)
_ = different2(a: false, b: false)
struct IntWrapper1 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 1 }
}
struct IntWrapper2 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 2 }
}
// SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @_T08def_func16differentWrappedSbx1a_q_1btAA0D0RzAaER_5ValueQzAFRt_r0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_1.Value == τ_0_0.Value> (@in τ_0_0, @in τ_0_1) -> Bool
_ = differentWrapped(a: IntWrapper1(), b: IntWrapper2())
// SIL: {{%.+}} = function_ref @_T08def_func10overloadedySi1x_tF : $@convention(thin) (Int) -> ()
// SIL: {{%.+}} = function_ref @_T08def_func10overloadedySb1x_tF : $@convention(thin) (Bool) -> ()
overloaded(x: 1)
overloaded(x: false)
// SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> ()
primitive()
if raw == 5 {
testNoReturnAttr()
testNoReturnAttrPoly(x: 5)
}
// SIL: {{%.+}} = function_ref @_T08def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: {{%.+}} = function_ref @_T08def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Never
// SIL: sil @_T08def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: sil @_T08def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Never
do {
try throws1()
_ = try throws2(1)
} catch _ {}
// SIL: sil @_T08def_func7throws1yyKF : $@convention(thin) () -> @error Error
// SIL: sil @_T08def_func7throws2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error)
// LLVM: }
| apache-2.0 | ec924278b9d628a6c1cacff31e912c43 | 42.833333 | 257 | 0.58327 | 2.741011 | false | true | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/OldModels/MovieCreditsMDB.swift | 1 | 1282 | //
// MovieCreditsMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-03-08.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public class MovieCreditsMDB: Decodable {
public var cast: [MovieCastMDB]?
public var crew: [CrewMDB]?
enum CodingKeys: String, CodingKey {
case cast
case crew
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
cast = try? container.decode([MovieCastMDB]?.self, forKey: .cast)
crew = try? container.decode([CrewMDB]?.self, forKey: .crew)
}
}
public class MovieCastMDB: CastCrewCommonMDB {
public var cast_id: Int!
public var character: String!
public var order: Int!
enum CodingKeys: String, CodingKey {
case cast_id
case character
case order
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
cast_id = try? container.decode(Int?.self, forKey: .cast_id)
character = try? container.decode(String?.self, forKey: .character)
order = try? container.decode(Int?.self, forKey: .order)
try super.init(from: decoder)
}
}
| mit | 9551937bce8eda7768546186340ec8c2 | 27.466667 | 75 | 0.656518 | 4.028302 | false | false | false | false |
VBVMI/VerseByVerse-iOS | Pods/XCGLogger/Sources/XCGLogger/Destinations/AutoRotatingFileDestination.swift | 1 | 12632 | //
// AutoRotatingFileDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-03-31.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
// MARK: - AutoRotatingFileDestination
/// A destination that outputs log details to files in a log folder, with auto-rotate options (by size or by time)
open class AutoRotatingFileDestination: FileDestination {
// MARK: - Constants
public static let autoRotatingFileDefaultMaxFileSize: UInt64 = 1_048_576
public static let autoRotatingFileDefaultMaxTimeInterval: TimeInterval = 600
// MARK: - Properties
/// Option: desired maximum size of a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize {
didSet {
if targetMaxFileSize < 1 {
targetMaxFileSize = .max
}
}
}
/// Option: desired maximum time in seconds stored in a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval {
didSet {
if targetMaxTimeInterval < 1 {
targetMaxTimeInterval = 0
}
}
}
/// Option: the desired number of archived log files to keep (number of log files may exceed this, it's a guideline only)
open var targetMaxLogFiles: UInt8 = 10 {
didSet {
cleanUpLogFiles()
}
}
/// Option: the URL of the folder to store archived log files (defaults to the same folder as the initial log file)
open var archiveFolderURL: URL? = nil {
didSet {
guard let archiveFolderURL = archiveFolderURL else { return }
try? FileManager.default.createDirectory(at: archiveFolderURL, withIntermediateDirectories: true)
}
}
/// Option: an optional closure to execute whenever the log is auto rotated
open var autoRotationCompletion: ((_ success: Bool) -> Void)? = nil
/// A custom date formatter object to use as the suffix of archived log files
internal var _customArchiveSuffixDateFormatter: DateFormatter? = nil
/// The date formatter object to use as the suffix of archived log files
open var archiveSuffixDateFormatter: DateFormatter! {
get {
guard _customArchiveSuffixDateFormatter == nil else { return _customArchiveSuffixDateFormatter }
struct Statics {
static var archiveSuffixDateFormatter: DateFormatter = {
let defaultArchiveSuffixDateFormatter = DateFormatter()
defaultArchiveSuffixDateFormatter.locale = NSLocale.current
defaultArchiveSuffixDateFormatter.dateFormat = "_yyyy-MM-dd_HHmmss"
return defaultArchiveSuffixDateFormatter
}()
}
return Statics.archiveSuffixDateFormatter
}
set {
_customArchiveSuffixDateFormatter = newValue
}
}
/// Size of the current log file
internal var currentLogFileSize: UInt64 = 0
/// Start time of the current log file
internal var currentLogStartTimeInterval: TimeInterval = 0
/// The base file name of the log file
internal var baseFileName: String = "xcglogger"
/// The extension of the log file name
internal var fileExtension: String = "log"
// MARK: - Class Properties
/// A default folder for storing archived logs if one isn't supplied
open class var defaultLogFolderURL: URL {
#if os(OSX)
let defaultLogFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#elseif os(iOS) || os(tvOS) || os(watchOS)
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let defaultLogFolderURL = urls[urls.endIndex - 1].appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#endif
}
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [FileAttributeKey: Any]? = nil, maxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize, maxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval, archiveSuffixDateFormatter: DateFormatter? = nil) {
super.init(owner: owner, writeToFile: writeToFile, identifier: identifier, shouldAppend: true, appendMarker: shouldAppend ? appendMarker : nil, attributes: attributes)
currentLogStartTimeInterval = Date().timeIntervalSince1970
self.archiveSuffixDateFormatter = archiveSuffixDateFormatter
self.shouldAppend = shouldAppend
self.targetMaxFileSize = maxFileSize
self.targetMaxTimeInterval = maxTimeInterval
guard let writeToFileURL = writeToFileURL else { return }
// Calculate some details for naming archived logs based on the current log file path/name
fileExtension = writeToFileURL.pathExtension
baseFileName = writeToFileURL.lastPathComponent
if let fileExtensionRange: Range = baseFileName.range(of: ".\(fileExtension)", options: .backwards),
fileExtensionRange.upperBound >= baseFileName.endIndex {
baseFileName = String(baseFileName[baseFileName.startIndex ..< fileExtensionRange.lowerBound])
}
let filePath: String = writeToFileURL.path
let logFileName: String = "\(baseFileName).\(fileExtension)"
if let logFileNameRange: Range = filePath.range(of: logFileName, options: .backwards),
logFileNameRange.upperBound >= filePath.endIndex {
let archiveFolderPath: String = String(filePath[filePath.startIndex ..< logFileNameRange.lowerBound])
archiveFolderURL = URL(fileURLWithPath: "\(archiveFolderPath)")
}
if archiveFolderURL == nil {
archiveFolderURL = type(of: self).defaultLogFolderURL
}
do {
// Initialize starting values for file size and start time so shouldRotate calculations are valid
let fileAttributes: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
currentLogFileSize = fileAttributes[.size] as? UInt64 ?? 0
currentLogStartTimeInterval = (fileAttributes[.creationDate] as? Date ?? Date()).timeIntervalSince1970
}
catch let error as NSError {
owner?._logln("Unable to determine current file attributes of log file: \(error.localizedDescription)", level: .warning)
}
// Because we always start by appending, regardless of the shouldAppend setting, we now need to handle the cases where we don't want to append or that we have now reached the rotation threshold for our current log file
if !shouldAppend || shouldRotate() {
rotateFile()
}
}
/// Scan the log folder and delete log files that are no longer relevant.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func cleanUpLogFiles() {
var archivedFileURLs: [URL] = self.archivedFileURLs()
guard archivedFileURLs.count > Int(targetMaxLogFiles) else { return }
archivedFileURLs.removeFirst(Int(targetMaxLogFiles))
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Delete all archived log files.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func purgeArchivedLogFiles() {
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs() {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Get the URLs of the archived log files.
///
/// - Parameters: None.
///
/// - Returns: An array of file URLs pointing to previously archived log files, sorted with the most recent logs first.
///
open func archivedFileURLs() -> [URL] {
let archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: archiveFolderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) else { return [] }
guard let identifierData: Data = identifier.data(using: .utf8) else { return [] }
var archivedDetails: [(url: URL, timestamp: String)] = []
for fileURL in fileURLs {
guard let archivedLogIdentifierOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey) else { continue }
guard let archivedLogIdentifierData = archivedLogIdentifierOptionalData else { continue }
guard archivedLogIdentifierData == identifierData else { continue }
guard let timestampOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey) else { continue }
guard let timestampData = timestampOptionalData else { continue }
guard let timestamp = String(data: timestampData, encoding: .utf8) else { continue }
archivedDetails.append((fileURL, timestamp))
}
archivedDetails.sort(by: { (lhs, rhs) -> Bool in lhs.timestamp > rhs.timestamp })
var archivedFileURLs: [URL] = []
for archivedDetail in archivedDetails {
archivedFileURLs.append(archivedDetail.url)
}
return archivedFileURLs
}
/// Rotate the current log file.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func rotateFile() {
var archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
archiveFolderURL = archiveFolderURL.appendingPathComponent("\(baseFileName)\(archiveSuffixDateFormatter.string(from: Date()))")
archiveFolderURL = archiveFolderURL.appendingPathExtension(fileExtension)
rotateFile(to: archiveFolderURL, closure: autoRotationCompletion)
currentLogStartTimeInterval = Date().timeIntervalSince1970
currentLogFileSize = 0
cleanUpLogFiles()
}
/// Determine if the log file should be rotated.
///
/// - Parameters: None.
///
/// - Returns:
/// - true: The log file should be rotated.
/// - false: The log file doesn't have to be rotated.
///
open func shouldRotate() -> Bool {
// Do not rotate until critical setup has been completed so that we do not accidentally rotate once to the defaultLogFolderURL before determining the desired log location
guard archiveFolderURL != nil else { return false }
// File Size
guard currentLogFileSize < targetMaxFileSize else { return true }
// Time Interval, zero = never rotate
guard targetMaxTimeInterval > 0 else { return false }
// Time Interval, else check time
guard Date().timeIntervalSince1970 - currentLogStartTimeInterval < targetMaxTimeInterval else { return true }
return false
}
// MARK: - Overridden Methods
/// Write the log to the log file.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func write(message: String) {
currentLogFileSize += UInt64(message.characters.count)
super.write(message: message)
if shouldRotate() {
rotateFile()
}
}
}
| mit | cc88a0e73daa335b94ae3a3f5ec24dfa | 43.319298 | 379 | 0.662814 | 5.414059 | false | false | false | false |
juliangrosshauser/PercentAge | PercentAgeKitTests/Classes/AgeViewModelSpec.swift | 1 | 8286 | //
// AgeViewModelSpec.swift
// PercentAgeKitTests
//
// Created by Julian Grosshauser on 14/03/15.
// Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//
import Quick
import Nimble
import PercentAgeKit
class AgeViewModelSpec: QuickSpec {
override func spec() {
var dateFormatter: NSDateFormatter!
beforeSuite {
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
}
describe("AgeViewModel") {
var ageViewModel: AgeViewModel!
beforeEach {
ageViewModel = AgeViewModel()
}
//MARK: ageInPercent
describe("ageInPercent") {
var birthday: NSDate!
var today: NSDate!
context("when birthday is today") {
beforeEach {
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("06-03-2015")
}
it("returns whole number") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("24.00"))
}
}
context("when birthday hasn't happened this year yet") {
beforeEach {
// difference of 31 days
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("03-02-2015")
}
it("returns correct age in percent") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("23.92"))
}
}
context("when birthday has happened this year already") {
beforeEach {
// difference of 31 days
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("06-04-2015")
}
it("returns correct age in percent") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("24.08"))
}
}
}
//MARK: dayDifference
describe("dayDifference") {
var before: NSDate!
var after: NSDate!
context("dates are in same year") {
context("dates are in same month") {
context("dates are on same day") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-03-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(0))
}
}
context("dates are on different days") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("27-03-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(21))
}
}
}
context("dates are in different months") {
context("dates are on same day") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-05-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(61))
}
}
context("dates are on different days") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("18-04-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(43))
}
}
}
}
context("dates are in different years") {
context("dates are in same month") {
context("dates are on same day") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-03-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(731))
}
}
context("dates are on different days") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("11-03-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(736))
}
}
}
context("dates are in different months") {
context("dates are on same day") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-04-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(762))
}
}
context("dates are on different days") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("14-05-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(800))
}
}
}
}
context("before and after dates are switched") {
it("returns negative number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("07-03-1991")
let days = ageViewModel.dayDifference(before: after, after: before)
expect(days).to(equal(-1))
}
}
}
}
}
}
| mit | ab6a0d3094b864dcefb2e1391388d3e3 | 42.15625 | 102 | 0.439899 | 6.383667 | false | false | false | false |
nickfalk/BSImagePicker | Pod/Classes/View/AlbumTitleView.swift | 2 | 3021 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
/**
The navigation title view with album name and a button for activating the drop down.
*/
final class AlbumTitleView: UIView {
@IBOutlet weak var albumButton: UIButton!
fileprivate var context = 0
var albumTitle = "" {
didSet {
if let imageView = self.albumButton?.imageView, let titleLabel = self.albumButton?.titleLabel {
// Set title on button
albumButton?.setTitle(self.albumTitle, for: UIControlState())
// Also set title directly to label, since it isn't done right away when setting button title
// And we need to know its width to calculate insets
titleLabel.text = self.albumTitle
titleLabel.sizeToFit()
// Adjust insets to right align image
albumButton?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.bounds.size.width, bottom: 0, right: imageView.bounds.size.width)
albumButton?.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.bounds.size.width + 4, bottom: 0, right: -(titleLabel.bounds.size.width + 4))
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Set image
albumButton?.setImage(arrowDownImage, for: UIControlState())
}
lazy var arrowDownImage: UIImage? = {
// Get path for BSImagePicker bundle
let bundlePath = Bundle(for: PhotosViewController.self).path(forResource: "BSImagePicker", ofType: "bundle")
let bundle: Bundle?
// Load bundle
if let bundlePath = bundlePath {
bundle = Bundle(path: bundlePath)
} else {
bundle = nil
}
return UIImage(named: "arrow_down", in: bundle, compatibleWith: nil)
}()
}
| mit | 02962c597f42768ce2cf905ac3e098d1 | 40.944444 | 162 | 0.657616 | 4.902597 | false | false | false | false |
Clipy/Magnet | Lib/Magnet/HotKeyCenter.swift | 1 | 6368 | //
// HotKeyCenter.swift
//
// Magnet
// GitHub: https://github.com/clipy
// HP: https://clipy-app.com
//
// Copyright © 2015-2020 Clipy Project.
//
import Cocoa
import Carbon
public final class HotKeyCenter {
// MARK: - Properties
public static let shared = HotKeyCenter()
private var hotKeys = [String: HotKey]()
private var hotKeyCount: UInt32 = 0
private let modifierEventHandler: ModifierEventHandler
private let notificationCenter: NotificationCenter
// MARK: - Initialize
init(modifierEventHandler: ModifierEventHandler = .init(), notificationCenter: NotificationCenter = .default) {
self.modifierEventHandler = modifierEventHandler
self.notificationCenter = notificationCenter
installHotKeyPressedEventHandler()
installModifiersChangedEventHandlerIfNeeded()
observeApplicationTerminate()
}
deinit {
notificationCenter.removeObserver(self)
}
}
// MARK: - Register & Unregister
public extension HotKeyCenter {
@discardableResult
func register(with hotKey: HotKey) -> Bool {
guard !hotKeys.keys.contains(hotKey.identifier) else { return false }
guard !hotKeys.values.contains(hotKey) else { return false }
hotKeys[hotKey.identifier] = hotKey
guard !hotKey.keyCombo.doubledModifiers else { return true }
/*
* Normal macOS shortcut
*
* Discussion:
* When registering a hotkey, a KeyCode that conforms to the
* keyboard layout at the time of registration is registered.
* To register a `v` on the QWERTY keyboard, `9` is registered,
* and to register a `v` on the Dvorak keyboard, `47` is registered.
* Therefore, if you change the keyboard layout after registering
* a hot key, the hot key is not assigned to the correct key.
* To solve this problem, you need to re-register the hotkeys
* when you change the layout, but it's not supported by the
* Apple Genuine app either, so it's not supported now.
*/
let hotKeyId = EventHotKeyID(signature: UTGetOSTypeFromString("Magnet" as CFString), id: hotKeyCount)
var carbonHotKey: EventHotKeyRef?
let error = RegisterEventHotKey(UInt32(hotKey.keyCombo.currentKeyCode),
UInt32(hotKey.keyCombo.modifiers),
hotKeyId,
GetEventDispatcherTarget(),
0,
&carbonHotKey)
guard error == noErr else {
unregister(with: hotKey)
return false
}
hotKey.hotKeyId = hotKeyId.id
hotKey.hotKeyRef = carbonHotKey
hotKeyCount += 1
return true
}
func unregister(with hotKey: HotKey) {
if let carbonHotKey = hotKey.hotKeyRef {
UnregisterEventHotKey(carbonHotKey)
}
hotKeys.removeValue(forKey: hotKey.identifier)
hotKey.hotKeyId = nil
hotKey.hotKeyRef = nil
}
@discardableResult
func unregisterHotKey(with identifier: String) -> Bool {
guard let hotKey = hotKeys[identifier] else { return false }
unregister(with: hotKey)
return true
}
func unregisterAll() {
hotKeys.forEach { unregister(with: $1) }
}
}
// MARK: - Terminate
extension HotKeyCenter {
private func observeApplicationTerminate() {
notificationCenter.addObserver(self,
selector: #selector(HotKeyCenter.applicationWillTerminate),
name: NSApplication.willTerminateNotification,
object: nil)
}
@objc func applicationWillTerminate() {
unregisterAll()
}
}
// MARK: - HotKey Events
private extension HotKeyCenter {
func installHotKeyPressedEventHandler() {
var pressedEventType = EventTypeSpec()
pressedEventType.eventClass = OSType(kEventClassKeyboard)
pressedEventType.eventKind = OSType(kEventHotKeyPressed)
InstallEventHandler(GetEventDispatcherTarget(), { _, inEvent, _ -> OSStatus in
return HotKeyCenter.shared.sendPressedKeyboardEvent(inEvent!)
}, 1, &pressedEventType, nil, nil)
}
func sendPressedKeyboardEvent(_ event: EventRef) -> OSStatus {
assert(Int(GetEventClass(event)) == kEventClassKeyboard, "Unknown event class")
var hotKeyId = EventHotKeyID()
let error = GetEventParameter(event,
EventParamName(kEventParamDirectObject),
EventParamName(typeEventHotKeyID),
nil,
MemoryLayout<EventHotKeyID>.size,
nil,
&hotKeyId)
guard error == noErr else { return error }
assert(hotKeyId.signature == UTGetOSTypeFromString("Magnet" as CFString), "Invalid hot key id")
let hotKey = hotKeys.values.first(where: { $0.hotKeyId == hotKeyId.id })
switch GetEventKind(event) {
case EventParamName(kEventHotKeyPressed):
hotKey?.invoke()
default:
assert(false, "Unknown event kind")
}
return noErr
}
}
// MARK: - Double Tap Modifier Event
private extension HotKeyCenter {
func installModifiersChangedEventHandlerIfNeeded() {
NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { [weak self] event in
self?.modifierEventHandler.handleModifiersEvent(with: event.modifierFlags, timestamp: event.timestamp)
}
NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event -> NSEvent? in
self?.modifierEventHandler.handleModifiersEvent(with: event.modifierFlags, timestamp: event.timestamp)
return event
}
modifierEventHandler.doubleTapped = { [weak self] tappedModifierFlags in
self?.hotKeys.values
.filter { $0.keyCombo.doubledModifiers }
.filter { $0.keyCombo.modifiers == tappedModifierFlags.carbonModifiers() }
.forEach { $0.invoke() }
}
}
}
| mit | 9e75c079530e29475bcdc2fcd584600b | 36.452941 | 115 | 0.611277 | 5.189079 | false | false | false | false |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/classes/Home/Model/ZXStatusFrame.swift | 1 | 10155 | //
// ZXStatusFrame.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/15.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ZXStatusFrame: NSObject {
// 微博数据模型
var status : ZXStatus? {
// 根据数据计算子控件的frame
didSet {
// 计算顶部控件的frame
setupTopViewFrame();
// 计算底部工具条的frame
setupToolbarFrame();
// 计算cell的高度
cellHeight = CGRectGetMaxY(toolbarF!);
}
};
// 顶部的view的frame
var topViewF : CGRect?;
// 原创微博的view的frame
var originalViewF : CGRect?;
// 头像的父视图
var iconSupViewF : CGRect?;
// 头像的frame
var iconViewF : CGRect?;
// 会员图标的frame
var vipViewF : CGRect?;
var vRankViewF : CGRect?
// 昵称的frame
var nameLabelF : CGRect?;
// 内容的frame
var contentLabelF : CGRect?;
// 配图的frame
var photosViewF : CGRect?;
// 底部的工具条
var toolbarF : CGRect?;
// 被转发微博View的frame
var repostedViewF : CGRect?;
// 被转发微博昵称的frame
var repostedNameLabelF : CGRect?;
// 被转发微博内容的frame
var repostedContentLabelF : CGRect?;
// 被转发微博配图的frame
var repostedPhotosViewF : CGRect?;
// cell的高度
var cellHeight : CGFloat?;
// 设置顶部View的frame
func setupTopViewFrame() -> Void {
// 计算原创微博的frame
setupOriginalViewFrame();
// 计算转发微博的frame
setupRepostedViewFrame();
// 计算顶部控件的frame
let repostedStatus = self.status?.retweeted_status;
var topViewH = CGFloat(0);
// 有转发微博
if (repostedStatus != nil) {
topViewH = CGRectGetMaxY(repostedViewF!);
}
// 无转发微博
else {
topViewH = CGRectGetMaxY(originalViewF!);
}
let topViewX = CGFloat(0);
let topViewY = kCellMargin;
let topViewW = kScreenWidth;
topViewF = CGRectMake(topViewX, topViewY, topViewW, topViewH);
}
// 计算底部工具条的frame
func setupToolbarFrame() -> Void {
let toolbarX = CGFloat(0);
let toolbarY = CGRectGetMaxY(topViewF!);
let toolbarW = kScreenWidth;
let toolbarH = CGFloat(35);
toolbarF = CGRectMake(toolbarX, toolbarY, toolbarW, toolbarH);
}
// 计算原创微博的frame
func setupOriginalViewFrame() -> Void {
// 头像父视图
let iconSupViewX = kCellPadding;
let iconSupViewY = kCellPadding;
let iconSupViewW = CGFloat(35);
let iconSupViewH = CGFloat(35);
iconSupViewF = CGRectMake(iconSupViewX, iconSupViewY, iconSupViewW, iconSupViewH);
// 头像
let iconViewX = CGFloat(0);
let iconViewY = CGFloat(0);
let iconViewW = CGFloat(35);
let iconViewH = CGFloat(35);
iconViewF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);
// 会员等级图标
let image = UIImage(named: "avatar_vip");
let vRankViewX = iconSupViewW - (image?.size.width)! * 0.8;
let vRankViewY = iconSupViewH - (image?.size.height)! * 0.8;
let vRankViewW = (image?.size.width)! * 0.8;
let vRankViewH = (image?.size.height)! * 0.8;
vRankViewF = CGRectMake(vRankViewX, vRankViewY, vRankViewW, vRankViewH);
// 昵称
let nameLabelX = CGRectGetMaxX(iconSupViewF!) + kCellPadding;
let nameLabelY = iconSupViewY;
var attrs = [String : AnyObject]();
attrs[NSFontAttributeName] = UIFont.systemFontOfSize(16);
let nameLabelSize = ((status?.user?.name)! as NSString).sizeWithAttributes(attrs);
nameLabelF = CGRectMake(nameLabelX, nameLabelY, nameLabelSize.width, nameLabelSize.height);
// 会员图标
let vipViewX = CGRectGetMaxX(nameLabelF!) + kCellPadding;
let vipViewY = nameLabelY;
let vipViewW = CGFloat(14);
let vipViewH = nameLabelSize.height;
vipViewF = CGRectMake(vipViewX, vipViewY, vipViewW, vipViewH);
// 正文内容
let contentLabelX = iconSupViewX;
let contentLabelY = CGRectGetMaxY(iconSupViewF!) + kCellPadding;
let contentLabelMaxW = kScreenWidth - 2 * kCellPadding;
let contentLabelMaxSize = CGSizeMake(contentLabelMaxW, CGFloat(MAXFLOAT));
var contentLabelAttrs = [String : AnyObject]();
contentLabelAttrs[NSFontAttributeName] = UIFont.systemFontOfSize(16.0);
let contentLabelRect = ((status?.text!)! as NSString).boundingRectWithSize(contentLabelMaxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: contentLabelAttrs, context: nil);
contentLabelF = CGRectMake(contentLabelX, contentLabelY, contentLabelRect.width, contentLabelRect.height);
// 配图
let photosCount = status?.pic_urls?.count;
var originalViewH = CGFloat(0);
// 有配图
if photosCount != nil {
let photosViewX = contentLabelX;
let photosViewY = CGRectGetMaxY(contentLabelF!) + kCellPadding;
// 计算配图的尺寸
let photosViewSize = photosSizeWithCount(photosCount);
photosViewF = CGRectMake(photosViewX, photosViewY, photosViewSize!.width, photosViewSize!.height);
originalViewH = CGRectGetMaxY(photosViewF!) + kCellPadding;
}
// 没有配图
else {
originalViewH = CGRectGetMaxY(contentLabelF!) + kCellPadding;
}
// 原创微博的整体
let originalViewX = CGFloat(0);
let originalViewY = CGFloat(0);
let originalViewW = kScreenWidth;
originalViewF = CGRectMake(originalViewX, originalViewY, originalViewW, originalViewH);
}
// 根据配图的个数计算配图的frame
func photosSizeWithCount(photosCount : NSInteger?) -> CGSize? {
// 一行最多的列数
let maxCols = photosMaxCols(photosCount);
// 列数
var cols = 0;
if photosCount >= maxCols {
cols = maxCols!;
} else {
cols = photosCount!;
}
// 行数
var rows = 0;
rows = photosCount! / maxCols!;
if photosCount! % maxCols! != 0 {
rows = rows + 1;
}
// 配图的宽度取决于图片的列数
let photosViewW = CGFloat(cols) * kPhotoW + (CGFloat(cols) - 1) * kPhotoMargin;
let photosViewH = CGFloat(rows) * kPhotoH + CGFloat(rows - 1) * kPhotoMargin;
return CGSizeMake(photosViewW, photosViewH);
}
// 计算转发微博的frame
func setupRepostedViewFrame() -> Void {
let repostedStatus = status?.retweeted_status;
if (repostedStatus == nil) {
return;
}
// 昵称
let repostedNameLabelX = kCellPadding;
let repostedNameLabelY = kCellPadding;
let name = String(format: "@%@" , (repostedStatus?.user?.name)!);
var repostedNameLabelAttrs = [String : AnyObject]();
repostedNameLabelAttrs[NSFontAttributeName] = UIFont.systemFontOfSize(15);
let repostedNameLabelSize = (name as NSString).sizeWithAttributes(repostedNameLabelAttrs);
repostedNameLabelF = CGRectMake(repostedNameLabelX, repostedNameLabelY, repostedNameLabelSize.width, repostedNameLabelSize.height);
// 正文内容
let repostedContentLabelX = repostedNameLabelX;
let repostedContentLabelY = CGRectGetMaxY(repostedNameLabelF!) + kCellPadding;
let repostedContentLabelMaxW = kScreenWidth - 2 * kCellPadding;
let repostedContentLabelMaxSize = CGSizeMake(repostedContentLabelMaxW, CGFloat(MAXFLOAT));
var repostedContentLabelAttrs = [String : AnyObject]();
repostedContentLabelAttrs[NSFontAttributeName] = kRepostedContentLabelFont;
print(repostedStatus);
let repostedContentLabelRect = ((repostedStatus?.text)! as NSString).boundingRectWithSize(repostedContentLabelMaxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: repostedContentLabelAttrs, context: nil);
repostedContentLabelF = CGRectMake(repostedContentLabelX, repostedContentLabelY, repostedContentLabelRect.width, repostedContentLabelRect.height);
// 配图
let photosCount = status?.retweeted_status?.pic_urls?.count;
var repostedViewH = CGFloat(0);
if (photosCount != nil) {
// 有配图
let repostedPhotosViewX = repostedContentLabelX;
let repostedPhotosViewY = CGRectGetMaxY(repostedContentLabelF!) + kCellPadding;
// 计算配图的尺寸
let repostedPhotosViewSize = photosSizeWithCount(photosCount);
repostedPhotosViewF = CGRectMake(repostedPhotosViewX, repostedPhotosViewY, (repostedPhotosViewSize?.width)!, (repostedPhotosViewSize?.height)!);
repostedViewH = CGRectGetMaxY(repostedPhotosViewF!) + kCellPadding;
}
// 没有配图
else {
repostedViewH = CGRectGetMaxY(repostedContentLabelF!) + kCellPadding;
}
// 整体
let repostedViewX = CGFloat(0);
let repostedViewY = CGRectGetMaxY(originalViewF!);
let repostedViewW = kScreenWidth;
repostedViewF = CGRectMake(repostedViewX, repostedViewY, repostedViewW, repostedViewH);
}
override init() {
super.init();
}
}
| apache-2.0 | 5bc68c704d91b5c79b4c1de468056f1d | 32.594406 | 236 | 0.60179 | 5.127001 | false | false | false | false |
vikas4goyal/IAPHelper | Example/Pods/SwiftyStoreKit/SwiftyStoreKit/PaymentQueueController.swift | 1 | 8336 | //
// PaymentQueueController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto ([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 StoreKit
protocol TransactionController {
/**
* - param transactions: transactions to process
* - param paymentQueue: payment queue for finishing transactions
* - return: array of unhandled transactions
*/
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction]
}
public enum TransactionResult {
case purchased(product: Product)
case restored(product: Product)
case failed(error: SKError)
}
public protocol PaymentQueue: class {
func add(_ observer: SKPaymentTransactionObserver)
func remove(_ observer: SKPaymentTransactionObserver)
func add(_ payment: SKPayment)
func restoreCompletedTransactions(withApplicationUsername username: String?)
func finishTransaction(_ transaction: SKPaymentTransaction)
}
extension SKPaymentQueue: PaymentQueue { }
extension SKPaymentTransaction {
open override var debugDescription: String {
let transactionId = transactionIdentifier ?? "null"
return "productId: \(payment.productIdentifier), transactionId: \(transactionId), state: \(transactionState), date: \(String(describing: transactionDate))"
}
}
extension SKPaymentTransactionState: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .purchasing: return "purchasing"
case .purchased: return "purchased"
case .failed: return "failed"
case .restored: return "restored"
case .deferred: return "deferred"
}
}
}
class PaymentQueueController: NSObject, SKPaymentTransactionObserver {
private let paymentsController: PaymentsController
private let restorePurchasesController: RestorePurchasesController
private let completeTransactionsController: CompleteTransactionsController
unowned let paymentQueue: PaymentQueue
deinit {
paymentQueue.remove(self)
}
init(paymentQueue: PaymentQueue = SKPaymentQueue.default(),
paymentsController: PaymentsController = PaymentsController(),
restorePurchasesController: RestorePurchasesController = RestorePurchasesController(),
completeTransactionsController: CompleteTransactionsController = CompleteTransactionsController()) {
self.paymentQueue = paymentQueue
self.paymentsController = paymentsController
self.restorePurchasesController = restorePurchasesController
self.completeTransactionsController = completeTransactionsController
super.init()
paymentQueue.add(self)
}
func startPayment(_ payment: Payment) {
let skPayment = SKMutablePayment(product: payment.product)
skPayment.applicationUsername = payment.applicationUsername
paymentQueue.add(skPayment)
paymentsController.append(payment)
}
func restorePurchases(_ restorePurchases: RestorePurchases) {
if restorePurchasesController.restorePurchases != nil {
return
}
paymentQueue.restoreCompletedTransactions(withApplicationUsername: restorePurchases.applicationUsername)
restorePurchasesController.restorePurchases = restorePurchases
}
func completeTransactions(_ completeTransactions: CompleteTransactions) {
guard completeTransactionsController.completeTransactions == nil else {
print("SwiftyStoreKit.completeTransactions() should only be called once when the app launches. Ignoring this call")
return
}
completeTransactionsController.completeTransactions = completeTransactions
}
func finishTransaction(_ transaction: PaymentTransaction) {
guard let skTransaction = transaction as? SKPaymentTransaction else {
print("Object is not a SKPaymentTransaction: \(transaction)")
return
}
paymentQueue.finishTransaction(skTransaction)
}
// MARK: SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
/*
* Some notes about how requests are processed by SKPaymentQueue:
*
* SKPaymentQueue is used to queue payments or restore purchases requests.
* Payments are processed serially and in-order and require user interaction.
* Restore purchases requests don't require user interaction and can jump ahead of the queue.
* SKPaymentQueue rejects multiple restore purchases calls.
* Having one payment queue observer for each request causes extra processing
* Failed transactions only ever belong to queued payment requests.
* restoreCompletedTransactionsFailedWithError is always called when a restore purchases request fails.
* paymentQueueRestoreCompletedTransactionsFinished is always called following 0 or more update transactions when a restore purchases request succeeds.
* A complete transactions handler is require to catch any transactions that are updated when the app is not running.
* Registering a complete transactions handler when the app launches ensures that any pending transactions can be cleared.
* If a complete transactions handler is missing, pending transactions can be mis-attributed to any new incoming payments or restore purchases.
*
* The order in which transaction updates are processed is:
* 1. payments (transactionState: .purchased and .failed for matching product identifiers)
* 2. restore purchases (transactionState: .restored, or restoreCompletedTransactionsFailedWithError, or paymentQueueRestoreCompletedTransactionsFinished)
* 3. complete transactions (transactionState: .purchased, .failed, .restored, .deferred)
* Any transactions where state == .purchasing are ignored.
*/
var unhandledTransactions = paymentsController.processTransactions(transactions, on: paymentQueue)
unhandledTransactions = restorePurchasesController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = completeTransactionsController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = unhandledTransactions.filter { $0.transactionState != .purchasing }
if unhandledTransactions.count > 0 {
let strings = unhandledTransactions.map { $0.debugDescription }.joined(separator: "\n")
print("unhandledTransactions:\n\(strings)")
}
}
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
restorePurchasesController.restoreCompletedTransactionsFinished()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
}
}
| mit | 5fbcfec73776e153fd2e9c9f321097e4 | 40.68 | 163 | 0.742682 | 6.124908 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/User/UserInfoRequest.swift | 1 | 929 | //
// UserInfoRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/19/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
// DOCS: https://rocket.chat/docs/developer-guides/rest-api/users/info
import SwiftyJSON
final class UserInfoRequest: APIRequest {
typealias APIResourceType = UserInfoResource
let path = "/api/v1/users.info"
let query: String?
let userId: String?
let username: String?
init(userId: String) {
self.userId = userId
self.username = nil
self.query = "userId=\(userId)"
}
init(username: String) {
self.username = username
self.userId = nil
self.query = "username=\(username)"
}
}
final class UserInfoResource: APIResource {
var user: User? {
guard let raw = raw?["user"] else { return nil }
let user = User()
user.map(raw, realm: nil)
return user
}
}
| mit | bfc8262b72b64f67a5cc3f760782fec8 | 21.095238 | 71 | 0.618534 | 3.787755 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Conference/Data/TimeZoneData.swift | 1 | 1725 | /*
* Copyright (c) 2010-2021 Belledonne Communications SARL.
*
* This file is part of linphone-android
* (see https://www.linphone.org).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import linphonesw
struct TimeZoneData : Comparable {
let timeZone: TimeZone
static func == (lhs: TimeZoneData, rhs: TimeZoneData) -> Bool {
return lhs.timeZone.identifier == rhs.timeZone.identifier
}
static func < (lhs: TimeZoneData, rhs: TimeZoneData) -> Bool {
return lhs.timeZone.secondsFromGMT() < rhs.timeZone.secondsFromGMT()
}
func descWithOffset() -> String {
return "\(timeZone.identifier) - GMT\(timeZone.offsetInHours())"
}
}
extension TimeZone {
func offsetFromUTC() -> String
{
let localTimeZoneFormatter = DateFormatter()
localTimeZoneFormatter.timeZone = self
localTimeZoneFormatter.dateFormat = "Z"
return localTimeZoneFormatter.string(from: Date())
}
func offsetInHours() -> String
{
let hours = secondsFromGMT()/3600
let minutes = abs(secondsFromGMT()/60) % 60
let tz_hr = String(format: "%+.2d:%.2d", hours, minutes) // "+hh:mm"
return tz_hr
}
}
| gpl-3.0 | c429f18b03b10ea850853c3f9bdd0276 | 27.75 | 71 | 0.721159 | 3.782895 | false | false | false | false |
ben-ng/swift | test/Sema/enum_equatable_hashable.swift | 5 | 3300 | // RUN: rm -rf %t && mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift
enum Foo {
case A, B
}
if Foo.A == .B { }
var aHash: Int = Foo.A.hashValue
enum Generic<T> {
case A, B
static func method() -> Int {
// Test synthesis of == without any member lookup being done
if A == B { }
return Generic.A.hashValue
}
}
if Generic<Foo>.A == .B { }
var gaHash: Int = Generic<Foo>.A.hashValue
func localEnum() -> Bool {
enum Local {
case A, B
}
return Local.A == .B
}
enum CustomHashable {
case A, B
var hashValue: Int { return 0 }
}
func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note{{non-matching type}}
return true
}
if CustomHashable.A == .B { }
var custHash: Int = CustomHashable.A.hashValue
// We still synthesize conforming overloads of '==' and 'hashValue' if
// explicit definitions don't satisfy the protocol requirements. Probably
// not what we actually want.
enum InvalidCustomHashable {
case A, B
var hashValue: String { return "" } // expected-note{{previously declared here}}
}
func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note{{non-matching type}}
return ""
}
if InvalidCustomHashable.A == .B { }
var s: String = InvalidCustomHashable.A == .B
s = InvalidCustomHashable.A.hashValue
var i: Int = InvalidCustomHashable.A.hashValue
// Check use of an enum's synthesized members before the enum is actually declared.
struct UseEnumBeforeDeclaration {
let eqValue = EnumToUseBeforeDeclaration.A == .A
let hashValue = EnumToUseBeforeDeclaration.A.hashValue
}
enum EnumToUseBeforeDeclaration {
case A
}
// Check enums from another file in the same module.
if FromOtherFile.A == .A {}
let _: Int = FromOtherFile.A.hashValue
func getFromOtherFile() -> AlsoFromOtherFile { return .A }
if .A == getFromOtherFile() {}
// FIXME: This should work.
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A }
func overloadFromOtherFile() -> Bool { return false }
if .A == overloadFromOtherFile() {}
// Complex enums are not implicitly Equatable or Hashable.
enum Complex {
case A(Int)
case B
}
if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }}
// rdar://19773050
private enum Bar<T> {
case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}}
mutating func value() -> T {
switch self {
// FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point
case E(let x):
return x.value
}
}
}
// Equatable extension -- rdar://20981254
enum Instrument {
case Piano
case Violin
case Guitar
}
extension Instrument : Equatable {}
// Explicit conformance should work too
public enum Medicine {
case Antibiotic
case Antihistamine
}
extension Medicine : Equatable {}
public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note{{non-matching type}}
return true
}
// No explicit conformance and cannot be derived
extension Complex : Hashable {} // expected-error 2 {{does not conform}}
| apache-2.0 | a0f383de09a4af725b94e918107714b7 | 24.78125 | 123 | 0.692424 | 3.788749 | false | false | false | false |
SebastianBoldt/Jelly | Jelly/Classes/public/Models/Configuration/Presentation/PresentationTiming.swift | 1 | 535 | import UIKit
public struct PresentationTiming: PresentationTimingProtocol {
public var duration: Duration
public var presentationCurve: UIView.AnimationCurve
public var dismissCurve: UIView.AnimationCurve
public init(duration: Duration = .medium,
presentationCurve: UIView.AnimationCurve = .linear,
dismissCurve: UIView.AnimationCurve = .linear) {
self.duration = duration
self.presentationCurve = presentationCurve
self.dismissCurve = dismissCurve
}
}
| mit | 930078ab7ee4cbfed3eb5d34090a01f1 | 34.666667 | 67 | 0.706542 | 5.459184 | false | false | false | false |
rlasante/Swift-Trip-Tracker | LocationTracker/ViewController.swift | 1 | 1776 | //
// ViewController.swift
// LocationTracker
//
// Created by Ryan LaSante on 11/1/15.
// Copyright © 2015 rlasante. All rights reserved.
//
import UIKit
import ReactiveCocoa
class ViewController: UIViewController {
@IBOutlet weak var startButton: UIButton?
@IBOutlet weak var stopButton: UIButton?
@IBOutlet weak var speedLabel: UILabel?
var tracking = false
override func viewDidLoad() {
super.viewDidLoad()
listenForSpeedChanges()
listenForTripCompleted()
}
private func listenForSpeedChanges() {
TripManager.sharedInstance.currentSpeedSignal()
.map { (metersPerSecond) -> Double in
metersPerSecond * 2.23694
}.observeNext { [weak self] (speed) -> () in
self?.speedLabel?.text = "\(Int(speed)) MPH"
}
}
private func listenForTripCompleted() {
TripManager.sharedInstance.completedTripSignal().observeNext { [weak self] (trip) -> () in
self?.performSegueWithIdentifier("mapSegue", sender: trip)
self?.stopButton?.hidden = true
self?.speedLabel?.hidden = true
self?.speedLabel?.text = ""
self?.startButton?.hidden = false
}
}
@IBAction func startTracking(sender: UIButton) {
TripManager.sharedInstance.startTracking()
startButton?.hidden = true
stopButton?.hidden = false
speedLabel?.hidden = false
}
@IBAction func stopTracking(sender: UIButton) {
TripManager.sharedInstance.stopTracking()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "mapSegue" {
let mapViewController = segue.destinationViewController as! MapViewController
mapViewController.trip = sender as! Trip
}
}
@IBAction func doneWithMapSegue(segue: UIStoryboardSegue) {
}
}
| mit | 497e64dff7cdca8d95ccc2485a824f0a | 25.893939 | 94 | 0.696338 | 4.622396 | false | false | false | false |
KoCMoHaBTa/MHAppKit | MHAppKit/Extensions/UIKit/UIView/UIView+Snapshot.swift | 1 | 2471 | //
// UIView+Snapshot.swift
// MHAppKit
//
// Created by Milen Halachev on 27.11.17.
// Copyright © 2017 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import Foundation
import UIKit
extension UIView {
public enum SnapshotTechnique {
case layerRendering
case drawHierarchy
@available(iOS 10.0, *)
case graphicsImageRenderer
case custom((UIView) -> UIImage?)
}
public func snapshot(using technique: SnapshotTechnique = .layerRendering) -> UIImage? {
switch technique {
case .layerRendering:
return self.layer.snapshot()
case .drawHierarchy:
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
case .graphicsImageRenderer:
if #available(iOS 10.0, *), #available(tvOS 10.0, *) {
let rendererFormat = UIGraphicsImageRendererFormat.preferred()
rendererFormat.opaque = self.isOpaque
let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: rendererFormat)
let snapshotImage = renderer.image { _ in
self.drawHierarchy(in: CGRect(origin: .zero, size: self.bounds.size), afterScreenUpdates: true)
}
return snapshotImage
}
else {
return nil
}
case .custom(let block):
return block(self)
}
}
}
extension CALayer {
public func snapshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
if let context = UIGraphicsGetCurrentContext() {
self.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
return nil
}
}
#endif
| mit | 8470405c3c70660388947553a5f52fec | 28.058824 | 119 | 0.521862 | 6.113861 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Conversation/ConversationViewController.swift | 1 | 47866 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MobileCoreServices
import AddressBook
import AddressBookUI
import AVFoundation
//import AGEmojiKeyboard
final public class ConversationViewController:
AAConversationContentController,
UIDocumentMenuDelegate,
UIDocumentPickerDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
AALocationPickerControllerDelegate,
ABPeoplePickerNavigationControllerDelegate,
AAAudioRecorderDelegate,
AAConvActionSheetDelegate,
AAStickersKeyboardDelegate
//,
//AGEmojiKeyboardViewDataSource,
// AGEmojiKeyboardViewDelegate
{
// Data binder
fileprivate let binder = AABinder()
// Internal state
// Members for autocomplete
var filteredMembers = [ACMentionFilterResult]()
let content: ACPage!
var appStyle: ActorStyle { get { return ActorSDK.sharedActor().style } }
//
// Views
//
fileprivate let titleView: UILabel = UILabel()
open let subtitleView: UILabel = UILabel()
fileprivate let navigationView: UIView = UIView()
fileprivate let avatarView = AABarAvatarView()
fileprivate let backgroundView = UIImageView()
fileprivate var audioButton: UIButton = UIButton()
fileprivate var voiceRecorderView : AAVoiceRecorderView!
fileprivate let inputOverlay = UIView()
fileprivate let inputOverlayLabel = UILabel()
//
// Stickers
//
fileprivate var stickersView: AAStickersKeyboard!
open var stickersButton : UIButton!
fileprivate var stickersOpen = false
//fileprivate var emojiKeyboar: AGEmojiKeyboardView!
//
// Audio Recorder
//
open var audioRecorder: AAAudioRecorder!
//
// Mode
//
fileprivate var textMode:Bool!
fileprivate var micOn: Bool! = true
open var removeExcedentControllers = true
////////////////////////////////////////////////////////////
// MARK: - Init
////////////////////////////////////////////////////////////
required override public init(peer: ACPeer) {
// Data
self.content = ACAllEvents_Chat_viewWithACPeer_(peer)
// Create controller
super.init(peer: peer)
//
// Background
//
backgroundView.clipsToBounds = true
backgroundView.contentMode = .scaleAspectFill
backgroundView.backgroundColor = appStyle.chatBgColor
// Custom background if available
if let bg = Actor.getSelectedWallpaper(){
if bg != "default" {
if bg.startsWith("local:") {
backgroundView.image = UIImage.bundled(bg.skip(6))
} else {
let path = CocoaFiles.pathFromDescriptor(bg.skip(5))
backgroundView.image = UIImage(contentsOfFile:path)
}
}
}
view.insertSubview(backgroundView, at: 0)
//
// slk settings
//
self.bounces = false
self.isKeyboardPanningEnabled = true
self.registerPrefixes(forAutoCompletion: ["@"])
//
// Text Input
//
self.textInputbar.backgroundColor = appStyle.chatInputFieldBgColor
self.textInputbar.autoHideRightButton = false;
self.textInputbar.isTranslucent = false
//
// Text view
//
self.textView.placeholder = AALocalized("ChatPlaceholder")
self.textView.keyboardAppearance = ActorSDK.sharedActor().style.isDarkApp ? .dark : .light
//
// Overlay
//
self.inputOverlay.addSubview(inputOverlayLabel)
self.inputOverlayLabel.textAlignment = .center
self.inputOverlayLabel.font = UIFont.systemFont(ofSize: 18)
self.inputOverlayLabel.textColor = ActorSDK.sharedActor().style.vcTintColor
self.inputOverlay.viewDidTap = {
self.onOverlayTap()
}
//
// Add stickers button
//
self.stickersButton = UIButton(type: UIButtonType.system)
self.stickersButton.tintColor = UIColor.lightGray.withAlphaComponent(0.5)
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.stickersButton.addTarget(self, action: #selector(ConversationViewController.changeKeyboard), for: UIControlEvents.touchUpInside)
if(ActorSDK.sharedActor().delegate.showStickersButton()){
self.textInputbar.addSubview(stickersButton)
}
//
// Check text for set right button
//
let checkText = Actor.loadDraft(with: peer)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (checkText.isEmpty) {
self.textMode = false
self.rightButton.tintColor = appStyle.chatSendColor
self.rightButton.setImage(UIImage.tinted("aa_micbutton", color: appStyle.chatAttachColor), for: UIControlState())
self.rightButton.setTitle("", for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
} else {
self.textMode = true
self.stickersButton.isHidden = true
self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled)
self.rightButton.setImage(nil, for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
}
//
// Voice Recorder
//
self.audioRecorder = AAAudioRecorder()
self.audioRecorder.delegate = self
self.leftButton.setImage(UIImage.tinted("conv_attach", color: appStyle.chatAttachColor), for: UIControlState())
//
// Navigation Title
//
navigationView.frame = CGRect(x: 0, y: 0, width: 200, height: 44)
navigationView.autoresizingMask = UIViewAutoresizing.flexibleWidth
titleView.font = UIFont.mediumSystemFontOfSize(17)
titleView.adjustsFontSizeToFitWidth = false
titleView.textAlignment = NSTextAlignment.center
titleView.lineBreakMode = NSLineBreakMode.byTruncatingTail
titleView.autoresizingMask = UIViewAutoresizing.flexibleWidth
titleView.textColor = appStyle.navigationTitleColor
subtitleView.font = UIFont.systemFont(ofSize: 13)
subtitleView.adjustsFontSizeToFitWidth = true
subtitleView.textAlignment = NSTextAlignment.center
subtitleView.lineBreakMode = NSLineBreakMode.byTruncatingTail
subtitleView.autoresizingMask = UIViewAutoresizing.flexibleWidth
navigationView.addSubview(titleView)
navigationView.addSubview(subtitleView)
self.navigationItem.titleView = navigationView
//
// Navigation Avatar
//
avatarView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
avatarView.viewDidTap = onAvatarTap
let barItem = UIBarButtonItem(customView: avatarView)
let isBot: Bool
if (peer.isPrivate) {
isBot = Bool(Actor.getUserWithUid(peer.peerId).isBot())
} else {
isBot = false
}
if (ActorSDK.sharedActor().enableCalls && !isBot && peer.isPrivate) {
if ActorSDK.sharedActor().enableVideoCalls {
let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
callButtonView.viewDidTap = onCallTap
let callButtonItem = UIBarButtonItem(customView: callButtonView)
let videoCallButtonView = AACallButton(image: UIImage.bundled("ic_video_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
videoCallButtonView.viewDidTap = onVideoCallTap
let callVideoButtonItem = UIBarButtonItem(customView: videoCallButtonView)
self.navigationItem.rightBarButtonItems = [barItem, callVideoButtonItem, callButtonItem]
} else {
let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
callButtonView.viewDidTap = onCallTap
let callButtonItem = UIBarButtonItem(customView: callButtonView)
self.navigationItem.rightBarButtonItems = [barItem, callButtonItem]
}
} else {
self.navigationItem.rightBarButtonItems = [barItem]
}
}
required public init(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
self.voiceRecorderView = AAVoiceRecorderView(frame: CGRect(x: 0, y: 0, width: view.width - 30, height: 44))
self.voiceRecorderView.isHidden = true
self.voiceRecorderView.binedController = self
self.textInputbar.addSubview(self.voiceRecorderView)
self.inputOverlay.backgroundColor = UIColor.white
self.inputOverlay.isHidden = false
self.textInputbar.addSubview(self.inputOverlay)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
self.stickersView = AAStickersKeyboard(frame: frame)
self.stickersView.delegate = self
//emojiKeyboar.frame = frame
NotificationCenter.default.addObserver(
self,
selector: #selector(ConversationViewController.updateStickersStateOnCloseKeyboard),
name: NSNotification.Name.SLKKeyboardWillHide,
object: nil)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.stickersButton.frame = CGRect(x: self.view.frame.size.width-67, y: 12, width: 20, height: 20)
self.voiceRecorderView.frame = CGRect(x: 0, y: 0, width: view.width - 30, height: 44)
self.inputOverlay.frame = CGRect(x: 0, y: 0, width: view.width, height: 44)
self.inputOverlayLabel.frame = CGRect(x: 0, y: 0, width: view.width, height: 44)
}
////////////////////////////////////////////////////////////
// MARK: - Lifecycle
////////////////////////////////////////////////////////////
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Installing bindings
if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) {
let user = Actor.getUserWithUid(peer.peerId)
let nameModel = user.getNameModel()
let blockStatus = user.isBlockedModel().get().booleanValue()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!)
self.navigationView.sizeToFit()
})
binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(user.getNameModel().get(), id: Int(user.getId()), avatar: value)
})
binder.bind(Actor.getTypingWithUid(peer.peerId), valueModel2: user.getPresenceModel(), closure:{ (typing:JavaLangBoolean?, presence:ACUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = Actor.getFormatter().formatTyping()
self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor
} else {
if (user.isBot()) {
self.subtitleView.text = "bot"
self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor
} else {
let stateText = Actor.getFormatter().formatPresence(presence, with: user.getSex())
self.subtitleView.text = stateText;
let state = presence!.state.ordinal()
if (state == ACUserPresence_State.online().ordinal()) {
self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor
} else {
self.subtitleView.textColor = self.appStyle.userOfflineNavigationColor
}
}
}
})
self.inputOverlay.isHidden = true
} else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) {
let group = Actor.getGroupWithGid(peer.peerId)
let nameModel = group.getNameModel()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(group.getNameModel().get(), id: Int(group.getId()), avatar: value)
})
binder.bind(Actor.getGroupTyping(withGid: group.getId()), valueModel2: group.membersCount, valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, membersCount: JavaLangInteger?, onlineCount:JavaLangInteger?) -> () in
if (!group.isMemberModel().get().booleanValue()) {
self.subtitleView.text = AALocalized("ChatNoGroupAccess")
self.subtitleView.textColor = self.appStyle.navigationSubtitleColor
return
}
if (typingValue != nil && typingValue!.length() > 0) {
self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor
if (typingValue!.length() == 1) {
let uid = typingValue!.int(at: 0);
let user = Actor.getUserWithUid(uid)
self.subtitleView.text = Actor.getFormatter().formatTyping(withName: user.getNameModel().get())
} else {
self.subtitleView.text = Actor.getFormatter().formatTyping(withCount: typingValue!.length());
}
} else {
var membersString = Actor.getFormatter().formatGroupMembers(membersCount!.intValue())
self.subtitleView.textColor = self.appStyle.navigationSubtitleColor
if (onlineCount == nil || onlineCount!.intValue == 0) {
self.subtitleView.text = membersString;
} else {
membersString = membersString! + ", ";
let onlineString = Actor.getFormatter().formatGroupOnline(onlineCount!.intValue());
let attributedString = NSMutableAttributedString(string: (membersString! + onlineString!))
attributedString.addAttribute(NSForegroundColorAttributeName, value: self.appStyle.userOnlineNavigationColor, range: NSMakeRange(membersString!.length, onlineString!.length))
self.subtitleView.attributedText = attributedString
}
}
})
binder.bind(group.isMember, valueModel2: group.isCanWriteMessage, valueModel3: group.isCanJoin, closure: { (isMember: JavaLangBoolean?, canWriteMessage: JavaLangBoolean?, canJoin: JavaLangBoolean?) in
if canWriteMessage!.booleanValue() {
self.stickersButton.isHidden = false
self.inputOverlay.isHidden = true
} else {
if !isMember!.booleanValue() {
if canJoin!.booleanValue() {
self.inputOverlayLabel.text = AALocalized("ChatJoin")
} else {
self.inputOverlayLabel.text = AALocalized("ChatNoGroupAccess")
}
} else {
if Actor.isNotificationsEnabled(with: self.peer) {
self.inputOverlayLabel.text = AALocalized("ActionMute")
} else {
self.inputOverlayLabel.text = AALocalized("ActionUnmute")
}
}
self.stickersButton.isHidden = true
self.stopAudioRecording()
self.textInputbar.textView.text = ""
self.inputOverlay.isHidden = false
}
})
binder.bind(group.isDeleted) { (isDeleted: JavaLangBoolean?) in
if isDeleted!.booleanValue() {
self.alertUser(AALocalized("ChatDeleted")) {
self.execute(Actor.deleteChatCommand(with: self.peer), successBlock: { (r) in
self.navigateBack()
})
}
}
}
}
Actor.onConversationOpen(with: peer)
ActorSDK.sharedActor().trackPageVisible(content)
if textView.isFirstResponder == false {
textView.resignFirstResponder()
}
textView.text = Actor.loadDraft(with: peer)
}
open func onOverlayTap() {
if peer.isGroup {
let group = Actor.getGroupWithGid(peer.peerId)
if !group.isMember.get().booleanValue() {
if group.isCanJoin.get().booleanValue() {
executePromise(Actor.joinGroup(withGid: peer.peerId))
} else {
// DO NOTHING
}
} else if !group.isCanWriteMessage.get().booleanValue() {
if Actor.isNotificationsEnabled(with: peer) {
Actor.changeNotificationsEnabled(with: peer, withValue: false)
inputOverlayLabel.text = AALocalized("ActionUnmute")
} else {
Actor.changeNotificationsEnabled(with: peer, withValue: true)
inputOverlayLabel.text = AALocalized("ActionMute")
}
}
} else if peer.isPrivate {
}
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backgroundView.frame = view.bounds
titleView.frame = CGRect(x: 0, y: 4, width: (navigationView.frame.width - 0), height: 20)
subtitleView.frame = CGRect(x: 0, y: 22, width: (navigationView.frame.width - 0), height: 20)
stickersView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
//emojiKeyboar.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.removeExcedentControllers {
if navigationController!.viewControllers.count > 2 {
let firstController = navigationController!.viewControllers[0]
let currentController = navigationController!.viewControllers[navigationController!.viewControllers.count - 1]
navigationController!.setViewControllers([firstController, currentController], animated: false)
}
}
if !AADevice.isiPad {
AANavigationBadge.showBadge()
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Actor.onConversationClosed(with: peer)
ActorSDK.sharedActor().trackPageHidden(content)
if !AADevice.isiPad {
AANavigationBadge.hideBadge()
}
// Closing keyboard
self.textView.resignFirstResponder()
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Actor.saveDraft(with: peer, withDraft: textView.text)
// Releasing bindings
binder.unbindAll()
}
////////////////////////////////////////////////////////////
// MARK: - Chat avatar tap
////////////////////////////////////////////////////////////
func onAvatarTap() {
let id = Int(peer.peerId)
var controller: AAViewController!
if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) {
controller = ActorSDK.sharedActor().delegate.actorControllerForUser(id)
if controller == nil {
controller = AAUserViewController(uid: id)
}
} else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) {
controller = ActorSDK.sharedActor().delegate.actorControllerForGroup(id)
if controller == nil {
controller = AAGroupViewController(gid: id)
}
} else {
return
}
if (AADevice.isiPad) {
let navigation = AANavigationController()
navigation.viewControllers = [controller]
let popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.present(from: navigationItem.rightBarButtonItem!,
permittedArrowDirections: UIPopoverArrowDirection.up,
animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
func onCallTap() {
if (self.peer.isGroup) {
execute(ActorSDK.sharedActor().messenger.doCall(withGid: self.peer.peerId))
} else if (self.peer.isPrivate) {
execute(ActorSDK.sharedActor().messenger.doCall(withUid: self.peer.peerId))
}
}
func onVideoCallTap() {
if (self.peer.isPrivate) {
execute(ActorSDK.sharedActor().messenger.doVideoCall(withUid: self.peer.peerId))
}
}
////////////////////////////////////////////////////////////
// MARK: - Text bar actions
////////////////////////////////////////////////////////////
override open func textDidUpdate(_ animated: Bool) {
super.textDidUpdate(animated)
Actor.onTyping(with: peer)
checkTextInTextView()
}
func checkTextInTextView() {
let text = self.textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
self.rightButton.isEnabled = true
//change button's
if !text.isEmpty && textMode == false {
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
self.rebindRightButton()
self.stickersButton.isHidden = true
self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled)
self.rightButton.setImage(nil, for: UIControlState())
self.rightButton.layoutIfNeeded()
self.textInputbar.layoutIfNeeded()
self.textMode = true
} else if (text.isEmpty && textMode == true) {
self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
self.stickersButton.isHidden = false
self.rightButton.tintColor = appStyle.chatAttachColor
self.rightButton.setImage(UIImage.bundled("aa_micbutton"), for: UIControlState())
self.rightButton.setTitle("", for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
self.textInputbar.layoutIfNeeded()
self.textMode = false
}
}
////////////////////////////////////////////////////////////
// MARK: - Right/Left button pressed
////////////////////////////////////////////////////////////
override open func didPressRightButton(_ sender: Any!) {
if !self.textView.text.isEmpty {
Actor.sendMessage(withMentionsDetect: peer, withText: textView.text)
super.didPressRightButton(sender)
}
}
override open func didPressLeftButton(_ sender: Any!) {
super.didPressLeftButton(sender)
self.textInputbar.textView.resignFirstResponder()
self.rightButton.layoutIfNeeded()
if !ActorSDK.sharedActor().delegate.actorConversationCustomAttachMenu(self) {
let actionSheet = AAConvActionSheet()
actionSheet.addCustomButton("SendDocument")
actionSheet.addCustomButton("ShareLocation")
actionSheet.addCustomButton("ShareContact")
actionSheet.delegate = self
actionSheet.presentInController(self)
}
}
////////////////////////////////////////////////////////////
// MARK: - Completition
////////////////////////////////////////////////////////////
override open func didChangeAutoCompletionPrefix(_ prefix: String!, andWord word: String!) {
if self.peer.peerType.ordinal() == ACPeerType.group().ordinal() {
if prefix == "@" {
let oldCount = filteredMembers.count
filteredMembers.removeAll(keepingCapacity: true)
let res = Actor.findMentions(withGid: self.peer.peerId, withQuery: word)!
for index in 0..<res.size() {
filteredMembers.append(res.getWith(index) as! ACMentionFilterResult)
}
if oldCount == filteredMembers.count {
self.autoCompletionView.reloadData()
}
dispatchOnUi { () -> Void in
self.showAutoCompletionView(self.filteredMembers.count > 0)
}
return
}
}
dispatchOnUi { () -> Void in
self.showAutoCompletionView(false)
}
}
////////////////////////////////////////////////////////////
// MARK: - TableView for completition
////////////////////////////////////////////////////////////
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredMembers.count
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let res = AAAutoCompleteCell(style: UITableViewCellStyle.default, reuseIdentifier: "user_name")
res.bindData(filteredMembers[(indexPath as NSIndexPath).row], highlightWord: foundWord)
return res
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = filteredMembers[(indexPath as NSIndexPath).row]
var postfix = " "
if foundPrefixRange.location == 0 {
postfix = ": "
}
acceptAutoCompletion(with: user.mentionString + postfix, keepPrefix: !user.isNickname)
}
override open func heightForAutoCompletionView() -> CGFloat {
let cellHeight: CGFloat = 44.0;
return cellHeight * CGFloat(filteredMembers.count)
}
override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsets.zero
}
////////////////////////////////////////////////////////////
// MARK: - Picker
////////////////////////////////////////////////////////////
open func actionSheetPickedImages(_ images:[(Data,Bool)]) {
for (i,j) in images {
Actor.sendUIImage(i, peer: peer, animated:j)
}
}
open func actionSheetPickCamera() {
pickImage(.camera)
}
open func actionSheetPickGallery() {
pickImage(.photoLibrary)
}
open func actionSheetCustomButton(_ index: Int) {
if index == 0 {
pickDocument()
} else if index == 1 {
pickLocation()
} else if index == 2 {
pickContact()
}
}
open func pickContact() {
let pickerController = ABPeoplePickerNavigationController()
pickerController.peoplePickerDelegate = self
self.present(pickerController, animated: true, completion: nil)
}
open func pickLocation() {
let pickerController = AALocationPickerController()
pickerController.delegate = self
self.present(AANavigationController(rootViewController:pickerController), animated: true, completion: nil)
}
open func pickDocument() {
let documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll as [String], in: UIDocumentPickerMode.import)
documentPicker.view.backgroundColor = UIColor.clear
documentPicker.delegate = self
self.present(documentPicker, animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Document picking
////////////////////////////////////////////////////////////
open func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
self.present(documentPicker, animated: true, completion: nil)
}
open func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
// Loading path and file name
let path = url.path
let fileName = url.lastPathComponent
// Check if file valid or directory
var isDir : ObjCBool = false
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
// Not exists
return
}
// Destination file
let descriptor = "/tmp/\(UUID().uuidString)"
let destPath = CocoaFiles.pathFromDescriptor(descriptor)
if isDir.boolValue {
// Zipping contents and sending
execute(AATools.zipDirectoryCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/zip", withDescriptor: descriptor)
}
} else {
// Sending file itself
execute(AATools.copyFileCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor)
}
}
}
////////////////////////////////////////////////////////////
// MARK: - Image picking
////////////////////////////////////////////////////////////
func pickImage(_ source: UIImagePickerControllerSourceType) {
if(source == .camera && (AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.undetermined || AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.denied)){
AVAudioSession.sharedInstance().requestRecordPermission({_ in (Bool).self})
}
let pickerController = AAImagePickerController()
pickerController.sourceType = source
pickerController.mediaTypes = [kUTTypeImage as String,kUTTypeMovie as String]
pickerController.delegate = self
self.present(pickerController, animated: true, completion: nil)
}
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
picker.dismiss(animated: true, completion: nil)
let imageData = UIImageJPEGRepresentation(image, 0.8)
Actor.sendUIImage(imageData!, peer: peer, animated:false)
}
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let imageData = UIImageJPEGRepresentation(image, 0.8)
//TODO: Need implement assert fetching here to get images
Actor.sendUIImage(imageData!, peer: peer, animated:false)
} else {
Actor.sendVideo(info[UIImagePickerControllerMediaURL] as! URL, peer: peer)
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Location picking
////////////////////////////////////////////////////////////
open func locationPickerDidCancelled(_ controller: AALocationPickerController) {
controller.dismiss(animated: true, completion: nil)
}
open func locationPickerDidPicked(_ controller: AALocationPickerController, latitude: Double, longitude: Double) {
Actor.sendLocation(with: self.peer, withLongitude: JavaLangDouble(value: longitude), withLatitude: JavaLangDouble(value: latitude), withStreet: nil, withPlace: nil)
controller.dismiss(animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Contact picking
////////////////////////////////////////////////////////////
open func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
// Dismissing picker
peoplePicker.dismiss(animated: true, completion: nil)
// Names
let name = ABRecordCopyCompositeName(person)?.takeRetainedValue() as String?
// Avatar
var jAvatarImage: String? = nil
let hasAvatarImage = ABPersonHasImageData(person)
if (hasAvatarImage) {
let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue()
let image = UIImage(data: imgData as Data)?.resizeSquare(90, maxH: 90)
if (image != nil) {
let thumbData = UIImageJPEGRepresentation(image!, 0.55)
jAvatarImage = thumbData?.base64EncodedString(options: NSData.Base64EncodingOptions())
}
}
// Phones
let jPhones = JavaUtilArrayList()
let phoneNumbers: ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
let phoneCount = ABMultiValueGetCount(phoneNumbers)
for i in 0 ..< phoneCount {
let phone = (ABMultiValueCopyValueAtIndex(phoneNumbers, i).takeRetainedValue() as! String).trim()
jPhones?.add(withId: phone)
}
// Email
let jEmails = JavaUtilArrayList()
let emails: ABMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty).takeRetainedValue()
let emailsCount = ABMultiValueGetCount(emails)
for i in 0 ..< emailsCount {
let email = (ABMultiValueCopyValueAtIndex(emails, i).takeRetainedValue() as! String).trim()
if (email.length > 0) {
jEmails?.add(withId: email)
}
}
// Sending
Actor.sendContact(with: self.peer, withName: name!, withPhones: jPhones!, withEmails: jEmails!, withPhoto: jAvatarImage)
}
////////////////////////////////////////////////////////////
// MARK: -
// MARK: Audio recording statments + send
////////////////////////////////////////////////////////////
func onAudioRecordingStarted() {
print("onAudioRecordingStarted\n")
stopAudioRecording()
// stop voice player when start recording
if (self.voicePlayer?.playbackPosition() != 0.0) {
self.voicePlayer?.audioPlayerStopAndFinish()
}
audioRecorder.delegate = self
audioRecorder.start()
}
func onAudioRecordingFinished() {
print("onAudioRecordingFinished\n")
audioRecorder.finish { (path: String?, duration: TimeInterval) -> Void in
if (nil == path) {
print("onAudioRecordingFinished: empty path")
return
}
NSLog("onAudioRecordingFinished: %@ [%lfs]", path!, duration)
let range = path!.range(of: "/tmp", options: NSString.CompareOptions(), range: nil, locale: nil)
let descriptor = path!.substring(from: range!.lowerBound)
NSLog("Audio Recording file: \(descriptor)")
Actor.sendAudio(with: self.peer, withName: NSString.localizedStringWithFormat("%@.ogg", UUID().uuidString) as String,
withDuration: jint(duration*1000), withDescriptor: descriptor)
}
audioRecorder.cancel()
}
open func audioRecorderDidStartRecording() {
self.voiceRecorderView.recordingStarted()
}
func onAudioRecordingCancelled() {
stopAudioRecording()
}
func stopAudioRecording() {
if (audioRecorder != nil) {
audioRecorder.delegate = nil
audioRecorder.cancel()
}
}
func beginRecord(_ button:UIButton,event:UIEvent) {
self.voiceRecorderView.startAnimation()
self.voiceRecorderView.isHidden = false
self.stickersButton.isHidden = true
let touches : Set<UITouch> = event.touches(for: button)!
let touch = touches.first!
let location = touch.location(in: button)
self.voiceRecorderView.trackTouchPoint = location
self.voiceRecorderView.firstTouchPoint = location
self.onAudioRecordingStarted()
}
func mayCancelRecord(_ button:UIButton,event:UIEvent) {
let touches : Set<UITouch> = event.touches(for: button)!
let touch = touches.first!
let currentLocation = touch.location(in: button)
if (currentLocation.x < self.rightButton.frame.origin.x) {
if (self.voiceRecorderView.trackTouchPoint.x > currentLocation.x) {
self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: false)
} else {
self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: true)
}
}
self.voiceRecorderView.trackTouchPoint = currentLocation
if ((self.voiceRecorderView.firstTouchPoint.x - self.voiceRecorderView.trackTouchPoint.x) > 120) {
//cancel
self.voiceRecorderView.isHidden = true
self.stickersButton.isHidden = false
self.stopAudioRecording()
self.voiceRecorderView.recordingStoped()
button.cancelTracking(with: event)
closeRecorderAnimation()
}
}
func closeRecorderAnimation() {
let leftButtonFrame = self.leftButton.frame
leftButton.frame.origin.x = -100
let textViewFrame = self.textView.frame
textView.frame.origin.x = textView.frame.origin.x + 500
let stickerViewFrame = self.stickersButton.frame
stickersButton.frame.origin.x = self.stickersButton.frame.origin.x + 500
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.leftButton.frame = leftButtonFrame
self.textView.frame = textViewFrame
self.stickersButton.frame = stickerViewFrame
}, completion: { (complite) -> Void in
// animation complite
})
}
func finishRecord(_ button:UIButton,event:UIEvent) {
closeRecorderAnimation()
self.voiceRecorderView.isHidden = true
self.stickersButton.isHidden = false
self.onAudioRecordingFinished()
self.voiceRecorderView.recordingStoped()
}
////////////////////////////////////////////////////////////
// MARK: - Stickers actions
////////////////////////////////////////////////////////////
open func updateStickersStateOnCloseKeyboard() {
self.stickersOpen = false
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.textInputbar.textView.inputView = nil
}
open func changeKeyboard() {
if self.stickersOpen == false {
//self.stickersView.loadStickers()
self.textInputbar.textView.inputView = self.stickersView
//self.textInputbar.textView.inputView = self.emojiKeyboar
self.textInputbar.textView.inputView?.isOpaque = false
self.textInputbar.textView.inputView?.backgroundColor = UIColor.clear
self.textInputbar.textView.refreshFirstResponder()
self.textInputbar.textView.refreshInputViews()
self.textInputbar.textView.becomeFirstResponder()
self.stickersButton.setImage(UIImage.bundled("keyboard_button"), for: UIControlState())
self.stickersOpen = true
} else {
self.textInputbar.textView.inputView = nil
self.textInputbar.textView.refreshFirstResponder()
self.textInputbar.textView.refreshInputViews()
self.textInputbar.textView.becomeFirstResponder()
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.stickersOpen = false
}
self.textInputbar.layoutIfNeeded()
self.view.layoutIfNeeded()
}
open func stickerDidSelected(_ keyboard: AAStickersKeyboard, sticker: ACSticker) {
Actor.sendSticker(with: self.peer, with: sticker)
}
/*
public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage{
switch category {
case .recent:
return UIImage.bundled("ic_smiles_recent")!
case .face:
return UIImage.bundled("ic_smiles_smile")!
case .car:
return UIImage.bundled("ic_smiles_car")!
case .bell:
return UIImage.bundled("ic_smiles_bell")!
case .flower:
return UIImage.bundled("ic_smiles_flower")!
case .characters:
return UIImage.bundled("ic_smiles_grid")!
}
}
public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForNonSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage!{
switch category {
case .recent:
return UIImage.bundled("ic_smiles_recent")!
case .face:
return UIImage.bundled("ic_smiles_smile")!
case .car:
return UIImage.bundled("ic_smiles_car")!
case .bell:
return UIImage.bundled("ic_smiles_bell")!
case .flower:
return UIImage.bundled("ic_smiles_flower")!
case .characters:
return UIImage.bundled("ic_smiles_grid")!
}
}
public func backSpaceButtonImage(for emojiKeyboardView: AGEmojiKeyboardView!) -> UIImage!{
return UIImage.bundled("ic_smiles_backspace")!
}
public func emojiKeyBoardView(_ emojiKeyBoardView: AGEmojiKeyboardView!, didUseEmoji emoji: String!){
self.textView.text = self.textView.text.appending(emoji)
}
public func emojiKeyBoardViewDidPressBackSpace(_ emojiKeyBoardView: AGEmojiKeyboardView!){
self.textView.deleteBackward()
}
*/
}
class AABarAvatarView : AAAvatarView {
// override init(frameSize: Int, type: AAAvatarType) {
// super.init(frameSize: frameSize, type: type)
// }
//
// required init(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
override var alignmentRectInsets : UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)
}
}
class AACallButton: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var alignmentRectInsets : UIEdgeInsets {
return UIEdgeInsets(top: 0, left: -2, bottom: 0, right: 0)
}
}
| agpl-3.0 | 0e47913d62b594aedea3d3dbdaacb738 | 39.32519 | 250 | 0.585614 | 5.692912 | false | false | false | false |
pavelpark/RoundMedia | roundMedia/roundMedia/SignInViewController.swift | 1 | 3704 | //
// ViewController.swift
// roundMedia
//
// Created by Pavel Parkhomey on 7/11/17.
// Copyright © 2017 Pavel Parkhomey. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import SwiftKeychainWrapper
class SignInViewController: UIViewController {
@IBOutlet weak var emailFeild: CleanText!
@IBOutlet weak var passwordFeild: CleanText!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: KEY_UID){
print("------: ID found in keychain")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
@IBAction func facebookButtonTapped(_ sender: AnyObject) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil {
print("------: Unable to authenticate with Facebook - \(String(describing: error))")
} else if result?.isCancelled == true {
print("------: User cancelled Facebook authentication")
} else {
print("------: Successfully authenticated with Facebook")
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.firebaseAuth(credential)
}
}
}
func firebaseAuth(_ credential: AuthCredential) {
Auth.auth().signIn(with: credential) { (user, error) in
if error != nil {
print("------: Unable to authenticate with Firebase")
} else {
print("------: Susseccfully authenticated with Firebase")
if user != nil {
let userData = ["provider": credential.provider]
self.completeWithSignIn(id: (user?.uid)!, userData: userData)
}
}
}
}
@IBAction func emailSignInTapped(_ sender: AnyObject) {
if let email = emailFeild.text, let password = passwordFeild.text {
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
print("-----: Email user authenticated with Firebase")
let userData = ["provider": user?.providerID]
self.completeWithSignIn(id: (user?.uid)!, userData: userData as! Dictionary<String, String>)
} else {
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print("------: Unable to authenticate with Firebase using email")
} else {
print("------: Successfully authenticated with Firebase")
if let user = user {
let userData = ["provider": user.providerID]
self.completeWithSignIn(id: user.uid, userData: userData)
}
}
})
}
})
}
}
func completeWithSignIn(id: String, userData: Dictionary<String, String>) {
DataService.ds.createFirbaseDBUser(uid: id, userData: userData)
let keychainResult = KeychainWrapper.standard.set(id , forKey: "key uid")
print("------: Data saved to keychain \(keychainResult)")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
| mit | f8d6ec47602526af1a7531894fa6d817 | 36.785714 | 121 | 0.548474 | 5.390102 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/animation/types/animation_generators/TransformGenerator.swift | 1 | 2950 | import UIKit
func addTransformAnimation(_ animation: BasicAnimation, sceneLayer: CALayer, animationCache: AnimationCache, completion: @escaping (() -> ())) {
guard let transformAnimation = animation as? TransformAnimation else {
return
}
guard let node = animation.node else {
return
}
// Creating proper animation
var generatedAnimation: CAAnimation?
generatedAnimation = transformAnimationByFunc(node, valueFunc: transformAnimation.getVFunc(), duration: animation.getDuration(), fps: transformAnimation.logicalFps)
guard let generatedAnim = generatedAnimation else {
return
}
generatedAnim.repeatCount = Float(animation.repeatCount)
generatedAnim.timingFunction = caTimingFunction(animation.easing)
generatedAnim.completion = { finished in
if !animation.manualStop {
animation.progress = 1.0
node.placeVar.value = transformAnimation.getVFunc()(1.0)
} else {
node.placeVar.value = transformAnimation.getVFunc()(animation.progress)
}
animationCache.freeLayer(node)
animation.completion?()
if !finished {
animationRestorer.addRestoreClosure(completion)
return
}
completion()
}
generatedAnim.progress = { progress in
let t = Double(progress)
node.placeVar.value = transformAnimation.getVFunc()(t)
animation.progress = t
animation.onProgressUpdate?(t)
}
let layer = animationCache.layerForNode(node, animation: animation)
layer.add(generatedAnim, forKey: animation.ID)
animation.removeFunc = {
layer.removeAnimation(forKey: animation.ID)
}
}
func transfomToCG(_ transform: Transform) -> CGAffineTransform {
return CGAffineTransform(
a: CGFloat(transform.m11),
b: CGFloat(transform.m12),
c: CGFloat(transform.m21),
d: CGFloat(transform.m22),
tx: CGFloat(transform.dx),
ty: CGFloat(transform.dy))
}
func transformAnimationByFunc(_ node: Node, valueFunc: (Double) -> Transform, duration: Double, fps: UInt) -> CAAnimation {
var transformValues = [CATransform3D]()
var timeValues = [Double]()
let step = 1.0 / (duration * Double(fps))
var dt = 0.0
var tValue = Array(stride(from: 0.0, to: 1.0, by: step))
tValue.append(1.0)
for t in tValue {
dt = t
if 1.0 - dt < step {
dt = 1.0
}
let value = AnimationUtils.absoluteTransform(node, pos: valueFunc(dt))
let cgValue = CATransform3DMakeAffineTransform(RenderUtils.mapTransform(value))
transformValues.append(cgValue)
}
let transformAnimation = CAKeyframeAnimation(keyPath: "transform")
transformAnimation.duration = duration
transformAnimation.values = transformValues
transformAnimation.keyTimes = timeValues as [NSNumber]?
transformAnimation.fillMode = kCAFillModeForwards
transformAnimation.isRemovedOnCompletion = false
return transformAnimation
}
func fixedAngle(_ angle: CGFloat) -> CGFloat {
return angle > -0.0000000000000000000000001 ? angle : CGFloat(2.0 * M_PI) + angle
}
| mit | d7769f0a842c76e376fb94001609c8df | 27.365385 | 165 | 0.725763 | 3.959732 | false | false | false | false |
mathcamp/lightbase | hldb/Lib/FMDBConnector.swift | 2 | 1978 | //
// FMDBConnector.swift
// hldb
//
// Created by Noah Picard on 6/27/16.
// Copyright © 2016 Mathcamp. All rights reserved.
//
import Foundation
public struct FMCursor: LazySequenceType, GeneratorType {
public typealias Element = NSDictionary
let fmResult: FMResultSet
public mutating func next() -> NSDictionary? {
if fmResult.next() {
return fmResult.resultDictionary()
} else {
return nil
}
}
}
public class FMAbstractDB: AbstractDB {
public typealias Cursor = FMCursor
internal let fmdb: FMDatabase
public init(fmdb: FMDatabase) {
self.fmdb = fmdb
}
public func executeUpdate(sql: String, withArgumentsInArray args:[AnyObject]) -> Bool {
return fmdb.executeUpdate(sql, withArgumentsInArray: args)
}
public func executeQuery(query: String, withArgumentsInArray args:[AnyObject]) -> FMCursor? {
return (fmdb.executeQuery(query, withArgumentsInArray: args) as FMResultSet?).map(FMCursor.init)
}
public func lastErrorMessage() -> String {
return fmdb.lastErrorMessage()
}
public func lastErrorCode() -> Int {
return Int(fmdb.lastErrorCode())
}
}
public class FMAbstractDBQueue: AbstractDBQueue {
public typealias DB = FMAbstractDB
let dbPath: String
let fmdbQueue: FMDatabaseQueue
public required init(dbPath: String) {
self.dbPath = dbPath
fmdbQueue = FMDatabaseQueue.init(path: dbPath)
}
public func execInDatabase(block: DB -> ()) {
fmdbQueue.inDatabase{ db in block(FMAbstractDB(fmdb: db)) }
}
public func execInTransaction(block: DB -> RollbackChoice) {
let fullBlock: (FMDatabase!, UnsafeMutablePointer<ObjCBool>) -> () = {db, success in
success.initialize(ObjCBool(
{
switch block(FMAbstractDB(fmdb: db)) {
case .Rollback:
return true
case .Ok:
return false
}}()
))
}
fmdbQueue.inTransaction(fullBlock)
}
}
| mit | 17101677c9aac9e1fec30428dec403e6 | 21.724138 | 100 | 0.663126 | 4.326039 | false | false | false | false |
stephanmantler/SwiftyGPIO | Sources/1Wire.swift | 1 | 3894 | /*
SwiftyGPIO
Copyright (c) 2017 Umberto Raimondi
Licensed under the MIT license, as follows:
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.)
*/
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
// MARK: - 1-Wire Presets
extension SwiftyGPIO {
public static func hardware1Wires(for board: SupportedBoard) -> [OneWireInterface]? {
switch board {
case .RaspberryPiRev1:
fallthrough
case .RaspberryPiRev2:
fallthrough
case .RaspberryPiPlusZero:
fallthrough
case .RaspberryPi2:
fallthrough
case .RaspberryPi3:
return [SysFSOneWire(masterId: 1)]
default:
return nil
}
}
}
// MARK: 1-Wire
public protocol OneWireInterface {
func getSlaves() -> [String]
func readData(_ slaveId: String) -> [String]
}
/// Hardware 1-Wire via SysFS
public final class SysFSOneWire: OneWireInterface {
let masterId: Int
public init(masterId: Int) {
self.masterId = masterId
}
public func getSlaves() -> [String] {
let listpath = ONEWIREBASEPATH+"w1_bus_master"+String(masterId)+"/w1_master_slaves"
let fd = open(listpath, O_RDONLY | O_SYNC)
guard fd>0 else {
perror("Couldn't open 1-Wire master device")
abort()
}
var slaves = [String]()
while let s = readLine(fd) {
slaves.append(s)
}
close(fd)
return slaves
}
public func readData(_ slaveId: String) -> [String] {
let devicepath = ONEWIREBASEPATH+slaveId+"/w1_slave"
let fd = open(devicepath, O_RDONLY | O_SYNC)
guard fd>0 else {
perror("Couldn't open 1-Wire slave device")
abort()
}
var lines = [String]()
while let s = readLine(fd) {
lines.append(s)
}
close(fd)
return lines
}
private func readLine(_ fd: Int32) -> String? {
var buf = [CChar](repeating:0, count: 128)
var ptr = UnsafeMutablePointer<CChar>(&buf)
var pos = 0
repeat {
let n = read(fd, ptr, MemoryLayout<CChar>.stride)
if n<0 {
perror("Error while reading from 1-Wire interface")
abort()
} else if n == 0 {
break
}
ptr += 1
pos += 1
} while buf[pos-1] != CChar(UInt8(ascii: "\n"))
if pos == 0 {
return nil
} else {
buf[pos-1] = 0
return String(cString: &buf)
}
}
}
// MARK: - 1-Wire Constants
internal let ONEWIREBASEPATH = "/sys/bus/w1/devices/"
// MARK: - Darwin / Xcode Support
#if os(OSX) || os(iOS)
private var O_SYNC: CInt { fatalError("Linux only") }
#endif
| mit | a91ffa08e21794a46eab32da769fec2a | 27.014388 | 95 | 0.59887 | 4.288546 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBAConsentSection.swift | 1 | 5613 | //
// SBAConsentSection.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
/**
Mapping used to define each section in the consent document. This is used for both
visual consent and consent review.
*/
public protocol SBAConsentSection: class {
var consentSectionType: SBAConsentSectionType { get }
var sectionTitle: String? { get }
var sectionFormalTitle: String? { get }
var sectionSummary: String? { get }
var sectionContent: String? { get }
var sectionHtmlContent: String? { get }
var sectionLearnMoreButtonTitle: String? { get }
var sectionCustomImage: UIImage? { get }
var sectionCustomAnimationURLString: String? { get }
}
public enum SBAConsentSectionType: String {
// Maps to ORKConsentSectionType
// These cases use images and animations baked into ResearchKit
case overview
case privacy
case dataGathering
case dataUse
case timeCommitment
case studySurvey
case studyTasks
case onlyInDocument
// Maps to ResearchUXFactory resources
// These cases use images and animations baked into ResearchUXFactory
case understanding
case activities
case sensorData
case medicalCare
case followUp
case potentialRisks
case exitArrow
case thinkItOver
case futureResearch
case dataSharing
case qualifiedResearchers
// The section defines its own image and animation
case custom
/**
Some sections of the consent flow map to sections where the image and animation
are defined in ResearchKit. For these cases, use the ResearchKit section types.
*/
var orkSectionType: ORKConsentSectionType {
switch(self) {
case .overview:
// syoung 10/05/2016 The layout of the ORKConsentSectionType.overview does not
// match the layout of the other views so the animation is janky.
return .custom
case .privacy:
return .privacy
case .dataGathering:
return .dataGathering
case .dataUse:
return .dataUse
case .timeCommitment:
return .timeCommitment
case .studySurvey:
return .studySurvey
case .studyTasks:
return .studyTasks
case .onlyInDocument:
return .onlyInDocument
case .potentialRisks:
// Internally, we use the "withdrawing" image and animation for potential risks
return .withdrawing
default:
return .custom
}
}
var customImage: UIImage? {
let imageName = "consent_\(self.rawValue)"
return SBAResourceFinder.shared.image(forResource: imageName)
}
}
extension SBAConsentSection {
func createConsentSection(previous: SBAConsentSectionType?) -> ORKConsentSection {
let section = ORKConsentSection(type: self.consentSectionType.orkSectionType)
section.title = self.sectionTitle
section.formalTitle = self.sectionFormalTitle
section.summary = self.sectionSummary
section.content = self.sectionContent
section.htmlContent = self.sectionHtmlContent
section.customImage = self.sectionCustomImage ?? self.consentSectionType.customImage
section.customAnimationURL = animationURL(previous: previous)
section.customLearnMoreButtonTitle = self.sectionLearnMoreButtonTitle ?? Localization.buttonLearnMore()
return section
}
func animationURL(previous: SBAConsentSectionType?) -> URL? {
let fromSection = previous?.rawValue ?? "blank"
let toSection = self.consentSectionType.rawValue
let urlString = self.sectionCustomAnimationURLString ?? "consent_\(fromSection)_to_\(toSection)"
let scaleFactor = UIScreen.main.scale >= 3 ? "@3x" : "@2x"
return SBAResourceFinder.shared.url(forResource: "\(urlString)\(scaleFactor)", withExtension: "m4v")
}
}
| bsd-3-clause | 3554ee0003f7f9832e4724a540e81aaa | 37.972222 | 111 | 0.709373 | 5.064982 | false | false | false | false |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Supports/Calendars.swift | 1 | 3114 | //
// CalendarConvertible.swift
// SwiftDate
//
// Created by Daniele Margutti on 06/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
public typealias Calendars = Calendar.Identifier
public protocol CalendarConvertible {
func toCalendar() -> Calendar
}
extension Calendar: CalendarConvertible {
public func toCalendar() -> Calendar {
return self
}
internal static func newCalendar(_ calendar: CalendarConvertible, configure: ((inout Calendar) -> Void)? = nil) -> Calendar {
var cal = calendar.toCalendar()
configure?(&cal)
return cal
}
}
extension Calendar.Identifier: CalendarConvertible {
public func toCalendar() -> Calendar {
return Calendar(identifier: self)
}
}
// MARK: - Support for Calendar.Identifier encoding with Codable
extension Calendar.Identifier: CustomStringConvertible {
public var description: String {
switch self {
case .gregorian: return "gregorian"
case .buddhist: return "buddhist"
case .chinese: return "chinese"
case .coptic: return "coptic"
case .ethiopicAmeteMihret: return "ethiopicAmeteMihret"
case .ethiopicAmeteAlem: return "ethiopicAmeteAlem"
case .hebrew: return "hebrew"
case .iso8601: return "iso8601"
case .indian: return "indian"
case .islamic: return "islamic"
case .islamicCivil: return "islamicCivil"
case .japanese: return "japanese"
case .persian: return "persian"
case .republicOfChina: return "republicOfChina"
case .islamicTabular: return "islamicTabular"
case .islamicUmmAlQura: return "islamicUmmAlQura"
}
}
public init(_ rawValue: String) {
switch rawValue {
case Calendar.Identifier.gregorian.description: self = .gregorian
case Calendar.Identifier.buddhist.description: self = .buddhist
case Calendar.Identifier.chinese.description: self = .chinese
case Calendar.Identifier.coptic.description: self = .coptic
case Calendar.Identifier.ethiopicAmeteMihret.description: self = .ethiopicAmeteMihret
case Calendar.Identifier.ethiopicAmeteAlem.description: self = .ethiopicAmeteAlem
case Calendar.Identifier.hebrew.description: self = .hebrew
case Calendar.Identifier.iso8601.description: self = .iso8601
case Calendar.Identifier.indian.description: self = .indian
case Calendar.Identifier.islamic.description: self = .islamic
case Calendar.Identifier.islamicCivil.description: self = .islamicCivil
case Calendar.Identifier.japanese.description: self = .japanese
case Calendar.Identifier.persian.description: self = .persian
case Calendar.Identifier.republicOfChina.description: self = .republicOfChina
case Calendar.Identifier.islamicTabular.description: self = .islamicTabular
case Calendar.Identifier.islamicTabular.description: self = .islamicTabular
case Calendar.Identifier.islamicUmmAlQura.description: self = .islamicUmmAlQura
default:
let defaultCalendar = SwiftDate.defaultRegion.calendar.identifier
debugPrint("Calendar Identifier '\(rawValue)' not recognized. Using default (\(defaultCalendar))")
self = defaultCalendar
}
}
}
| apache-2.0 | 8e8de80dd03010481adf131e575c7f89 | 33.588889 | 126 | 0.752008 | 4.063969 | false | false | false | false |
CYXiang/CYXSwiftDemo | CYXSwiftDemo/CYXSwiftDemo/Classes/Main/GuideViewController.swift | 1 | 3534 | //
// NewCharacteristicsViewController.swift
// CYXSwiftDemo
//
// Created by apple开发 on 16/5/5.
// Copyright © 2016年 cyx. All rights reserved.
//
import UIKit
class GuideViewController: BaseViewController {
private var collectionView: UICollectionView?
private var imageNames = ["guide_40_1", "guide_40_2", "guide_40_3", "guide_40_4"]
private let cellIdentifier = "GuideCell"
private var isHiddenNextButton = true
private var pageController = UIPageControl(frame: CGRectMake(0, ScreenHeight - 50, ScreenWidth, 20))
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.None)
buildCollectionView()
buildPageController()
}
// MARK: - Build UI
private func buildCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = ScreenBounds.size
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView = UICollectionView(frame: ScreenBounds, collectionViewLayout: layout)
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
collectionView?.pagingEnabled = true
collectionView?.bounces = false
collectionView?.registerClass(GuideCell.self, forCellWithReuseIdentifier: cellIdentifier)
view.addSubview(collectionView!)
}
private func buildPageController() {
pageController.numberOfPages = imageNames.count
pageController.currentPage = 0
view.addSubview(pageController)
}
}
extension GuideViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! GuideCell
cell.newImage = UIImage(named: imageNames[indexPath.row])
if indexPath.row != imageNames.count - 1 {
cell.setNextButtonHidden(true)
}
return cell
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.contentOffset.x == ScreenWidth * CGFloat(imageNames.count - 1) {
let cell = collectionView!.cellForItemAtIndexPath(NSIndexPath(forRow: imageNames.count - 1, inSection: 0)) as! GuideCell
cell.setNextButtonHidden(false)
isHiddenNextButton = false
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.x != ScreenWidth * CGFloat(imageNames.count - 1) && !isHiddenNextButton && scrollView.contentOffset.x > ScreenWidth * CGFloat(imageNames.count - 2) {
let cell = collectionView!.cellForItemAtIndexPath(NSIndexPath(forRow: imageNames.count - 1, inSection: 0)) as! GuideCell
cell.setNextButtonHidden(true)
isHiddenNextButton = true
}
pageController.currentPage = Int(scrollView.contentOffset.x / ScreenWidth + 0.5)
}
}
| apache-2.0 | 94ea848ceb7cfae2b6e7352ed7bf7178 | 39.54023 | 185 | 0.698327 | 5.661316 | false | false | false | false |
fei1990/PageScaledScroll | ScaledPageView/Pods/EZSwiftExtensions/Sources/UIImageExtensions.swift | 1 | 4037 | //
// UIImageExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UIImage {
/// EZSE: Returns compressed image to rate from 0 to 1
public func compressImage(rate rate: CGFloat) -> NSData? {
return UIImageJPEGRepresentation(self, rate)
}
/// EZSE: Returns Image size in Bytes
public func getSizeAsBytes() -> Int {
return UIImageJPEGRepresentation(self, 1)?.length ?? 0
}
/// EZSE: Returns Image size in Kylobites
public func getSizeAsKilobytes() -> Int {
let sizeAsBytes = getSizeAsBytes()
return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0
}
/// EZSE: scales image
public class func scaleTo(image image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
let newSize = CGSize(width: w, height: h)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// EZSE Returns resized image with width. Might return low quality
public func resizeWithWidth(width: CGFloat) -> UIImage {
let aspectSize = CGSize (width: width, height: aspectHeightForWidth(width))
UIGraphicsBeginImageContext(aspectSize)
self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
/// EZSE Returns resized image with height. Might return low quality
public func resizeWithHeight(height: CGFloat) -> UIImage {
let aspectSize = CGSize (width: aspectWidthForHeight(height), height: height)
UIGraphicsBeginImageContext(aspectSize)
self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
/// EZSE:
public func aspectHeightForWidth(width: CGFloat) -> CGFloat {
return (width * self.size.height) / self.size.width
}
/// EZSE:
public func aspectWidthForHeight(height: CGFloat) -> CGFloat {
return (height * self.size.width) / self.size.height
}
/// EZSE: Returns cropped image from CGRect
public func croppedImage(bound: CGRect) -> UIImage? {
guard self.size.width > bound.origin.x else {
print("EZSE: Your cropping X coordinate is larger than the image width")
return nil
}
guard self.size.height > bound.origin.y else {
print("EZSE: Your cropping Y coordinate is larger than the image height")
return nil
}
let scaledBounds: CGRect = CGRect(x: bound.x * self.scale, y: bound.y * self.scale, width: bound.w * self.scale, height: bound.h * self.scale)
let imageRef = CGImageCreateWithImageInRect(self.CGImage!, scaledBounds)
let croppedImage: UIImage = UIImage(CGImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.Up)
return croppedImage
}
///EZSE: Returns the image associated with the URL
public convenience init?(urlString: String) {
guard let url = NSURL(string: urlString) else {
self.init(data: NSData())
return
}
guard let data = NSData(contentsOfURL: url) else {
print("EZSE: No image in URL \(urlString)")
self.init(data: NSData())
return
}
self.init(data: data)
}
///EZSE: Returns an empty image //TODO: Add to readme
public class func blankImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mit | 4425a53d2026aa857ecb7f02925fc502 | 36.036697 | 150 | 0.655189 | 4.805952 | false | false | false | false |
christopherhelf/TouchHeatmap | Source/TouchHeatmapExtensions.swift | 2 | 4120 | //
// TouchHeatmapExtensions.swift
// TouchHeatmap
//
// Created by Christopher Helf on 27.09.15.
// Copyright © 2015 Christopher Helf. All rights reserved.
//
import Foundation
import UIKit
/**
- UIApplication Extension
We exchange implementations of the sendEvent method in order to be able to capture
all touches occurring within the application, the other option would be to subclass
UIApplication, which is however harder for users to setup
*/
public protocol SwizzlingInjection: class {
static func inject()
}
class SwizzlingHelper {
private static let doOnce: Any? = {
UIViewController.inject()
return nil
}()
static func enableInjection() {
_ = SwizzlingHelper.doOnce
}
}
extension UIApplication {
override open var next: UIResponder? {
// Called before applicationDidFinishLaunching
SwizzlingHelper.enableInjection()
return super.next
}
// Here we exchange the implementations
func swizzleSendEvent() {
let original = class_getInstanceMethod(object_getClass(self), #selector(UIApplication.sendEvent(_:)))
let swizzled = class_getInstanceMethod(object_getClass(self), #selector(self.sendEventTracked(_:)))
method_exchangeImplementations(original!, swizzled!);
}
// The new method, where we also send touch events to the TouchHeatmap Singleton
@objc func sendEventTracked(_ event: UIEvent) {
self.sendEventTracked(event)
TouchHeatmap.sharedInstance.sendEvent(event: event)
}
}
/**
- UIViewController Extension
In order to make screenshots and to manage the flows between Controllers,
we need to know when a screen was presented. We override the initialization
function here and exchange implementations of the viewDidAppear method
In addition, we can add a name to a UIViewController so it's name is being
tracked more easily
*/
extension UIViewController : SwizzlingInjection {
// Reference for deprecates UIViewController initialize()
// https://stackoverflow.com/questions/42824541/swift-3-1-deprecates-initialize-how-can-i-achieve-the-same-thing/42824542#_=_
public static func inject() {
// make sure this isn't a subclass
guard self === UIViewController.self else { return }
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
let swizzledSelector = #selector(viewDidAppearTracked(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!);
}
}
// The struct we storing for the controller's name
private struct AssociatedKeys {
static var DescriptiveName = "TouchHeatMapViewControllerKeyDefault"
}
// The variable that's set as the controller's name, default's to the classname
var touchHeatmapKey: String {
get {
if let name = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String {
return name
} else {
return String.init(describing: self.classForCoder)
}
}
set {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
// The method where we are tracking
@objc func viewDidAppearTracked(_ animated: Bool) {
self.viewDidAppearTracked(animated)
TouchHeatmap.sharedInstance.viewDidAppear(name: self.touchHeatmapKey)
}
}
| mit | 99a385b7892132d2c76d3573acc71b3f | 31.952 | 150 | 0.682933 | 5.240458 | false | false | false | false |
exyte/Macaw | Source/MCAMediaTimingFunctionName_iOS.swift | 1 | 558 | //
// MCAMediaTimingFunctionName_iOS.swift
// Macaw
//
// Created by Anton Marunko on 27/09/2018.
// Copyright © 2018 Exyte. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
public struct MCAMediaTimingFunctionName {
static let linear = CAMediaTimingFunctionName.linear
static let easeIn = CAMediaTimingFunctionName.easeIn
static let easeOut = CAMediaTimingFunctionName.easeOut
static let easeInEaseOut = CAMediaTimingFunctionName.easeInEaseOut
static let `default` = CAMediaTimingFunctionName.default
}
#endif
| mit | f53bfbb3b9d7c15cacc6a0e8423ba59c | 24.318182 | 70 | 0.771993 | 4.680672 | false | false | false | false |
nessBautista/iOSBackup | DataStructsSwift/DataStructsSwift/BinaryTree.swift | 1 | 19617 | //
// BinaryTree.swift
// DataStructsSwift
//
// Created by Ness on 4/13/17.
// Copyright © 2017 Ness. All rights reserved.
//
import UIKit
//MARK: BINARY TREE CLASS
public class BinaryTree<T:Comparable>
{
public var root:BinaryTreeNode<T>?
public init(root: T)
{
self.root = BinaryTreeNode(value:root)
}
//MARK: ADD
public func add(value: T)
{
guard let root = self.root else {
print("Tree is empty")
return
}
self.addHelper(node: root, value: value)
}
private func addHelper(node: BinaryTreeNode<T>, value: T)
{
if value < node.value
{
if let left = node.leftChild {
self.addHelper(node: left, value: value)
}
else
{
let newNode = BinaryTreeNode(value:value)
newNode.parent = node
node.leftChild = newNode
}
}
else if value > node.value
{
if let right = node.rightChild {
self.addHelper(node: right, value: value)
}
else
{
let newNode = BinaryTreeNode(value:value)
newNode.parent = node
node.rightChild = newNode
}
}
else
{
print("Duplicated")
}
}
//MARK: SEARCH
public func search(value:T) -> BinaryTreeNode<T>?
{
//Just in case root is removed at some point
guard let root = self.root else {
return nil
}
return self.searchHelper(node: root, value: value)
}
private func searchHelper(node: BinaryTreeNode<T>, value: T) -> BinaryTreeNode<T>?
{
if value == node.value
{
return node
}
else if value < node.value
{
if let left = node.leftChild {
return self.searchHelper(node: left, value: value)
}
else
{
return nil
}
}
else
{
if let right = node.rightChild {
return self.searchHelper(node: right, value: value)
}
else
{
return nil
}
}
}
//MARK: MINIMUMS AND MAXIMUMS
public func getMaximum() -> BinaryTreeNode<T>
{
if let right = self.root?.rightChild {
return self.getMaximumHelper(node: right)
}
else
{
return self.root!
}
}
private func getMaximumHelper(node: BinaryTreeNode<T>) -> BinaryTreeNode<T>
{
if let right = node.rightChild {
return self.getMaximumHelper(node: right)
}
else
{
return node
}
}
public func getMinimum() -> BinaryTreeNode<T>
{
if let left = self.root?.leftChild {
return self.getMinimumHelper(node: left)
}
else
{
return self.root!
}
}
private func getMinimumHelper(node: BinaryTreeNode<T>) -> BinaryTreeNode<T>
{
if let left = node.leftChild {
return self.getMinimumHelper(node: left)
}
else
{
return node
}
}
public func getMaximumValue() -> T?
{
guard let root = self.root else {
print("empty tree")
return nil
}
var prev = root.parent
var current: BinaryTreeNode<T>? = root
while(current != nil)
{
prev = current
current = current?.rightChild
}
return prev?.value
}
public func getMinimumValue() -> T?
{
guard let root = self.root else {
print("empty tree")
return nil
}
var prev = root.parent
var current:BinaryTreeNode<T>? = root
while current != nil
{
prev = current
current = current?.leftChild
}
return prev?.value
}
//MARK: ROTATIONS
/*
Two cases for rotation, it depends if the node being rotated is the root or not
*/
public func rotateLeft(node:BinaryTreeNode<T>)
{
//IF THE ROOT IS BEING ROTATED
if node.parent == nil
{
let x = node
let y = node.rightChild
x.rightChild = y?.leftChild
y?.leftChild?.parent = x
if x.parent == nil
{
self.root = y
}
y?.leftChild = x
x.parent = y
}
else
{
//Set nodes: X is the rotating node
//Y is taking X's place (upward)
let x = node
let y = node.rightChild
//connect y left subtree with x right subtree (optionals take care of validations)
x.rightChild = y?.leftChild
y?.leftChild?.parent = x
//update root
if x.parent == nil
{
self.root = y
}
//Connect X's Parent with Y <->
//Link x's parent with y
y?.parent = x.parent
if x === x.parent?.leftChild
{
//x is the left child
x.parent?.leftChild = y
}
else
{
//x is the right child
x.parent?.rightChild = y
}
//Put x on y's left
y?.leftChild = x
x.parent = y
}
}
public func rotateRight(node:BinaryTreeNode<T>)
{
//IF THE ROOT IS BEING ROTATED
if node.parent == nil
{
let x = node
let y = node.leftChild
x.leftChild = y?.rightChild
y?.rightChild?.parent = x
if x.parent == nil
{
self.root = y
}
y?.rightChild = x
x.parent = y
}
else
{
//SET NODES
let x = node
let y = node.parent
//Connect x's right subtree with y's left subtree
y?.leftChild = x.rightChild
x.rightChild?.parent = y
//Update root
if y?.parent == nil
{
self.root = x
}
//Connect Y's Parent with X <->
//Link y's parent with x
x.parent = y?.parent
if y === y?.parent?.leftChild
{
//y is the left child
y?.parent?.leftChild = x
}
else
{
//y is the right child
y?.parent?.rightChild = x
}
//Put Y on X's right
x.rightChild = y
y?.parent = x
}
}
//MARK: DELETE
public func delete(node: BinaryTreeNode<T>?)
{
guard let nodeToDelete = node else {
return
}
//We will have 3 cases, node to delete has 2 children, only left, only right
if let left = node?.leftChild {
if let right = node?.rightChild {
}
//CASE 2: Node has only left child
guard let parent = node?.parent else {
//If parent is nil
node?.leftChild?.parent = node?.parent //set leftchild's to nil
return
}
//Connect parent to child
//If nodeToDelete is the left child, connect to the left only child
left.parent = parent
if parent.leftChild === nodeToDelete
{
parent.leftChild = left
}
else
{
parent.rightChild = left
}
}
else if let right = node?.rightChild
{
//CASE 3: Node has only right child
guard let parent = node?.parent else {
node?.rightChild?.parent = node?.parent
return
}
//Connect parent to child
//If nodeToDelete is the left child, connect to the right only child
right.parent = parent
if parent.leftChild === nodeToDelete
{
parent.leftChild = right
}
else
{
parent.rightChild = right
}
}
}
private func connectNode(parent:BinaryTreeNode<T>?, to child:BinaryTreeNode<T>?)
{
//first check that the parent is not nil
guard let p = parent else {
child?.parent = parent //set child's parent to nil
return
}
//if the node is the lf
}
//MARK: HEIGHT AND DEPTH
public func height() -> Int
{
guard let root = self.root else {
return 0
}
return self.heightHelper(node: root)
}
private func heightHelper(node: BinaryTreeNode<T>?) -> Int
{
if node?.rightChild == nil && node?.leftChild == nil
{
return 0
}
else
{
return 1 + max(self.heightHelper(node: node?.rightChild),self.heightHelper(node: node?.leftChild))
}
}
public func depth(node:BinaryTreeNode<T>?) -> Int
{
guard var parent = node?.parent else {
return 0
}
var depth = 0
while (true)
{
depth = 1 + depth
if let p = parent.parent {
parent = p
}
else
{
break
}
}
return depth
}
//MARK: PRINTING FUNCTIONS
public func printRBTreeByLevels(nodes:[BinaryTreeNode<T>])
{
var children:[BinaryTreeNode<T>] = Array()
for node in nodes
{
print("\(node.value) ")
if let leftChild = node.leftChild {
children.append(leftChild)
}
if let rightChild = node.rightChild {
children.append(rightChild)
}
}
if children.count > 0
{
print("************")
printRBTreeByLevels(nodes: children)
}
}
public func inOrder()
{
guard let root = self.root else {
print("Tree empty")
return
}
self.inOrderHelper(node: root)
}
private func inOrderHelper(node: BinaryTreeNode<T>?)
{
guard let n = node else {
return
}
self.inOrderHelper(node: n.leftChild)
print(n.value)
self.inOrderHelper(node: n.rightChild)
}
public func preOrder()
{
guard let root = self.root else {
print("Tree empty")
return
}
self.preOrderHelper(node: root)
}
private func preOrderHelper(node: BinaryTreeNode<T>?)
{
guard let n = node else {
return
}
print(n.value)
self.preOrderHelper(node: n.leftChild)
self.preOrderHelper(node: n.rightChild)
}
public func postOrder()
{
guard let root = self.root else {
print("Tree empty")
return
}
self.postOrderHelper(node: root)
}
private func postOrderHelper(node: BinaryTreeNode<T>?)
{
guard let n = node else {
return
}
self.postOrderHelper(node: n.leftChild)
self.postOrderHelper(node: n.rightChild)
print(n.value)
}
}
//MARK: SINGLE NODE CLASS
public class BinaryTreeNode<T:Comparable>
{
public var value: T
public var leftChild:BinaryTreeNode?
public var rightChild:BinaryTreeNode?
public weak var parent:BinaryTreeNode?
public convenience init(value:T)
{
self.init(value: value, left: nil, right: nil, parent: nil)
}
public init(value:T, left:BinaryTreeNode?, right:BinaryTreeNode?, parent: BinaryTreeNode?)
{
self.value = value
self.leftChild = left
self.rightChild = right
self.parent = parent
}
public func insertNodeFromRoot(value: T)
{
//to maintain the binary search tree property we must ensure that we run the insertNode process from the root node
if let _ = self.parent {
print("You can only add new nodes from the root node of the tree")
return
}
self.addNode(value: value)
}
public func addNode(value:T)
{
if value < self.value
{
if let left = self.leftChild {
left.addNode(value: value)
}
else
{
let newNode = BinaryTreeNode(value: value)
newNode.parent = self
self.leftChild = newNode
}
}
else if value > self.value
{
if let right = self.rightChild {
right.addNode(value: value)
}
else
{
let newNode = BinaryTreeNode(value: value)
newNode.parent = self
self.rightChild = newNode
}
}
else
{
print("dup")
}
}
public class func traverseInOrder(node: BinaryTreeNode?)
{
guard let node = node else {
return
}
BinaryTreeNode.traverseInOrder(node: node.leftChild)
print(node.value)
BinaryTreeNode.traverseInOrder(node: node.rightChild)
}
public class func traversePreOrder(node: BinaryTreeNode?)
{
guard let node = node else {
return
}
print(node.value)
BinaryTreeNode.traversePreOrder(node: node.leftChild)
BinaryTreeNode.traversePreOrder(node: node.rightChild)
}
public class func traversePostOrder(node: BinaryTreeNode?)
{
guard let node = node else {
return
}
BinaryTreeNode.traversePostOrder(node: node.leftChild)
BinaryTreeNode.traversePostOrder(node: node.rightChild)
print(node.value)
}
public func search(value: T) -> BinaryTreeNode?
{
if value == self.value
{
return self
}
else if value < self.value
{
guard let left = self.leftChild else {
return nil
}
return left.search(value: value)
}
else
{
guard let right = self.rightChild else {
return nil
}
return right.search(value: value)
}
}
public func delete()
{
if let left = leftChild {
if let _ = rightChild {
//node has 2 children
self.exchangeWithSuccessor()
}
else
{
//Node has only left child
self.connectParentTo(child: left)
}
}
else if let right = rightChild {
//Node has only right child
self.connectParentTo(child: right)
}
else
{
//Node has no childs
self.connectParentTo(child: nil)
}
//Delete refrences
self.parent = nil
self.leftChild = nil
self.rightChild = nil
}
private func exchangeWithSuccessor()
{
//making sure node has both childs
guard let right = self.rightChild, let left = self.leftChild else {
return
}
//GET THE SUCCESSOR
//The successor is the node with the lowest value in the right subtree
let successor = right.minimum()
//Disconnect the successor (this won't have any childs because is the minimum value)
successor.delete()
//CONNECT CURRENT DELETING NODE LEFT AND RIGHT CHILDS TO THE SUCCESSOR
//Connect the left child with its new parent
successor.leftChild = left
left.parent = successor
if right !== successor
{
//if the successor was NOT inmediatly connected to the deleted node
successor.rightChild = right
right.parent = successor
}
else
{
//If the successor was the right child of the deleted node
//Then the successor won't have any childs
successor.rightChild = nil
}
//CONNECT THE PARENT
self.connectParentTo(child: successor)
}
private func connectParentTo(child: BinaryTreeNode?)
{
guard let parent = self.parent else {
//set child to nil
child?.parent = self.parent
return
}
if parent.leftChild === self
{
//If self is the left child of its parent
parent.leftChild = child
child?.parent = parent
}
else if parent.rightChild === self
{
//If self is the right child of its parent
parent.rightChild = child
child?.parent = parent
}
}
public func minimumValue() -> T
{
if let left = leftChild {
return left.minimumValue()
}
else
{
return value
}
}
public func maximumValue() -> T
{
if let right = rightChild {
return right.maximumValue()
}
else
{
return value
}
}
public func minimum() -> BinaryTreeNode
{
if let left = leftChild {
return left.minimum()
}
else
{
return self
}
}
public func maximum() -> BinaryTreeNode
{
if let right = rightChild {
return right.maximum()
}
else
{
return self
}
}
public func height()-> Int
{
if leftChild == nil && rightChild == nil
{
return 0
}
return 1 + max(leftChild?.height() ?? 0, rightChild?.height() ?? 0)
}
public func depth() -> Int
{
guard var node = parent else {
return 0
}
var depth = 1
while let parent = node.parent {
depth = depth + 1
node = parent
}
return depth
}
}
| cc0-1.0 | 7d511275b0878d6b0139a7202a2285c9 | 23.277228 | 122 | 0.456668 | 5.271701 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieCore/Concurrency/SerialRunLoop.swift | 1 | 2999 | //
// SerialRunLoop.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public class SerialRunLoop: @unchecked Sendable {
private var queue: AsyncStream<@Sendable () async -> Void>.Continuation!
private let in_runloop = TaskLocal(wrappedValue: false)
public init(priority: TaskPriority? = nil) {
let stream = AsyncStream { self.queue = $0 }
let in_runloop = self.in_runloop
Task.detached(priority: priority) {
await in_runloop.withValue(true) {
for await task in stream {
await task()
}
}
}
}
deinit {
self.queue.finish()
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension SerialRunLoop {
public var inRunloop: Bool {
return in_runloop.get()
}
}
@rethrows protocol _Rethrow {
associatedtype Success
func get() throws -> Success
}
extension _Rethrow {
func _rethrowGet() rethrows -> Success { try get() }
}
extension Result: _Rethrow { }
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension SerialRunLoop {
public func perform<T: Sendable>(_ task: @Sendable @escaping () async throws -> T) async rethrows -> T {
let result: Result<T, Error> = await withUnsafeContinuation { continuation in
self.queue.yield {
do {
try await continuation.resume(returning: .success(task()))
} catch {
continuation.resume(returning: .failure(error))
}
}
}
return try result._rethrowGet()
}
}
| mit | 2643a7c7bd99ddda5522d58fa706763a | 30.568421 | 108 | 0.611204 | 4.620955 | false | false | false | false |
haijianhuo/TopStore | Pods/JSQCoreDataKit/Source/Migrate.swift | 2 | 6703 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/**
An error type that specifies possible errors that are thrown by calling `CoreDataModel.migrate() throws`.
*/
public enum MigrationError: Error {
/**
Specifies that the `NSManagedObjectModel` corresponding to the existing persistent store was not found in the model's bundle.
- parameter model: The model that failed to be migrated.
*/
case sourceModelNotFound(model: CoreDataModel)
/**
Specifies that an `NSMappingModel` was not found in the model's bundle in the progressive migration 'path'.
- parameter sourceModel: The destination managed object model for which a mapping model was not found.
*/
case mappingModelNotFound(destinationModel: NSManagedObjectModel)
}
extension CoreDataModel {
/**
Progressively migrates the persistent store of the `CoreDataModel` based on mapping models found in the model's bundle.
If the model returns false from `needsMigration`, then this function does nothing.
- throws: If an error occurs, either an `NSError` or a `MigrationError` is thrown. If an `NSError` is thrown, it could
specify any of the following: an error checking persistent store metadata, an error from `NSMigrationManager`, or
an error from `NSFileManager`.
- warning: Migration is only supported for on-disk persistent stores.
A complete 'path' of mapping models must exist between the peristent store's version and the model's version.
*/
public func migrate() throws {
guard needsMigration else { return }
guard let storeURL = self.storeURL, let storeDirectory = storeType.storeDirectory() else {
preconditionFailure("*** Error: migration is only available for on-disk persistent stores. Invalid model: \(self)")
}
// could also throw NSError from NSPersistentStoreCoordinator
guard let sourceModel = try findCompatibleModel(withBundle: bundle, storeType: storeType.type, storeURL: storeURL) else {
throw MigrationError.sourceModelNotFound(model: self)
}
let migrationSteps = try buildMigrationMappingSteps(bundle: bundle,
sourceModel: sourceModel,
destinationModel: managedObjectModel)
for step in migrationSteps {
let tempURL = storeDirectory.appendingPathComponent("migration." + ModelFileExtension.sqlite.rawValue)
// could throw error from `migrateStoreFromURL`
let manager = NSMigrationManager(sourceModel: step.source, destinationModel: step.destination)
try manager.migrateStore(from: storeURL,
sourceType: storeType.type,
options: nil,
with: step.mapping,
toDestinationURL: tempURL,
destinationType: storeType.type,
destinationOptions: nil)
// could throw file system errors
try removeExistingStore()
try FileManager.default.moveItem(at: tempURL, to: storeURL)
}
}
}
// MARK: Internal
internal struct MigrationMappingStep {
let source: NSManagedObjectModel
let mapping: NSMappingModel
let destination: NSManagedObjectModel
}
internal func findCompatibleModel(withBundle bundle: Bundle,
storeType: String,
storeURL: URL) throws -> NSManagedObjectModel? {
let storeMetadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: storeType, at: storeURL, options: nil)
let modelsInBundle = findModelsInBundle(bundle)
for model in modelsInBundle where model.isConfiguration(withName: nil, compatibleWithStoreMetadata: storeMetadata) {
return model
}
return nil
}
internal func findModelsInBundle(_ bundle: Bundle) -> [NSManagedObjectModel] {
guard let modelBundleDirectoryURLs = bundle.urls(forResourcesWithExtension: ModelFileExtension.bundle.rawValue, subdirectory: nil) else {
return []
}
let modelBundleDirectoryNames = modelBundleDirectoryURLs.flatMap { url -> String? in
url.lastPathComponent
}
let modelVersionFileURLs = modelBundleDirectoryNames.flatMap { name -> [URL]? in
bundle.urls(forResourcesWithExtension: ModelFileExtension.versionedFile.rawValue, subdirectory: name)
}
let managedObjectModels = Array(modelVersionFileURLs.joined()).flatMap { url -> NSManagedObjectModel? in
NSManagedObjectModel(contentsOf: url)
}
return managedObjectModels
}
internal func buildMigrationMappingSteps(bundle: Bundle,
sourceModel: NSManagedObjectModel,
destinationModel: NSManagedObjectModel) throws -> [MigrationMappingStep] {
var migrationSteps = [MigrationMappingStep]()
var nextModel = sourceModel
repeat {
guard let nextStep = nextMigrationMappingStep(fromSourceModel: nextModel, bundle: bundle) else {
throw MigrationError.mappingModelNotFound(destinationModel: nextModel)
}
migrationSteps.append(nextStep)
nextModel = nextStep.destination
} while nextModel.entityVersionHashesByName != destinationModel.entityVersionHashesByName
return migrationSteps
}
internal func nextMigrationMappingStep(fromSourceModel sourceModel: NSManagedObjectModel,
bundle: Bundle) -> MigrationMappingStep? {
let modelsInBundle = findModelsInBundle(bundle)
for nextDestinationModel in modelsInBundle where nextDestinationModel.entityVersionHashesByName != sourceModel.entityVersionHashesByName {
if let mappingModel = NSMappingModel(from: [bundle],
forSourceModel: sourceModel,
destinationModel: nextDestinationModel) {
return MigrationMappingStep(source: sourceModel, mapping: mappingModel, destination: nextDestinationModel)
}
}
return nil
}
| mit | ab72747238d9630800011219f154988f | 39.373494 | 142 | 0.657416 | 5.733105 | false | false | false | false |
jasperblues/ICLoader | ICLoader.swift | 1 | 7667 | ////////////////////////////////////////////////////////////////////////////////
//
// JASPER BLUES
// Copyright 2013 - 2020, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
import NanoFrame
public class ICLoader: UIView {
public static var logoImageName: String? = nil
public static var labelFontName: String? = nil
private(set) var backgroundView: UIView!
private(set) var logoView: UIImageView!
private(set) var centerDot: UIView!
private(set) var leftDot: UIView!
private(set) var rightDot: UIView!
private(set) var label: UILabel!
public class func present() {
let lockQueue = DispatchQueue(label: "self")
lockQueue.sync {
let controller = UIApplication.shared.keyWindow?.rootViewController
var visibleController: UIViewController?
if controller is UINavigationController {
visibleController = (controller as? UINavigationController)?.visibleViewController
} else {
visibleController = controller
}
let loader = ICLoader(withImageName: logoImageName!)
DispatchQueue.main.async(execute: {
visibleController?.view.addSubview(loader)
visibleController?.view.bringSubviewToFront(loader)
visibleController?.view.isUserInteractionEnabled = false
UIView.transition(with: loader, duration: 0.33, options: [], animations: {
loader.frame = visibleController!.view.bounds
})
})
}
}
public class func dismiss() {
let controller = UIApplication.shared.keyWindow?.rootViewController
var visibleController: UIViewController?
if controller is UINavigationController {
visibleController = (controller as? UINavigationController)?.visibleViewController
} else {
visibleController = controller
}
DispatchQueue.main.async(execute: {
for loader in ICLoader.loaders(for: visibleController?.view) {
loader.layer.removeAllAnimations()
UIView.transition(with: loader, duration: 0.25, options: [.transitionFlipFromTop], animations: {
loader.alpha = 0.0
}) { finished in
loader.removeFromSuperview()
visibleController?.view.isUserInteractionEnabled = true
}
}
})
}
public class func loaders(for view: UIView?) -> [ICLoader] {
var theHUDs: [ICLoader] = []
for candidate in view?.subviews ?? [] {
if candidate is ICLoader {
theHUDs.append(candidate as! ICLoader)
}
}
return theHUDs
}
public class func setImageName(_ imageName: String?) {
logoImageName = imageName
}
public class func setLabelFontName(_ fontName: String?) {
labelFontName = fontName
}
//-------------------------------------------------------------------------------------------
// MARK: - Initializers
//-------------------------------------------------------------------------------------------
public init(withImageName imageName: String) {
if (imageName.count) == 0 {
fatalError("ICLoader requires a logo image. Set with [ICLoader setImageName:anImageName]")
}
super.init(frame: CGRect.zero)
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
backgroundView.backgroundColor = UIColor(hex: 0x666677, alpha: 0.8)
backgroundView.layer.cornerRadius = 45
backgroundView.clipsToBounds = true
addSubview(backgroundView)
initLogo(imageName)
initDots()
initLabel()
animate(toDot: rightDot)
}
public required init?(coder: NSCoder) {
fatalError("init with coder is not supported")
}
//-------------------------------------------------------------------------------------------
// MARK: - Overridden Methods
//-------------------------------------------------------------------------------------------
public override func layoutSubviews() {
super.layoutSubviews()
backgroundView.centerInSuperView()
}
//-------------------------------------------------------------------------------------------
// MARK: - Private Methods
//-------------------------------------------------------------------------------------------
private func initLogo(_ logoImageName: String) {
if let image = UIImage(named: logoImageName) {
logoView = UIImageView(image: image)
logoView.size = image.size
logoView.center(in: CGRect(x: 0, y: 7, width: 90, height: 45))
logoView.contentMode = .scaleAspectFit
backgroundView.addSubview(logoView)
}
}
private func initDots() {
let dodWidth: CGFloat = 5
let centerX = (backgroundView.frame.size.width - dodWidth) / 2
let dotY = ((backgroundView.frame.size.height - dodWidth) / 2) + 9
centerDot = UIView(frame: CGRect(x: centerX, y: dotY, width: dodWidth, height: dodWidth))
centerDot.backgroundColor = UIColor.white
centerDot.layer.cornerRadius = centerDot.width / 2
centerDot.layer.opacity = 1.0
backgroundView.addSubview(centerDot)
leftDot = UIView(frame: CGRect(x: centerX - 11, y: dotY, width: dodWidth, height: dodWidth))
leftDot.backgroundColor = UIColor.white
leftDot.layer.cornerRadius = leftDot.width / 2
leftDot.layer.opacity = 0.5
backgroundView.addSubview(leftDot)
rightDot = UIView(frame: CGRect(x: centerX + 11, y: dotY, width: dodWidth, height: dodWidth))
rightDot.backgroundColor = UIColor.white
rightDot.layer.cornerRadius = rightDot.width / 2
rightDot.layer.opacity = 0.5
backgroundView.addSubview(rightDot)
}
private func initLabel() {
label = UILabel(frame: CGRect(x: 2 + (backgroundView.frame.size.width - 65) / 2, y: 60, width: 65, height: 14))
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.textAlignment = .center
label.font = ICLoader.labelFontName != nil ? UIFont(name: ICLoader.labelFontName!, size: 10) :
UIFont.systemFont(ofSize: 10)
label.text = "Loading..."
backgroundView.addSubview(label)
}
private func animate(toDot dot: UIView?) {
weak var weakSelf = self
weak var centerDot = self.centerDot
weak var leftDot = self.leftDot
weak var rightDot = self.rightDot
if let weakSelf = weakSelf {
UIView.transition(with: weakSelf, duration: 0.4, options: .curveEaseInOut, animations: {
centerDot?.layer.opacity = dot == centerDot ? 1.0 : 0.5
rightDot?.layer.opacity = dot == rightDot ? 1.0 : 0.5
leftDot?.layer.opacity = dot == leftDot ? 1.0 : 0.5
}) { complete in
if dot == centerDot {
weakSelf.animate(toDot: rightDot)
} else if dot == rightDot {
weakSelf.animate(toDot: leftDot)
} else {
weakSelf.animate(toDot: centerDot)
}
}
}
}
} | apache-2.0 | 8e5a5041c0ef08d2252745bef9d4033c | 37.149254 | 119 | 0.55002 | 5.384129 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Extensions/WPStyleGuide+Aztec.swift | 1 | 1573 | import UIKit
import WordPressShared
extension WPStyleGuide {
static let aztecFormatBarInactiveColor: UIColor = UIColor(hexString: "7B9AB1")
static let aztecFormatBarActiveColor: UIColor = UIColor(hexString: "11181D")
static let aztecFormatBarDisabledColor = WPStyleGuide.greyLighten20()
static let aztecFormatBarDividerColor = WPStyleGuide.greyLighten30()
static let aztecFormatBarBackgroundColor = UIColor.white
static var aztecFormatPickerSelectedCellBackgroundColor: UIColor {
get {
return (UIDevice.isPad()) ? WPStyleGuide.lightGrey() : WPStyleGuide.greyLighten30()
}
}
static var aztecFormatPickerBackgroundColor: UIColor {
get {
return (UIDevice.isPad()) ? .white : WPStyleGuide.lightGrey()
}
}
static func configureBetaButton(_ button: UIButton) {
button.titleLabel?.font = UIFont.systemFont(ofSize: 11.0)
button.layer.borderWidth = 1.0
button.layer.cornerRadius = 3.0
button.tintColor = WPStyleGuide.darkGrey()
button.setTitleColor(WPStyleGuide.darkGrey(), for: .disabled)
button.layer.borderColor = WPStyleGuide.greyLighten20().cgColor
let verticalInset = CGFloat(6.0)
let horizontalInset = CGFloat(8.0)
button.contentEdgeInsets = UIEdgeInsets(top: verticalInset,
left: horizontalInset,
bottom: verticalInset,
right: horizontalInset)
}
}
| gpl-2.0 | 041a5fd03ed2b90f2ebc3b77f358b929 | 35.581395 | 95 | 0.643992 | 5.519298 | false | false | false | false |
duming91/Hear-You | Hear You/Services/Downloader.swift | 1 | 5825 | //
// Downloader.swift
// BaseKit
//
// Created by 董亚珣 on 16/4/1.
// Copyright © 2016年 snow. All rights reserved.
//
import Foundation
import UIKit
class Downloader: NSObject {
static let sharedDownloader = Downloader()
lazy var session: NSURLSession = {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
return session
}()
struct ProgressReporter {
struct Task {
let downloadTask: NSURLSessionDataTask
typealias FinishedAction = NSData -> Void
let finishedAction: FinishedAction
let progress = NSProgress()
let tempData = NSMutableData()
let imageTransform: (UIImage -> UIImage)?
}
let tasks: [Task]
var finishedTasksCount = 0
typealias ReportProgress = (progress: Double, image: UIImage?) -> Void
let reportProgress: ReportProgress?
init(tasks: [Task], reportProgress: ReportProgress?) {
self.tasks = tasks
self.reportProgress = reportProgress
}
var totalProgress: Double {
let completedUnitCount = tasks.map({ $0.progress.completedUnitCount }).reduce(0, combine: +)
let totalUnitCount = tasks.map({ $0.progress.totalUnitCount }).reduce(0, combine: +)
return Double(completedUnitCount) / Double(totalUnitCount)
}
}
var progressReporters = [ProgressReporter]()
class func downloadDataFromURL(URL: NSURL, reportProgress: ProgressReporter.ReportProgress?, finishedAction: ProgressReporter.Task.FinishedAction) {
let downloadTask = sharedDownloader.session.dataTaskWithURL(URL)
let task = ProgressReporter.Task(downloadTask: downloadTask, finishedAction: finishedAction, imageTransform: nil)
let progressReporter = ProgressReporter(tasks: [task], reportProgress: reportProgress)
sharedDownloader.progressReporters.append(progressReporter)
downloadTask.resume()
}
}
extension Downloader: NSURLSessionDataDelegate {
private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, totalBytes: Int64) {
for progressReporter in progressReporters {
for i in 0..<progressReporter.tasks.count {
if downloadTask == progressReporter.tasks[i].downloadTask {
progressReporter.tasks[i].progress.totalUnitCount = totalBytes
progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil)
return
}
}
}
}
private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, didReceiveData data: NSData) -> Bool {
for progressReporter in progressReporters {
for i in 0..<progressReporter.tasks.count {
if downloadTask == progressReporter.tasks[i].downloadTask {
let didReceiveDataBytes = Int64(data.length)
progressReporter.tasks[i].progress.completedUnitCount += didReceiveDataBytes
progressReporter.tasks[i].tempData.appendData(data)
let progress = progressReporter.tasks[i].progress
let final = progress.completedUnitCount == progress.totalUnitCount
progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil)
return final
}
}
}
return false
}
private func finishDownloadTask(downloadTask: NSURLSessionDataTask) {
for i in 0..<progressReporters.count {
for j in 0..<progressReporters[i].tasks.count {
if downloadTask == progressReporters[i].tasks[j].downloadTask {
let finishedAction = progressReporters[i].tasks[j].finishedAction
let data = progressReporters[i].tasks[j].tempData
finishedAction(data)
progressReporters[i].finishedTasksCount += 1
// 若任务都已完成,移除此 progressReporter
if progressReporters[i].finishedTasksCount == progressReporters[i].tasks.count {
progressReporters.removeAtIndex(i)
}
return
}
}
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
println("Downloader begin, expectedContentLength:\(response.expectedContentLength)")
reportProgressAssociatedWithDownloadTask(dataTask, totalBytes: response.expectedContentLength)
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
println("Downloader data.length: \(data.length)")
let finish = reportProgressAssociatedWithDownloadTask(dataTask, didReceiveData: data)
if finish {
println("Downloader finish")
finishDownloadTask(dataTask)
}
}
}
| gpl-3.0 | 56f37fff60ac5eb743f03a7605eb609b | 36.141026 | 182 | 0.591474 | 6.532131 | false | false | false | false |
Stitch7/Vaporizer | App/Application.swift | 1 | 2285 | //
// Application.swift
// Vaporizer
//
// Created by Christopher Reitz on 29.08.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import Foundation
import Vapor
import SwiftyBeaver
import SwiftyBeaverVapor
final class Application {
// MARK: - Properties
public var drop: Droplet
// MARK: - Initializers
public init(testing: Bool = false) {
var args = CommandLine.arguments
if testing {
// Simulate passing `--env=testing` from the command line if testing is true
args.append("--env=testing")
}
drop = Droplet(arguments: args)
configureProviders()
configureLogging()
configurePreparations()
configureMiddlewares()
configureRoutes()
}
private func configurePreparations() {
// Add preparations from the Preparations folder
drop.preparations = preparations
}
private func configureLogging() {
var destinations = [BaseDestination]()
destinations.append(ConsoleDestination())
if let logfile = drop.config["app", "logfile"]?.string {
let file = FileDestination()
file.logFileURL = URL(string: "file://" + logfile)!
destinations.append(file)
}
let provider = SwiftyBeaverProvider(destinations: destinations)
drop.addProvider(provider)
}
private func configureProviders() {
// Add providers from the Providers folder
do {
for provider in providers {
try drop.addProvider(provider)
}
} catch {
fatalError("Can not add provider. \(error)")
}
}
private func configureMiddlewares() {
// Add middlewares from the Middleware folder
drop.middleware += middleware
}
private func configureRoutes() {
// Add routes from the Routes folder
publicRoutes(drop)
// Protected routes requiring basic authorization
let protect = BasicAuthMiddleware()
let protectedGroup = drop.grouped(protect)
protectedRoutes(drop, protectedGroup: protectedGroup)
}
// MARK: - Public
public func start() {
drop.log.info("Starting server")
drop.run()
}
}
| mit | 08da5322494cd6b0869ef21cebcf98a0 | 24.954545 | 88 | 0.615587 | 5.08686 | false | true | false | false |
twittemb/Weavy | WeavyDemo/WeavyDemo/Services/MoviesService.swift | 1 | 1081 | //
// MoviesService.swift
// WeavyDemo
//
// Created by Thibault Wittemberg on 17-11-16.
// Copyright © 2017 Warp Factor. All rights reserved.
//
class MoviesService {
func wishlistMovies () -> [Movie] {
return MoviesRepository.movies.filter { !$0.watched }
}
func watchedMovies () -> [Movie] {
return MoviesRepository.movies.filter { $0.watched }
}
func movie (forId id: Int) -> Movie {
return MoviesRepository.movies.filter { $0.id == id }.first!
}
func cast (forId id: Int) -> Cast {
return CastsRepository.casts.filter { $0.id == id }.first!
}
func casts (for movie: Movie) -> [Cast] {
// Dumb condition to find the casting according to a movie
if movie.id % 2 == 0 {
return [CastsRepository.casts[0], CastsRepository.casts[2], CastsRepository.casts[4], CastsRepository.casts[6], CastsRepository.casts[8]]
}
return [CastsRepository.casts[1], CastsRepository.casts[3], CastsRepository.casts[5], CastsRepository.casts[7], CastsRepository.casts[9]]
}
}
| mit | c8dbf0769fe9f82158e508916dd64e4b | 29.857143 | 148 | 0.635185 | 3.884892 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Model/DataObject/DataObject.swift | 3 | 1345 | //
// DataObject.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/5/8.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import CoreData
import Foundation
enum SearchType: String {
case All = "all"
case Article = "articles"
case Question = "questions"
case Topic = "topics"
case User = "users"
}
class DataObject: NSManagedObject {
@NSManaged var id: NSNumber!
private class func cast<T>(object: NSManagedObject, type: T.Type) -> T {
return object as! T
}
class func cachedObjectWithID(ID: NSNumber) -> Self {
return cast(DataManager.defaultManager!.autoGenerate(entityName, ID: ID), type: self)
}
class func allCachedObjects() -> [DataObject] /* [Self] in not supported. */ {
return try! DataManager.defaultManager!.fetchAll(entityName)
}
class func deleteAllCachedObjects() {
try! DataManager.defaultManager!.deleteAllObjectsWithEntityName(entityName)
}
class func temporaryObject() -> Self {
return cast(DataManager.temporaryManager!.create(entityName), type: self)
}
class var entityName: String {
let s = NSStringFromClass(self)
return s.characters.split { $0 == "." }.map { String($0) }.last ?? s
}
}
| gpl-2.0 | 7e28a429164ce602fe3d831ad5f2301b | 26.408163 | 99 | 0.647803 | 4.36039 | false | false | false | false |
WPO-Foundation/xrecord | CommandLine/CommandLine.swift | 1 | 6993 | /*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for setlocale(3) */
import Darwin
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke parse(). Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, parse() will return
* false. You can then call printUsage() to output an automatically-generated usage message.
*/
open class CommandLine {
fileprivate var _arguments: [String]
fileprivate var _options: [Option] = [Option]()
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Swift.CommandLine.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
fileprivate func _getFlagValues(flagIndex: Int) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
/* Grab attached arg, if any */
var attachedArg = _arguments[flagIndex].splitByCharacter(ArgumentAttacher, maxSplits: 1)
if attachedArg.count > 1 {
args.append(attachedArg[1])
}
for i in flagIndex + 1 ..< _arguments.count {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
open func addOption(_ option: Option) {
_options.append(option)
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
open func addOptions(_ options: [Option]) {
_options += options
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
open func addOptions(_ options: Option...) {
_options += options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
open func setOptions(_ options: [Option]) {
_options = options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
open func setOptions(_ options: Option...) {
_options = options
}
/**
* Parses command-line arguments into their matching Option values.
*
* - returns: True if all arguments were parsed successfully, false if any option had an
* invalid value or if a required option was missing.
*/
open func parse() -> (Bool, String?) {
for (idx, arg) in _arguments.enumerated() {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
/* Swift strings don't have substringFromIndex(). Do a little dance instead. */
var flag = ""
var skipChars =
arg.hasPrefix(LongOptionPrefix) ? LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count
for c in arg.characters {
if skipChars > 0 {
skipChars -= 1
continue
}
flag.append(c)
}
/* Remove attached argument from flag */
flag = flag.splitByCharacter(ArgumentAttacher, maxSplits: 1)[0]
var flagMatched = false
for option in _options {
if flag == option.shortFlag || flag == option.longFlag {
let vals = self._getFlagValues(flagIndex: idx)
if !option.match(vals) {
return (false, "Invalid value for \(option.longFlag)")
}
flagMatched = true
break
}
}
/* Flags that do not take any arguments can be concatenated */
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
for (i, c) in flag.characters.enumerated() {
let flagLength = flag.characters.count
for option in _options {
if String(c) == option.shortFlag {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(flagIndex: idx) : [String]()
if !option.match(vals) {
return (false, "Invalid value for \(option.longFlag)")
}
break
}
}
}
}
}
/* Check to see if any required options were not matched */
for option in _options {
if option.required && !option.isSet {
return (false, "\(option.longFlag) is required")
}
}
return (true, nil)
}
/** Prints a usage message to stdout. */
open func printUsage() {
let name = _arguments[0]
var flagWidth = 0
for opt in _options {
flagWidth = max(flagWidth,
" \(ShortOptionPrefix)\(opt.shortFlag), \(LongOptionPrefix)\(opt.longFlag):".characters.count)
}
print("Usage: \(name) [options]")
for opt in _options {
let flags = " \(ShortOptionPrefix)\(opt.shortFlag), \(LongOptionPrefix)\(opt.longFlag):".paddedToWidth(flagWidth)
print("\(flags)\n \(opt.helpMessage)")
}
}
}
| bsd-3-clause | 62a24c4f13a12c1b5d4eb4998276a768 | 29.142241 | 120 | 0.616045 | 4.411987 | false | false | false | false |
AutomationStation/BouncerBuddy | BouncerBuddyV6/BouncerBuddy/AppDelegate.swift | 4 | 6093 | //
// AppDelegate.swift
// BouncerBuddy
//
// Created by Sha Wu on 16/3/2.
// Copyright © 2016年 Sheryl Hong. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "hong.BouncerBuddy" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("BouncerBuddy", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | f1493f9dd977f429850ea1da2c2f1100 | 53.864865 | 291 | 0.71954 | 5.889749 | false | false | false | false |
renatoguarato/cidadaoalerta | apps/ios/cidadaoalerta/cidadaoalerta/DetalhesExecucaoFinanceiraViewController.swift | 1 | 1956 | //
// DetalhesExecucaoFinanceiraViewController.swift
// cidadaoalerta
//
// Created by Renato Guarato on 26/03/16.
// Copyright © 2016 Renato Guarato. All rights reserved.
//
import UIKit
class DetalhesExecucaoFinanceiraViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var items = [DetalheTabela]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 160.0
self.automaticallyAdjustsScrollViewInsets = false
self.items = [DetalheTabela("Número Proposta", "1591"), DetalheTabela("Modalidade", "Prestação de Contas em Análise"), DetalheTabela("Órgão Superior", "MINISTERIO DO DESENV. SOCIAL E COMBATE A FOME"), DetalheTabela("Valor", "R$ 347.926,32")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func btnVoltar(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DetailViewCell
let empenho = self.items[indexPath.row]
cell.lblColunaDetalheExecucaoFinanceira.text = empenho.coluna
cell.lblValorDetalheExecucaoFinanceira.text = empenho.valor
return cell
}
}
| gpl-3.0 | ff9c8407606142d6a8fdf6bc16526720 | 31.483333 | 249 | 0.689071 | 4.730583 | false | false | false | false |
aaronbrethorst/onebusaway-iphone | OneBusAway/ui/privacy/PIIViewController.swift | 1 | 5004 | //
// PIIViewController.swift
// org.onebusaway.iphone
//
// Created by Aaron Brethorst on 10/1/16.
// Copyright © 2016 OneBusAway. All rights reserved.
//
import UIKit
import OBAKit
class PIIViewController: OBAStaticTableViewController {
lazy var privacyBroker: PrivacyBroker = {
return OBAApplication.shared().privacyBroker
}()
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Information for Support", comment: "Title of the PIIViewController")
self.tableView.tableHeaderView = OBAUIBuilder.footerView(withText: NSLocalizedString("This information is only sent to OneBusAway when you submit a support request. You can disable sending us any or all of this data, but it will limit our ability to diagnose and fix problems you are experiencing.", comment: "The footer label on the PIIViewController"), maximumWidth: self.tableView.frame.width)
self.reloadData()
// self.tableFooterView = OBAUIBuilder.footerView(text: NSLocalizedString("This information is only sent to OneBusAway when you submit a support request. You can disable sending us any or all of this data, but it will limit our ability to diagnose and fix problems you are experiencing.", comment: "The footer label on the PIIViewController"), maximumWidth: self.tableView.frame.width)
}
// MARK: - Table Sections
func reloadData() {
let regionSection = self.buildRegionSection()
let locationSection = self.buildLocationSection()
let logsSection = self.buildLogsSection()
self.sections = [regionSection, locationSection, logsSection]
self.tableView.reloadData()
}
func buildRegionSection() -> OBATableSection {
let regionSection = OBATableSection.init(title: NSLocalizedString("Region", comment: "Region section title on PII controller"))
regionSection.addRow {
return OBASwitchRow.init(title: NSLocalizedString("Share Current Region", comment: "Region switch row on PII Controller"), action: {
self.privacyBroker.toggleShareRegionInformation()
self.reloadData()
}, switchValue: self.privacyBroker.canShareRegionInformation)
}
regionSection.addRow {
let row: OBATableRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: {
self.showData(self.privacyBroker.shareableRegionInformation().description)
})
row.accessoryType = .disclosureIndicator
return row
}
return regionSection
}
func buildLocationSection() -> OBATableSection {
let locationSection = OBATableSection.init(title: NSLocalizedString("Location", comment: "Location section title on PII controller"))
locationSection.addRow {
return OBASwitchRow.init(title: NSLocalizedString("Share Location", comment: "Location switch row on PII Controller"), action: {
self.privacyBroker.toggleShareLocationInformation()
self.reloadData()
}, switchValue: self.privacyBroker.canShareLocationInformation)
}
locationSection.addRow {
let row: OBATableRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: {
var locationInfo = self.privacyBroker.shareableLocationInformation
if locationInfo == nil {
locationInfo = "NOPE"
}
self.showData(locationInfo!)
})
row.accessoryType = .disclosureIndicator
return row
}
return locationSection
}
func buildLogsSection() -> OBATableSection {
let shareRow = OBASwitchRow.init(title: NSLocalizedString("Share Logs", comment: "Share logs action row title in the PII controller"), action: {
self.privacyBroker.toggleShareLogs()
self.reloadData()
}, switchValue: self.privacyBroker.canShareLogs)
let viewDataRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: {
let logController = PTERootController.init()
self.navigationController?.pushViewController(logController, animated: true)
})
viewDataRow.accessoryType = .disclosureIndicator
let section = OBATableSection.init(title: NSLocalizedString("Logs", comment: "Logs table section in the PII controller"), rows: [shareRow, viewDataRow])
return section
}
// MARK: - Data Display
func showData(_ data: String) {
let alert = UIAlertController.init(title: nil, message: data, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: OBAStrings.dismiss(), style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| apache-2.0 | 007d5f7182e11ad61ed0d240ba82ab47 | 42.885965 | 404 | 0.681591 | 5.168388 | false | false | false | false |
otokunaga2/ibeacon-swift-tutorial | iBeaconTemplateSwift/AppDelegate.swift | 1 | 6572 | //
// AppDelegate.swift
// iBeaconTemplateSwift
//
// Created by James Nick Sears on 7/1/14.
// Copyright (c) 2014 iBeaconModules.us. All rights reserved.
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager?
var lastProximity: CLProximity?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// let uuidString = "00000000-F80B-1001-B000-001C4D47FBC6"
let uuidString = "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"
let beaconIdentifier = "iBeaconModules.us"
let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString)
let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID,
identifier: beaconIdentifier)
locationManager = CLLocationManager()
if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) {
locationManager!.requestAlwaysAuthorization()
}
locationManager!.delegate = self
locationManager!.pausesLocationUpdatesAutomatically = false
locationManager!.startMonitoringForRegion(beaconRegion)
locationManager!.startRangingBeaconsInRegion(beaconRegion)
locationManager!.startUpdatingLocation()
if(application.respondsToSelector("registerUserNotificationSettings:")) {
application.registerUserNotificationSettings(
UIUserNotificationSettings(
forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound,
categories: nil
)
)
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: CLLocationManagerDelegate {
func sendLocalNotificationWithMessage(message: String!, playSound: Bool) {
let notification:UILocalNotification = UILocalNotification()
notification.alertBody = message
if(playSound) {
// classic star trek communicator beep
// http://www.trekcore.com/audio/
//
// note: convert mp3 and wav formats into caf using:
// "afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf"
// http://stackoverflow.com/a/10388263
notification.soundName = "tos_beep.caf";
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
func locationManager(manager: CLLocationManager!,
didRangeBeacons beacons: [AnyObject]!,
inRegion region: CLBeaconRegion!) {
let viewController:ViewController = window!.rootViewController as ViewController
viewController.beacons = beacons as [CLBeacon]?
viewController.tableView!.reloadData()
NSLog("didRangeBeacons");
var message:String = ""
var playSound = false
if(beacons.count > 0) {
let nearestBeacon:CLBeacon = beacons[0] as CLBeacon
if(nearestBeacon.proximity == lastProximity ||
nearestBeacon.proximity == CLProximity.Unknown) {
return;
}
lastProximity = nearestBeacon.proximity;
switch nearestBeacon.proximity {
case CLProximity.Far:
message = "You are far away from the beacon"
playSound = true
case CLProximity.Near:
message = "You are near the beacon"
case CLProximity.Immediate:
message = "You are in the immediate proximity of the beacon"
case CLProximity.Unknown:
return
}
} else {
if(lastProximity == CLProximity.Unknown) {
return;
}
message = "No beacons are nearby"
playSound = true
lastProximity = CLProximity.Unknown
}
NSLog("%@", message)
sendLocalNotificationWithMessage(message, playSound: playSound)
}
func locationManager(manager: CLLocationManager!,
didEnterRegion region: CLRegion!) {
manager.startRangingBeaconsInRegion(region as CLBeaconRegion)
manager.startUpdatingLocation()
NSLog("You entered the region")
sendLocalNotificationWithMessage("You entered the region", playSound: false)
}
func locationManager(manager: CLLocationManager!,
didExitRegion region: CLRegion!) {
manager.stopRangingBeaconsInRegion(region as CLBeaconRegion)
manager.stopUpdatingLocation()
NSLog("You exited the region")
sendLocalNotificationWithMessage("You exited the region", playSound: true)
}
}
| mit | fecd1750444d71843e44228cb61377af | 39.567901 | 285 | 0.660073 | 5.873101 | false | false | false | false |
janslow/qlab-from-csv | QLab From CSV/QLabFromCsv/CsvParser.swift | 1 | 3676 | //
// csv.swift
// QLab From CSV
//
// Created by Jay Anslow on 20/12/2014.
// Copyright (c) 2014 Jay Anslow. All rights reserved.
//
import Foundation
public class CsvParser {
public class func csv() -> CsvParser {
return CsvParser(delimiter: ",")
}
private var delimiter : String
init(delimiter : String) {
self.delimiter = delimiter
}
func parse(contents : String) -> (headers: [String], rows: [Dictionary<String,String>])? {
var lines: [String] = []
contents.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()).enumerateLines { line, stop in lines.append(line) }
if lines.count < 1 {
log.error("CSV Parser: There must be at least one line including the header.")
return nil
}
let headers = lines[0].componentsSeparatedByString(",").map({
(s : String) -> String in
return s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
})
var rows : [Dictionary<String, String>] = []
for (lineNumber, line) in enumerate(lines) {
if lineNumber == 0 {
continue
}
var row = Dictionary<String, String>()
let scanner = NSScanner(string: line)
let delimiter = ","
let doubleQuote = NSCharacterSet(charactersInString: "\"")
let whitespace = NSCharacterSet.whitespaceCharacterSet()
for (index, header) in enumerate(headers) {
scanner.scanCharactersFromSet(whitespace, intoString: nil)
var value : NSString = ""
if scanner.scanCharactersFromSet(doubleQuote, intoString: nil) {
var result : NSString?
while true {
scanner.scanUpToCharactersFromSet(doubleQuote, intoString: &result)
if result != nil {
value = value + result!
}
if scanner.scanString("\"\"", intoString: nil) {
value = value + "\""
} else {
scanner.scanCharactersFromSet(doubleQuote, intoString: nil)
break
}
}
} else {
var result : NSString?
// Case where value is not quoted
scanner.scanUpToString(delimiter, intoString: &result)
if result != nil {
value = result!
}
}
// Trim whitespace
var trimmedVal = value.stringByTrimmingCharactersInSet(whitespace)
// If value is non-empty store it in the row
if !trimmedVal.isEmpty {
row[header] = trimmedVal
}
// Remove whitespace and comma
scanner.scanCharactersFromSet(whitespace, intoString: nil)
scanner.scanString(delimiter, intoString: nil)
}
rows.append(row)
}
return (headers, rows)
}
func parseFromFile(path : String) -> (headers: [String], rows: [Dictionary<String,String>])? {
if let contents = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
return parse(contents)
} else {
log.error("CSV Parser: Unable to read CSV file.")
return nil
}
}
} | mit | 387799f4c7bc747a01f912b35a15b883 | 36.141414 | 138 | 0.507889 | 5.708075 | false | false | false | false |
Fitbit/RxBluetoothKit | Tests/Autogenerated/_Peripheral+Convenience.generated.swift | 2 | 18249 | import Foundation
import CoreBluetooth
@testable import RxBluetoothKit
import RxSwift
// swiftlint:disable line_length
extension _Peripheral {
/// Function used to receive service with given identifier. It's taken from cache if it's available,
/// or directly by `discoverServices` call
/// - Parameter identifier: Unique identifier of _Service
/// - Returns: `Single` which emits `next` event, when specified service has been found.
///
/// Observable can ends with following errors:
/// * `RxError.noElements`
/// * `_BluetoothError.servicesDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func service(with identifier: ServiceIdentifier) -> Single<_Service> {
return .deferred { [weak self] in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
if let services = strongSelf.services,
let service = services.first(where: { $0.uuid == identifier.uuid }) {
return .just(service)
} else {
return strongSelf.discoverServices([identifier.uuid])
.map {
if let service = $0.first {
return service
}
throw RxError.noElements
}
}
}
}
/// Function used to receive characteristic with given identifier. If it's available it's taken from cache.
/// Otherwise - directly by `discoverCharacteristics` call
/// - Parameter identifier: Unique identifier of _Characteristic, that has information
/// about service which characteristic belongs to.
/// - Returns: `Single` which emits `next` event, when specified characteristic has been found.
///
/// Observable can ends with following errors:
/// * `RxError.noElements`
/// * `_BluetoothError.characteristicsDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func characteristic(with identifier: CharacteristicIdentifier) -> Single<_Characteristic> {
return .deferred { [weak self] in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
return strongSelf.service(with: identifier.service)
.flatMap { service -> Single<_Characteristic> in
if let characteristics = service.characteristics, let characteristic = characteristics.first(where: {
$0.uuid == identifier.uuid
}) {
return .just(characteristic)
}
return service.discoverCharacteristics([identifier.uuid])
.map {
if let characteristic = $0.first {
return characteristic
}
throw RxError.noElements
}
}
}
}
/// Function used to receive descriptor with given identifier. If it's available it's taken from cache.
/// Otherwise - directly by `discoverDescriptor` call
/// - Parameter identifier: Unique identifier of _Descriptor, that has information
/// about characteristic which descriptor belongs to.
/// - Returns: `Single` which emits `next` event, when specified descriptor has been found.
///
/// Observable can ends with following errors:
/// * `RxError.noElements`
/// * `_BluetoothError.descriptorsDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func descriptor(with identifier: DescriptorIdentifier) -> Single<_Descriptor> {
return .deferred { [weak self] in
guard let strongSelf = self else { throw _BluetoothError.destroyed }
return strongSelf.characteristic(with: identifier.characteristic)
.flatMap { characteristic -> Single<_Descriptor> in
if let descriptors = characteristic.descriptors,
let descriptor = descriptors.first(where: { $0.uuid == identifier.uuid }) {
return .just(descriptor)
}
return characteristic.discoverDescriptors()
.map {
if let descriptor = $0.filter({ $0.uuid == identifier.uuid }).first {
return descriptor
}
throw RxError.noElements
}
}
}
}
/// Function that allow to observe writes that happened for characteristic.
/// - Parameter identifier: Identifier of characteristic of which value writes should be observed.
/// - Returns: Observable that emits `next` with `_Characteristic` instance every time when write has happened.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeWrite(for identifier: CharacteristicIdentifier)
-> Observable<_Characteristic> {
return characteristic(with: identifier)
.asObservable()
.flatMap { [weak self] in
self?.observeWrite(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made.
/// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/documentation/corebluetooth/cbcharacteristicwritetype),
/// so be sure to check this out before usage of the method.
/// - parameter data: Data that'll be written written to `_Characteristic` instance
/// - parameter forCharacteristicWithIdentifier: unique identifier of characteristic, which also holds information about service characteristic belongs to.
/// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse`
/// - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call.
/// Behavior is following:
/// - `WithResponse` - Observable emits `next` with `_Characteristic` instance write was confirmed without any errors.
/// Immediately after that `complete` is called. If any problem has happened, errors are emitted.
/// - `WithoutResponse` - Observable emits `next` with `_Characteristic` instance once write was called.
/// Immediately after that `.complete` is called. Result of this call is not checked, so as a user you are not sure
/// if everything completed successfully. Errors are not emitted
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func writeValue(_ data: Data, for identifier: CharacteristicIdentifier,
type: CBCharacteristicWriteType) -> Single<_Characteristic> {
return characteristic(with: identifier)
.flatMap { [weak self] in
self?.writeValue(data, for: $0, type: type) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that allow to observe value updates for `_Characteristic` instance.
/// - Parameter identifier: unique identifier of characteristic, which also holds information about service that characteristic belongs to.
/// - Returns: Observable that emits `next` with `_Characteristic` instance every time when value has changed.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdate(for identifier: CharacteristicIdentifier) -> Observable<_Characteristic> {
return characteristic(with: identifier)
.asObservable()
.flatMap { [weak self] in
self?.observeValueUpdate(for: $0).asObservable() ?? .error(_BluetoothError.destroyed)
}
}
/// Function that triggers read of current value of the `_Characteristic` instance.
/// Read is called after subscription to `Observable` is made.
/// - Parameter identifier: unique identifier of characteristic, which also holds information about service that characteristic belongs to.
/// - Returns: Observable which emits `next` with given characteristic when value is ready to read. Immediately after that
/// `.complete` is emitted.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func readValue(for identifier: CharacteristicIdentifier) -> Single<_Characteristic> {
return characteristic(with: identifier)
.flatMap { [weak self] in
self?.readValue(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Setup characteristic notification in order to receive callbacks when given characteristic has been changed.
/// Returned observable will emit `_Characteristic` on every notification change.
/// It is possible to setup more observables for the same characteristic and the lifecycle of the notification will be shared among them.
///
/// Notification is automaticaly unregistered once this observable is unsubscribed
///
/// - parameter characteristic: `_Characteristic` for notification setup.
/// - returns: `Observable` emitting `_Characteristic` when given characteristic has been changed.
///
/// This is **infinite** stream of values.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.characteristicReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdateAndSetNotification(for identifier: CharacteristicIdentifier)
-> Observable<_Characteristic> {
return characteristic(with: identifier)
.asObservable()
.flatMap { [weak self] in
self?.observeValueUpdateAndSetNotification(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that triggers descriptors discovery for characteristic
/// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to.
/// - Returns: `Single` that emits `next` with array of `_Descriptor` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorsDiscoveryFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func discoverDescriptors(for identifier: CharacteristicIdentifier) ->
Single<[_Descriptor]> {
return characteristic(with: identifier)
.flatMap { [weak self] in
self?.discoverDescriptors(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that allow to observe writes that happened for descriptor.
/// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to.
/// - Returns: Observable that emits `next` with `_Descriptor` instance every time when write has happened.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeWrite(for identifier: DescriptorIdentifier) -> Observable<_Descriptor> {
return descriptor(with: identifier)
.asObservable()
.flatMap { [weak self] in
self?.observeWrite(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made.
/// - parameter data: `Data` that'll be written to `_Descriptor` instance
/// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to.
/// - returns: `Single` that emits `next` with `_Descriptor` instance, once value is written successfully.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorWriteFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func writeValue(_ data: Data, for identifier: DescriptorIdentifier)
-> Single<_Descriptor> {
return descriptor(with: identifier)
.flatMap { [weak self] in
self?.writeValue(data, for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that allow to observe value updates for `_Descriptor` instance.
/// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to.
/// - Returns: Observable that emits `next` with `_Descriptor` instance every time when value has changed.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func observeValueUpdate(for identifier: DescriptorIdentifier) -> Observable<_Descriptor> {
return descriptor(with: identifier)
.asObservable()
.flatMap { [weak self] in
self?.observeValueUpdate(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
/// Function that triggers read of current value of the `_Descriptor` instance.
/// Read is called after subscription to `Observable` is made.
/// - Parameter identifier: `_Descriptor` to read value from
/// - Returns: Observable which emits `next` with given descriptor when value is ready to read. Immediately after that
/// `.complete` is emitted.
///
/// Observable can ends with following errors:
/// * `_BluetoothError.descriptorReadFailed`
/// * `_BluetoothError.peripheralDisconnected`
/// * `_BluetoothError.destroyed`
/// * `_BluetoothError.bluetoothUnsupported`
/// * `_BluetoothError.bluetoothUnauthorized`
/// * `_BluetoothError.bluetoothPoweredOff`
/// * `_BluetoothError.bluetoothInUnknownState`
/// * `_BluetoothError.bluetoothResetting`
func readValue(for identifier: DescriptorIdentifier) -> Single<_Descriptor> {
return descriptor(with: identifier)
.flatMap { [weak self] in
self?.readValue(for: $0) ?? .error(_BluetoothError.destroyed)
}
}
}
| apache-2.0 | 43a31722f989efcd4e89ce2017d6a840 | 50.991453 | 165 | 0.657187 | 5.603009 | false | false | false | false |
carabina/DDMathParser | MathParser/ResolvedToken.swift | 2 | 1611 | //
// ResolvedToken.swift
// DDMathParser
//
// Created by Dave DeLong on 8/8/15.
//
//
import Foundation
public struct ResolvedToken {
public enum Kind {
case Number(Double)
case Variable(String)
case Identifier(String)
case Operator(MathParser.Operator)
}
public let kind: Kind
public let string: String
public let range: Range<String.Index>
}
public extension ResolvedToken.Kind {
public var number: Double? {
guard case .Number(let o) = self else { return nil }
return o
}
public var variable: String? {
guard case .Variable(let v) = self else { return nil }
return v
}
public var identifier: String? {
guard case .Identifier(let i) = self else { return nil }
return i
}
public var resolvedOperator: MathParser.Operator? {
guard case .Operator(let o) = self else { return nil }
return o
}
public var builtInOperator: BuiltInOperator? {
return resolvedOperator?.builtInOperator
}
public var isNumber: Bool { return number != nil }
public var isVariable: Bool { return variable != nil }
public var isIdentifier: Bool { return identifier != nil }
public var isOperator: Bool { return resolvedOperator != nil }
}
public struct TokenResolverError: ErrorType {
public enum Kind {
case CannotParseHexNumber
case CannotParseLocalizedNumber
case UnknownOperator
case AmbiguousOperator
}
public let kind: Kind
public let rawToken: RawToken
}
| mit | 57b41d5aeee943fd0dd128d8806ba89d | 23.409091 | 66 | 0.632526 | 4.550847 | false | false | false | false |
nmartinson/Bluetooth-Camera-Controller | BLE Test/HelpViewController.swift | 1 | 2202 | //
// HelpViewController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 10/6/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import Foundation
import UIKit
//@objc protocol HelpViewControllerDelegate : Any{
//
// func helpViewControllerDidFinish(controller : HelpViewController)
//
//}
class HelpViewController : UIViewController {
// @IBOutlet var delegate : HelpViewControllerDelegate?
@IBOutlet var versionLabel : UILabel?
@IBOutlet var textView : UITextView?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// override init() {
// super.init()
// }
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
preferredContentSize = CGSizeMake(320.0, 480.0) //popover size on iPad
}
override func viewDidLoad() {
super.viewDidLoad()
if (IS_IPAD == true) {
self.preferredContentSize = self.view.frame.size; //popover size on iPad
}
else if (IS_IPHONE == true) {
self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
}
//Set the app version # in the Help/Info view
let versionString: String = "v" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleShortVersionString"] as! String!)
// let bundleVersionString: String = "b" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleVersion"] as String!) // Build number
// versionLabel?.text = versionString + " " + bundleVersionString
versionLabel?.text = versionString
}
override func viewDidAppear(animated : Bool){
super.viewDidAppear(animated)
textView?.flashScrollIndicators() //indicate add'l content below screen
}
// @IBAction func done(sender : AnyObject) {
//
//// delegate?.helpViewControllerDidFinish(self)
//
// }
} | bsd-3-clause | 25ab35c93975e565e2dd07d91558feb0 | 24.616279 | 147 | 0.597639 | 5.08545 | false | false | false | false |
luinily/hOme | hOme/UI/NewIRKitCommandViewController.swift | 1 | 3477 | //
// NewIRKitCommandViewController.swift
// hOme
//
// Created by Coldefy Yoann on 2016/02/27.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import UIKit
class NewIRKitCommandViewController: UITableViewController {
@IBOutlet weak var format: UILabel!
@IBOutlet weak var frequence: UILabel!
@IBOutlet weak var data: UILabel!
@IBOutlet weak var table: UITableView!
@IBOutlet weak var createButton: UIBarButtonItem!
@IBOutlet weak var nameTextField: UITextField!
private let _nameSection = 0
private let _signalSection = 1
private let _getSignalSection = 2
private let _getSignalRow = 0
private let _testCommandRow = 1
private var _command: CommandProtocol?
private var _device: DeviceProtocol?
private var _irSignal: IRKITSignal?
private var _name: String = ""
private var _onClose: (() -> Void)?
override func viewDidLoad() {
updateView()
nameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingDidEnd)
nameTextField.becomeFirstResponder()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).section == _getSignalSection {
if (indexPath as NSIndexPath).row == _getSignalRow {
getData()
} else if (indexPath as NSIndexPath).row == _testCommandRow {
testCommand()
}
tableView.cellForRow(at: indexPath)?.isSelected = false
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case _nameSection: return _device?.name
case _signalSection: return _device?.connector?.name
case _getSignalSection: return ""
default: return ""
}
}
@IBAction func cancel(_ sender: AnyObject) {
_onClose?()
self.dismiss(animated: true, completion: nil)
}
@IBAction func create(_ sender: AnyObject) {
createCommand()
_onClose?()
self.dismiss(animated: true, completion: nil)
}
func setDevice(_ device: DeviceProtocol) {
_device = device
}
func setOnClose(_ onClose: @escaping () -> Void) {
_onClose = onClose
}
func textFieldDidChange() {
if let name = nameTextField.text {
_name = name
}
updateView()
}
private func getData() {
if let irKit = _device?.connector as? IRKitConnector {
irKit.getData() {
data in
if data.hasSignal() {
self._irSignal = data
self.updateView()
}
}
}
}
private func testCommand() {
if let irKit = _device?.connector as? IRKitConnector,
let irSignal = _irSignal {
if irSignal.hasSignal() {
irKit.sendDataToIRKit(irSignal) {
}
}
}
}
private func updateView() {
if let irSignal = _irSignal {
format.text = irSignal.format
frequence.text = String(irSignal.frequence)
data.text = String(describing: irSignal.data)
} else {
format.text = "None"
frequence.text = "None"
data.text = "None"
}
createButton.isEnabled = checkInputs()
table.reloadData()
}
private func checkInputs() -> Bool {
if let irSignal = _irSignal {
return (_name != "") && irSignal.hasSignal()
}
return false
}
private func createCommand() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let device = _device,
let irSignal = _irSignal {
if let command = appDelegate.homeApplication.createNewCommand(device: device, name: _name) as? IRKitCommand {
command.setIRSignal(signal: irSignal)
_command = command
}
}
}
}
| mit | 84d7c11575d1e639c6ac8d43e3655060 | 23.293706 | 113 | 0.689407 | 3.611227 | false | false | false | false |
kesun421/firefox-ios | Sync/KeyBundle.swift | 3 | 11801 | /* 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 FxA
import Account
import SwiftyJSON
private let KeyLength = 32
open class KeyBundle: Hashable {
let encKey: Data
let hmacKey: Data
open class func fromKB(_ kB: Data) -> KeyBundle {
let salt = Data()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
let derived = (kB as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: len)!
return KeyBundle(encKey: derived.subdata(in: 0..<KeyLength),
hmacKey: derived.subdata(in: KeyLength..<(2 * KeyLength)))
}
open class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
open class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")!
}
public init?(encKeyB64: String, hmacKeyB64: String) {
guard let e = Bytes.decodeBase64(encKeyB64),
let h = Bytes.decodeBase64(hmacKeyB64) else {
return nil
}
self.encKey = e
self.hmacKey = h
}
public init(encKey: Data, hmacKey: Data) {
self.encKey = encKey
self.hmacKey = hmacKey
}
fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result)
return (result, digestLen)
}
open func hmac(_ ciphertext: Data) -> Data {
let (result, digestLen) = _hmac(ciphertext)
let data = NSMutableData(bytes: result, length: digestLen)
result.deinitialize()
return data as Data
}
/**
* Returns a hex string for the HMAC.
*/
open func hmacString(_ ciphertext: Data) -> String {
let (result, digestLen) = _hmac(ciphertext)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(hash)
}
open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
let byteCount = cleartext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return (d, iv)
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
// You *must* verify HMAC before calling this.
open func decrypt(_ ciphertext: Data, iv: Data) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
let byteCount = ciphertext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue)
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return s as String?
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) {
let resultSize = input.count + kCCBlockSizeAES128
var copied: Int = 0
let result = UnsafeMutableRawPointer.allocate(bytes: resultSize, alignedTo: MemoryLayout<Void>.size)
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.getBytes(),
kCCKeySizeAES256,
iv.getBytes(),
input.getBytes(),
input.count,
result,
resultSize,
&copied
)
return (success, result, copied)
}
open func verify(hmac: Data, ciphertextB64: Data) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return (expectedHMAC == computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
open func factory<T: CleartextPayloadJSON>(_ f: @escaping (JSON) -> T) -> (String) -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !potential.isValid() {
return nil
}
let cleartext = potential.cleartext
if cleartext == nil {
return nil
}
return f(cleartext!)
}
}
// TODO: how much do we want to move this into EncryptedJSON?
open func serializer<T: CleartextPayloadJSON>(_ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? {
return { (record: Record<T>) -> JSON? in
let json = f(record.payload)
if json.isNull() {
// This should never happen, but if it does, we don't want to leak this
// record to the server!
return nil
}
let bytes: Data
do {
// Get the most basic kind of encoding: no pretty printing.
// This can throw; if so, we return nil.
// `rawData` simply calls JSONSerialization.dataWithJSONObject:options:error, which
// guarantees UTF-8 encoded output.
bytes = try json.rawData(options: [])
} catch {
return nil
}
// Given a valid non-null JSON object, we don't ever expect a round-trip to fail.
assert(!JSON(bytes).isNull())
// We pass a null IV, which means "generate me a new one".
// We then include the generated IV in the resulting record.
if let (ciphertext, iv) = self.encrypt(bytes, iv: nil) {
// So we have the encrypted payload. Now let's build the envelope around it.
let ciphertext = ciphertext.base64EncodedString
// The HMAC is computed over the base64 string. As bytes. Yes, I know.
if let encodedCiphertextBytes = ciphertext.data(using: String.Encoding.ascii, allowLossyConversion: false) {
let hmac = self.hmacString(encodedCiphertextBytes)
let iv = iv.base64EncodedString
// The payload is stringified JSON. Yes, I know.
let payload: Any = JSON(object: ["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringValue()! as Any
let obj = ["id": record.id,
"sortindex": record.sortindex,
// This is how SwiftyJSON wants us to express a null that we want to
// serialize. Yes, this is gross.
"ttl": record.ttl ?? NSNull(),
"payload": payload]
return JSON(object: obj)
}
}
return nil
}
}
open func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
open var hashValue: Int {
return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue
}
}
public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return (lhs.encKey == rhs.encKey) &&
(lhs.hmacKey == rhs.hmacKey)
}
open class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload, payload.isValid() {
if let keys = payload.defaultKeys {
self.defaultBundle = keys
self.collectionKeys = payload.collectionKeys
self.valid = true
return
}
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
open class func random() -> Keys {
return Keys(defaultBundle: KeyBundle.random())
}
open func forCollection(_ collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
open func encrypter<T>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> {
return RecordEncrypter(bundle: forCollection(collection), encoder: encoder)
}
open func asPayload() -> KeysPayload {
let json: JSON = JSON([
"id": "keys",
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, f: { $0.asPair() })
])
return KeysPayload(json)
}
}
/**
* Yup, these are basically typed tuples.
*/
public struct RecordEncoder<T: CleartextPayloadJSON> {
let decode: (JSON) -> T
let encode: (T) -> JSON
}
public struct RecordEncrypter<T: CleartextPayloadJSON> {
let serializer: (Record<T>) -> JSON?
let factory: (String) -> T?
init(bundle: KeyBundle, encoder: RecordEncoder<T>) {
self.serializer = bundle.serializer(encoder.encode)
self.factory = bundle.factory(encoder.decode)
}
init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) {
self.serializer = serializer
self.factory = factory
}
}
public func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
| mpl-2.0 | 7b5c86f848e53709743f5ad14c37d510 | 36.227129 | 144 | 0.594017 | 4.651557 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/Categories/UINavigationController+StripeIdentity.swift | 1 | 2824 | //
// UINavigationController+StripeIdentity.swift
// StripeIdentity
//
// Created by Jaime Park on 2/10/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeUICore
import UIKit
extension UINavigationController {
func configureBorderlessNavigationBar() {
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.copyButtonAppearance(from: UINavigationBar.appearance().standardAppearance)
appearance.configureWithTransparentBackground()
navigationBar.standardAppearance = appearance
navigationBar.scrollEdgeAppearance = appearance
} else {
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
navigationBar.backgroundColor = .clear
}
}
func setNavigationBarBackgroundColor(with backgroundColor: UIColor?) {
let bgColor = backgroundColor ?? .systemBackground
if #available(iOS 13.0, *) {
navigationBar.standardAppearance.backgroundColor = bgColor
navigationBar.scrollEdgeAppearance?.backgroundColor = bgColor
} else {
navigationBar.backgroundColor = bgColor
}
}
}
@available(iOS 13.0, *)
extension UINavigationBarAppearance {
fileprivate func copyButtonAppearance(from other: UINavigationBarAppearance) {
// Button appearances will be undefined if using the default configuration.
// Copying the default undefined configuration will result in an
// NSInternalInconsistencyException. We can check for undefined by
// copying the values to an optional type and checking for nil.
let otherButtonAppearance: UIBarButtonItemAppearance? = other.buttonAppearance
let otherDoneButtonAppearance: UIBarButtonItemAppearance? = other.doneButtonAppearance
let otherBackButtonAppearance: UIBarButtonItemAppearance? = other.backButtonAppearance
if let otherButtonAppearance = otherButtonAppearance {
buttonAppearance = otherButtonAppearance
} else {
buttonAppearance.configureWithDefault(for: .plain)
}
if let otherDoneButtonAppearance = otherDoneButtonAppearance {
doneButtonAppearance = otherDoneButtonAppearance
} else {
doneButtonAppearance.configureWithDefault(for: .done)
}
if let otherBackButtonAppearance = otherBackButtonAppearance {
backButtonAppearance = otherBackButtonAppearance
} else {
backButtonAppearance.configureWithDefault(for: .plain)
}
setBackIndicatorImage(
other.backIndicatorImage,
transitionMaskImage: other.backIndicatorTransitionMaskImage
)
}
}
| mit | ea212c3b97f88086f2ce9bc2a8d0aacc | 38.208333 | 98 | 0.695005 | 6.177243 | false | true | false | false |
GraphKit/MaterialKit | Sources/iOS/Button.swift | 1 | 8926 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class Button: UIButton, Pulseable {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/// A Pulse reference.
fileprivate var pulse: Pulse!
/// PulseAnimation value.
open var pulseAnimation: PulseAnimation {
get {
return pulse.animation
}
set(value) {
pulse.animation = value
}
}
/// PulseAnimation color.
@IBInspectable
open var pulseColor: UIColor {
get {
return pulse.color
}
set(value) {
pulse.color = value
}
}
/// Pulse opacity.
@IBInspectable
open var pulseOpacity: CGFloat {
get {
return pulse.opacity
}
set(value) {
pulse.opacity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/// A preset property for updated contentEdgeInsets.
open var contentEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// Sets the normal and highlighted image for the button.
@IBInspectable
open var image: UIImage? {
didSet {
setImage(image, for: .normal)
setImage(image, for: .highlighted)
}
}
/// Sets the normal and highlighted title for the button.
@IBInspectable
open var title: String? {
didSet {
setTitle(title, for: .normal)
setTitle(title, for: .highlighted)
guard nil != title else {
return
}
guard nil == titleColor else {
return
}
titleColor = Color.blue.base
}
}
/// Sets the normal and highlighted titleColor for the button.
@IBInspectable
open var titleColor: UIColor? {
didSet {
setTitleColor(titleColor, for: .normal)
setTitleColor(titleColor, for: .highlighted)
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
tintColor = Color.blue.base
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
tintColor = Color.blue.base
prepare()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
/**
A convenience initializer that acceps an image and tint
- Parameter image: A UIImage.
- Parameter tintColor: A UI
*/
public convenience init(image: UIImage?, tintColor: UIColor = Color.blue.base) {
self.init()
prepare(with: image, tintColor: tintColor)
prepare()
}
/**
A convenience initializer that acceps a title and title
- Parameter title: A String.
- Parameter titleColor: A UI
*/
public convenience init(title: String?, titleColor: UIColor = Color.blue.base) {
self.init()
prepare(with: title, titleColor: titleColor)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Triggers the pulse animation.
- Parameter point: A Optional point to pulse from, otherwise pulses
from the center.
*/
open func pulse(point: CGPoint? = nil) {
let p = point ?? center
pulse.expandAnimation(point: p)
Animation.delay(time: 0.35) { [weak self] in
self?.pulse.contractAnimation()
}
}
/**
A delegation method that is executed when the view has began a
touch event.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
pulse.expandAnimation(point: layer.convert(touches.first!.location(in: self), from: layer))
}
/**
A delegation method that is executed when the view touch event has
ended.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
pulse.contractAnimation()
}
/**
A delegation method that is executed when the view touch event has
been cancelled.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
pulse.contractAnimation()
}
open func bringImageViewToFront() {
guard let v = imageView else {
return
}
bringSubview(toFront: v)
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
prepareVisualLayer()
preparePulse()
}
}
extension Button {
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
/// Prepares the pulse motion.
fileprivate func preparePulse() {
pulse = Pulse(pulseView: self, pulseLayer: visualLayer)
}
/**
Prepares the Button with an image and tint
- Parameter image: A UIImage.
- Parameter tintColor: A UI
*/
fileprivate func prepare(with image: UIImage?, tintColor: UIColor) {
self.image = image
self.tintColor = tintColor
}
/**
Prepares the Button with a title and title
- Parameter title: A String.
- Parameter titleColor: A UI
*/
fileprivate func prepare(with title: String?, titleColor: UIColor) {
self.title = title
self.titleColor = titleColor
}
}
extension Button {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| agpl-3.0 | 0f7cb4b1efab2c42d04e2d195e7c9bc1 | 29.360544 | 99 | 0.641497 | 4.896325 | false | false | false | false |
ECP-CANDLE/Supervisor | workflows/common/swift/log_app.swift | 1 | 1143 |
// LOG APP
(void o) log_start(string algorithm) {
file out<turbine_output/"log_start_out.txt">;
file err<turbine_output/"log_start_err.txt">;
string ps = join(file_lines(input(param_set)), " ");
string t_log = turbine_output/"turbine.log";
if (file_exists(t_log)) {
string sys_env = join(file_lines(input(t_log)), ", ");
(out, err) = run_log_start(log_runner, ps, sys_env, algorithm, site) =>
o = propagate();
} else {
(out, err) = run_log_start(log_runner, ps, "", algorithm, site) =>
o = propagate();
}
}
(void o) log_end() {
file out <"%s/log_end_out.txt" % turbine_output>;
file err <"%s/log_end_err.txt" % turbine_output>;
(out, err) = run_log_end(log_runner, site) =>
o = propagate();
}
app (file out, file err) run_log_start(file shfile, string ps, string sys_env, string algorithm, string site)
{
"bash" shfile "start" emews_root propose_points max_iterations ps algorithm exp_id sys_env site @stdout=out @stderr=err;
}
app (file out, file err) run_log_end(file shfile, string site)
{
"bash" shfile "end" emews_root exp_id site @stdout=out @stderr=err;
}
| mit | feaead2e4c55032ab1fdad61a74c1ea2 | 31.657143 | 124 | 0.628171 | 2.901015 | false | false | true | false |
CoderSLZeng/SLWeiBo | SLWeiBo/SLWeiBo/Classes/Home/Controller/HomeTableViewController.swift | 1 | 10947 | //
// HomeTableViewController.swift
// SLWeiBo
//
// Created by Anthony on 17/3/6.
// Copyright © 2017年 SLZeng. All rights reserved.
//
import UIKit
import SDWebImage
import MJRefresh
class HomeTableViewController: BaseTableViewController {
// MARK: - 懒加载属性
/// 标题按钮
fileprivate lazy var titleBtn : TitleButton = TitleButton()
/*
注意:在闭包中如果使用当前对象的属性或者调用方法,也需要加self
两个地方需要使用self : 1> 如果在一个函数中出现歧义 2> 在闭包中使用当前对象的属性和方法也需要加self
*/
/// 转场动画
fileprivate lazy var popoverAnimator : PopoverAnimator = PopoverAnimator { [weak self] (presented) in
self?.titleBtn.isSelected = presented
}
/// 微博视图模型
fileprivate lazy var viewModels : [StatusViewModel] = [StatusViewModel]()
/// 更新微博提示框
fileprivate lazy var tipLabel : UILabel = UILabel()
/// 自定义渐变的转场动画
fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
// MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 1.判断用户是否登录
if !isLogin
{
// 设置访客视图
visitorView.setupVisitorViewInfo(nil, title: "关注一些人,回这里看看有什么惊喜")
return
}
// 2.设置导航条
setupNavigationBar()
// 3.设置预估高度值
tableView.estimatedRowHeight = 200
// 4.设置头部刷新控件
setupRefreshHeaderView()
// 5.设置底部刷新控件
setupRefreshFooterView()
// 6.设置更新微博提示框
setupTipLabel()
// 6.监听通知
setupNatifications()
}
}
// MARK: - 设置UI界面
extension HomeTableViewController
{
/**
设置导航条
*/
fileprivate func setupNavigationBar()
{
// 1.添加左右按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftBtnClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightBtnClick))
// 2.添加标题按钮
// 获取用户名称
let title = UserAccountViewModel.shareIntance.account?.screen_name ?? "CoderSLZeng"
titleBtn.setTitle(title + " ", for: UIControlState())
titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), for: .touchUpInside)
navigationItem.titleView = titleBtn
}
/**
设置头部刷新控件
*/
fileprivate func setupRefreshHeaderView() {
// 1.创建headerView
let refreshHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadNewStatuses))
// 2.设置header的属性
refreshHeader?.setTitle("下拉刷新", for: .idle)
refreshHeader?.setTitle("释放更新", for: .pulling)
refreshHeader?.setTitle("加载中...", for: .refreshing)
// 3.设置tableView的header
tableView.mj_header = refreshHeader
// 4.进入刷新状态
tableView.mj_header.beginRefreshing()
}
/**
设置底部刷新控件
*/
fileprivate func setupRefreshFooterView() {
tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadMoreStatuses))
}
/**
设置更新微博提示框
*/
fileprivate func setupTipLabel() {
// 1.添加父控件中
navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
// 2.设置边框尺寸
tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
// 3.设置属性
tipLabel.backgroundColor = UIColor.orange
tipLabel.textColor = UIColor.white
tipLabel.font = UIFont.systemFont(ofSize: 14)
tipLabel.textAlignment = .center
tipLabel.isHidden = true
}
fileprivate func setupNatifications() {
NotificationCenter.default.addObserver(self, selector: #selector(HomeTableViewController.showPhotoBrowser(_:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
}
}
// MARK: - 监听事件处理
extension HomeTableViewController
{
@objc fileprivate func leftBtnClick()
{
myLog("")
}
@objc fileprivate func rightBtnClick()
{
// 1.创建二维码控制器
let sb = UIStoryboard(name: "QRCode", bundle: nil)
let vc = sb.instantiateInitialViewController()!
// 2.弹出二维码控制器
present(vc, animated: true, completion: nil)
}
@objc fileprivate func titleBtnClick(_ button: TitleButton)
{
// 1.创建弹出的控制器
let popoverVc = PopoverViewController()
// 2.设置控制器的modal样式
popoverVc.modalPresentationStyle = .custom
// 3.设置转场的代理
popoverVc.transitioningDelegate = popoverAnimator
// 4.设置展示出来的尺寸
popoverAnimator.presentedFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
// 5.弹出控制器
present(popoverVc, animated: true, completion: nil)
}
@objc fileprivate func showPhotoBrowser(_ note : Notification) {
// 0.取出数据
let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! IndexPath
let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey] as! [URL]
let object = note.object as! PicCollectionView
// 1.创建控制器
let photoBrowserVc = PhotoBrowserController(indexPath: indexPath, picURLs: picURLs)
// 2.设置modal样式
photoBrowserVc.modalPresentationStyle = .custom
// 3.设置转场的代理
photoBrowserVc.transitioningDelegate = photoBrowserAnimator
// 4.设置动画的代理
photoBrowserAnimator.presentedDelegate = object
photoBrowserAnimator.indexPath = indexPath
photoBrowserAnimator.dismissDelegate = photoBrowserVc
// 5.以modal的形式弹出控制器
present(photoBrowserVc, animated: true, completion: nil)
}
/// 加载最新的数据
@objc fileprivate func loadNewStatuses() {
loadStatuses(true)
}
/// 加载更多的数据
@objc fileprivate func loadMoreStatuses() {
loadStatuses(false)
}
}
// MARK:- 请求数据
extension HomeTableViewController {
/// 加载微博数据
fileprivate func loadStatuses(_ isNewData : Bool) {
// 1.获取since_id/max_id
var since_id = 0
var max_id = 0
if isNewData {
since_id = viewModels.first?.status?.mid ?? 0
} else {
max_id = viewModels.last?.status?.mid ?? 0
max_id = max_id == 0 ? 0 : (max_id - 1)
}
// 2.请求数据
NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (result, error) -> () in
// 1.错误校验
if error != nil {
myLog(error)
return
}
// 2.获取可选类型中的数据
guard let resultArray = result else {
return
}
// 3.遍历微博对应的字典
var tempViewModel = [StatusViewModel]()
for statusDict in resultArray {
let status = Status(dict: statusDict)
let viewModel = StatusViewModel(status: status)
tempViewModel.append(viewModel)
}
// 4.将数据放入到成员变量的数组中
if isNewData {
self.viewModels = tempViewModel + self.viewModels
} else {
self.viewModels += tempViewModel
}
// 5.缓存图片
self.cacheImages(tempViewModel)
}
}
/**
缓存图片
*/
fileprivate func cacheImages(_ viewModels : [StatusViewModel]) {
// 0.创建group
let group = DispatchGroup()
// 1.缓存图片
for viewmodel in viewModels {
for picURL in viewmodel.picURLs {
group.enter()
SDWebImageManager.shared().loadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
group.leave()
})
}
}
// 2.刷新表格
group.notify(queue: DispatchQueue.main) { () -> Void in
self.tableView.reloadData()
// 停止刷新
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
// 显示更新微博提示框
self.showTipLabel(viewModels.count)
}
}
/// 显示更新微博提示的框
fileprivate func showTipLabel(_ count : Int) {
// 1.设置属性
tipLabel.isHidden = false
tipLabel.text = count == 0 ? "没有更新的微博" : "更新了\(count) 条形微博"
// 2.执行动画
UIView.animate(withDuration: 1.0, animations: { () -> Void in
self.tipLabel.frame.origin.y = 44
}, completion: { (_) -> Void in
UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { () -> Void in
self.tipLabel.frame.origin.y = 10
}, completion: { (_) -> Void in
self.tipLabel.isHidden = true
})
})
}
}
// MARK:- tableView的数据源方法
extension HomeTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModels.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 1.创建cell
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell
// 2.给cell设置数据
cell.viewModel = viewModels[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// 1.获取模型对象
let viewModel = viewModels[indexPath.row]
return viewModel.cellHeight
}
}
| mit | 460ac0ad644d6e1ef92b4454ee9e56e9 | 28.927492 | 191 | 0.581264 | 4.997982 | false | false | false | false |
hollance/swift-algorithm-club | CounterClockWise/CounterClockWise.playground/Contents.swift | 2 | 2335 | /*
CounterClockWise(CCW) Algorithm
The user cross-multiplies corresponding coordinates to find the area encompassing the polygon,
and subtracts it from the surrounding polygon to find the area of the polygon within.
This code is based on the "Shoelace formula" by Carl Friedrich Gauss
https://en.wikipedia.org/wiki/Shoelace_formula
*/
import Foundation
// MARK : Point struct for defining 2-D coordinate(x,y)
public struct Point{
// Coordinate(x,y)
var x: Int
var y: Int
public init(x: Int ,y: Int){
self.x = x
self.y = y
}
}
// MARK : Function that determine the area of a simple polygon whose vertices are described
// by their Cartesian coordinates in the plane.
func ccw(points: [Point]) -> Int{
let polygon = points.count
var orientation = 0
// Take the first x-coordinate and multiply it by the second y-value,
// then take the second x-coordinate and multiply it by the third y-value,
// and repeat as many times until it is done for all wanted points.
for i in 0..<polygon{
orientation += (points[i%polygon].x*points[(i+1)%polygon].y
- points[(i+1)%polygon].x*points[i%polygon].y)
}
// If the points are labeled sequentially in the counterclockwise direction,
// then the sum of the above determinants is positive and the absolute value signs can be omitted
// if they are labeled in the clockwise direction, the sum of the determinants will be negative.
// This is because the formula can be viewed as a special case of Green's Theorem.
switch orientation {
case Int.min..<0:
return -1 // if operation < 0 : ClockWise
case 0:
return 0 // if operation == 0 : Parallel
default:
return 1 // if operation > 0 : CounterClockWise
}
}
// A few simple tests
// Triangle
var p1 = Point(x: 5, y: 8)
var p2 = Point(x: 9, y: 1)
var p3 = Point(x: 3, y: 6)
print(ccw(points: [p1,p2,p3])) // -1 means ClockWise
// Quadrilateral
var p4 = Point(x: 5, y: 8)
var p5 = Point(x: 2, y: 3)
var p6 = Point(x: 6, y: 1)
var p7 = Point(x: 9, y: 3)
print(ccw(points: [p4,p5,p6,p7])) // 1 means CounterClockWise
// Pentagon
var p8 = Point(x: 5, y: 11)
var p9 = Point(x: 3, y: 4)
var p10 = Point(x: 5, y: 6)
var p11 = Point(x: 9, y: 5)
var p12 = Point(x: 12, y: 8)
print(ccw(points: [p8,p9,p10,p11,p12])) // 1 means CounterClockWise
| mit | 4709b9fc8499ed72eee6e5b022d27fea | 29.723684 | 99 | 0.672805 | 3.234072 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift | 2 | 3825 | //
// Signal+Subscription.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy {
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter to: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E {
return self.asSharedSequence().asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter to: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E? {
return self.asSharedSequence().asObservable().map { $0 as E? }.subscribe(observer)
}
/**
Creates new subscription and sends elements to `BehaviorRelay`.
- parameter relay: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the relay.
*/
public func emit(to relay: BehaviorRelay<E>) -> Disposable {
return self.emit(onNext: { e in
relay.accept(e)
})
}
/**
Creates new subscription and sends elements to `BehaviorRelay`.
- parameter relay: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the relay.
*/
public func emit(to relay: BehaviorRelay<E?>) -> Disposable {
return self.emit(onNext: { e in
relay.accept(e)
})
}
/**
Creates new subscription and sends elements to relay.
- parameter relay: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the relay.
*/
public func emit(to relay: PublishRelay<E>) -> Disposable {
return self.emit(onNext: { e in
relay.accept(e)
})
}
/**
Creates new subscription and sends elements to relay.
- parameter to: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the relay.
*/
public func emit(to relay: PublishRelay<E?>) -> Disposable {
return self.emit(onNext: { e in
relay.accept(e)
})
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
Error callback is not exposed because `Signal` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is canceled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func emit(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
}
| apache-2.0 | 0016583fbb31ea4c303d26c7cbae2ffb | 37.24 | 133 | 0.67887 | 4.896287 | false | false | false | false |
Subsets and Splits