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
LawrenceHan/iOS-project-playground
iOSRACSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Atomic.swift
29
1403
// // Atomic.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-06-10. // Copyright (c) 2014 GitHub. All rights reserved. // /// An atomic variable. public final class Atomic<Value> { private var spinLock = OS_SPINLOCK_INIT private var _value: Value /// Atomically gets or sets the value of the variable. public var value: Value { get { lock() let v = _value unlock() return v } set(newValue) { lock() _value = newValue unlock() } } /// Initializes the variable with the given initial value. public init(_ value: Value) { _value = value } private func lock() { OSSpinLockLock(&spinLock) } private func unlock() { OSSpinLockUnlock(&spinLock) } /// Atomically replaces the contents of the variable. /// /// Returns the old value. public func swap(newValue: Value) -> Value { return modify { _ in newValue } } /// Atomically modifies the variable. /// /// Returns the old value. public func modify(@noescape action: Value -> Value) -> Value { lock() let oldValue = _value _value = action(_value) unlock() return oldValue } /// Atomically performs an arbitrary action using the current value of the /// variable. /// /// Returns the result of the action. public func withValue<U>(@noescape action: Value -> U) -> U { lock() let result = action(_value) unlock() return result } }
mit
9f5a03e9ce3e57d2498b4807b6e40c09
17.959459
75
0.64861
3.372596
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift
6
1945
// // LineScatterCandleRadarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 29/7/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class LineScatterCandleRadarChartDataSet: BarLineScatterCandleBubbleChartDataSet, ILineScatterCandleRadarChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn. open var drawHorizontalHighlightIndicatorEnabled = true /// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn. open var drawVerticalHighlightIndicatorEnabled = true /// - returns: true if horizontal highlight indicator lines are enabled (drawn) open var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled } /// - returns: true if vertical highlight indicator lines are enabled (drawn) open var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled } /// Enables / disables both vertical and horizontal highlight-indicators. /// :param: enabled open func setDrawHighlightIndicators(_ enabled: Bool) { drawHorizontalHighlightIndicatorEnabled = enabled drawVerticalHighlightIndicatorEnabled = enabled } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> Any { let copy = super.copyWithZone(zone) as! LineScatterCandleRadarChartDataSet copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled return copy } }
mit
7154ed5204684bcb83ff529036c1b466
35.698113
122
0.743445
5.911854
false
false
false
false
Acidburn0zzz/firefox-ios
Sync/CleartextPayloadJSON.swift
1
1674
/* 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 SwiftyJSON open class BasePayloadJSON { let json: JSON required public init(_ jsonString: String) { self.json = JSON(parseJSON: jsonString) } public init(_ json: JSON) { self.json = json } // Override me. public func isValid() -> Bool { return self.json.type != .unknown && self.json.error == nil } subscript(key: String) -> JSON { get { return json[key] } } } /** * http://docs.services.mozilla.com/sync/objectformats.html * "In addition to these custom collection object structures, the * Encrypted DataObject adds fields like id and deleted." */ open class CleartextPayloadJSON: BasePayloadJSON { required public override init(_ json: JSON) { super.init(json) } required public init(_ jsonString: String) { super.init(jsonString) } // Override me. override open func isValid() -> Bool { return super.isValid() && self["id"].isString() } open var id: String { return self["id"].string! } open var deleted: Bool { let d = self["deleted"] if let bool = d.bool { return bool } else { return false } } // Override me. // Doesn't check id. Should it? open func equalPayloads (_ obj: CleartextPayloadJSON) -> Bool { return self.deleted == obj.deleted } }
mpl-2.0
e3dcf5d67e84f86108786e6e7c7c3015
23.26087
70
0.595579
4.216625
false
false
false
false
icanzilb/Languages
4-Challenge/Languages-4/Languages/ViewController.swift
1
11467
/* * Copyright (c) 2015 Razeware LLC * * 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 // MARK: constants let kDeselectedDetailsText = "Managing to fluently transmit your thoughts and have daily conversations" let kSelectedDetailsText = "Excercises: 67%\nConversations: 50%\nDaily streak: 4\nCurrent grade: B" // MARK: - ViewController class ViewController: UIViewController { @IBOutlet var speakingTrailing: NSLayoutConstraint! var understandButton: UIButton! // MARK: IB outlets @IBOutlet var speakingDetails: UILabel! @IBOutlet var understandingImage: UIImageView! @IBOutlet var readingImage: UIImageView! @IBOutlet var speakingView: UIView! @IBOutlet var understandingView: UIView! @IBOutlet var readingView: UIView! // MARK: class properties var views: [UIView]! var selectedView: UIView? var deselectCurrentView: (()->())? // MARK: - view controller methods override func viewDidLoad() { super.viewDidLoad() views = [speakingView, readingView, understandingView] let speakingTap = UITapGestureRecognizer(target: self, action: Selector("toggleSpeaking:")) speakingView.addGestureRecognizer(speakingTap) let readingTap = UITapGestureRecognizer(target: self, action: Selector("toggleReading:")) readingView.addGestureRecognizer(readingTap) let understandingTap = UITapGestureRecognizer(target: self, action: Selector("toggleUnderstanding:")) understandingView.addGestureRecognizer(understandingTap) } // MARK: - auto layout animation func adjustHeights(viewToSelect: UIView, shouldSelect: Bool) { println("tapped: \(viewToSelect) select: \(shouldSelect)") var newConstraints: [NSLayoutConstraint] = [] for constraint in viewToSelect.superview!.constraints() as [NSLayoutConstraint] { if contains(views, constraint.firstItem as UIView) && constraint.firstAttribute == .Height { println("height constraint found") NSLayoutConstraint.deactivateConstraints([constraint]) var multiplier: CGFloat = 0.34 if shouldSelect { multiplier = (viewToSelect == constraint.firstItem as UIView) ? 0.55 : 0.23 } let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .Height, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .Height, multiplier: multiplier, constant: 0.0) newConstraints.append(con) } } NSLayoutConstraint.activateConstraints(newConstraints) } // deselects any selected views and selects the tapped view func toggleView(tap: UITapGestureRecognizer) { let wasSelected = selectedView==tap.view! adjustHeights(tap.view!, shouldSelect: !wasSelected) selectedView = wasSelected ? nil : tap.view! if !wasSelected { UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState, animations: { self.deselectCurrentView?() self.deselectCurrentView = nil }, completion: nil) } UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) } //speaking func updateSpeakingDetails(#selected: Bool) { speakingDetails.text = selected ? kSelectedDetailsText : kDeselectedDetailsText for constraint in speakingDetails.superview!.constraints() as [NSLayoutConstraint] { if constraint.firstItem as UIView == speakingDetails && constraint.firstAttribute == .Leading { constraint.constant = -view.frame.size.width/2 speakingView.layoutIfNeeded() UIView.animateWithDuration(0.5, delay: 0.1, options: .CurveEaseOut, animations: { constraint.constant = 0.0 self.speakingView.layoutIfNeeded() }, completion: nil) break } } } func toggleSpeaking(tap: UITapGestureRecognizer) { toggleView(tap) let isSelected = (selectedView==tap.view!) UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn, animations: { self.speakingTrailing.constant = isSelected ? self.speakingView.frame.size.width/2.0 : 0.0 self.updateSpeakingDetails(selected: isSelected) }, completion: nil) deselectCurrentView = { self.speakingTrailing.constant = 0.0 self.updateSpeakingDetails(selected: false) } } //reading func toggleReading(tap: UITapGestureRecognizer) { toggleView(tap) let isSelected = (selectedView==tap.view!) toggleReadingImageSize(readingImage, isSelected: isSelected) UIView.animateWithDuration(0.5, delay: 0.1, options: .CurveEaseOut, animations: { self.readingView.layoutIfNeeded() }, completion: nil) deselectCurrentView = { self.toggleReadingImageSize(self.readingImage, isSelected: false) } } func toggleReadingImageSize(imageView: UIImageView, isSelected: Bool) { for constraint in imageView.superview!.constraints() as [NSLayoutConstraint] { if constraint.firstItem as UIView == imageView && constraint.firstAttribute == .Height { NSLayoutConstraint.deactivateConstraints([constraint]) let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .Height, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .Height, multiplier: isSelected ? 0.33 : 0.67, constant: 0.0) con.active = true } } } //understanding func toggleUnderstanding(tap: UITapGestureRecognizer) { toggleView(tap) let isSelected = (selectedView==tap.view!) toggleUnderstandingImageViewSize(understandingImage, isSelected: isSelected) UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { self.understandingImage.alpha = isSelected ? 0.33 : 1.0 self.understandingImage.superview!.layoutIfNeeded() }, completion: nil) deselectCurrentView = { self.toggleUnderstandingImageViewSize(self.understandingImage, isSelected: false) self.understandingImage.alpha = 1.0 self.hideUnderstandingButton() } showUnderstandingButton(isSelected) } func hideUnderstandingButton() { UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseOut | .BeginFromCurrentState, animations: { self.understandButton.alpha = 0.0 }, completion: nil) } func showUnderstandingButton(isSelected: Bool) { if !isSelected { hideUnderstandingButton() return } understandButton?.removeFromSuperview() understandButton = UIButton.buttonWithType(.Custom) as UIButton understandButton.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.9) understandButton.setTitleColor(UIColor.blackColor(), forState: .Normal) understandButton.setTitle("Start excercise", forState: .Normal) understandButton.layer.cornerRadius = 10.0 understandButton.layer.masksToBounds = true understandButton.setTranslatesAutoresizingMaskIntoConstraints(false) understandingView.addSubview(understandButton) let conX = NSLayoutConstraint(item: understandButton, attribute: .CenterX, relatedBy: .Equal, toItem: understandingView, attribute: .CenterX, multiplier: 1.0, constant: 0.0) let conY = NSLayoutConstraint(item: understandButton, attribute: .Bottom, relatedBy: .Equal, toItem: understandingView, attribute: .Bottom, multiplier: 0.75, constant: understandingView.frame.size.height) let conWidth = NSLayoutConstraint(item: understandButton, attribute: .Width, relatedBy: .Equal, toItem: understandingView, attribute: .Width, multiplier: 0.5, constant: 0.0) let conHeight = NSLayoutConstraint(item: understandButton, attribute: .Height, relatedBy: .Equal, toItem: understandButton, attribute: .Width, multiplier: 0.25, constant: 0.0) NSLayoutConstraint.activateConstraints([conX, conY, conWidth, conHeight]) understandButton.layoutIfNeeded() UIView.animateWithDuration(1.33, delay: 0.1, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: .BeginFromCurrentState, animations: { conY.constant = 0.0 self.understandButton.layoutIfNeeded() }, completion: nil) } func toggleUnderstandingImageViewSize(imageView: UIImageView, isSelected: Bool) { var newConstraints: [NSLayoutConstraint] = [] for constraint in imageView.superview!.constraints() as [NSLayoutConstraint] { if constraint.firstItem as UIView == imageView && constraint.firstAttribute == .Height { //remove existing height constraint NSLayoutConstraint.deactivateConstraints([constraint]) //add new height constraint let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .Height, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .Height, multiplier: isSelected ? 1.6 : 0.45, constant: 0.0) newConstraints.append(con) } if constraint.firstItem as UIView == imageView && constraint.firstAttribute == .CenterY { //remove existing vertical constraint NSLayoutConstraint.deactivateConstraints([constraint]) //add new vertical constraint let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .CenterY, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .CenterY, multiplier: isSelected ? 1.8 : 0.75, constant: 0.0) newConstraints.append(con) } } NSLayoutConstraint.activateConstraints(newConstraints) } }
mit
fc2986d4c8b4b6adbd7e77b22419e3d6
35.519108
208
0.684312
4.979158
false
false
false
false
IngmarStein/swift
test/ClangModules/objc_bridging_generics.swift
4
14814
// RUN: %target-swift-frontend -sdk %S/../Inputs/clang-importer-sdk -I %S/../Inputs/clang-importer-sdk/swift-modules -enable-source-import -parse -parse-as-library -verify %s // REQUIRES: objc_interop import Foundation import objc_generics func testNSArrayBridging(_ hive: Hive) { _ = hive.bees as [Bee] } func testNSDictionaryBridging(_ hive: Hive) { _ = hive.beesByName as [String : Bee] // expected-error{{value of optional type '[String : Bee]?' not unwrapped; did you mean to use '!' or '?'?}} var dict1 = hive.anythingToBees let dict2: [AnyHashable : Bee] = dict1 dict1 = dict2 } func testNSSetBridging(_ hive: Hive) { _ = hive.allBees as Set<Bee> } public func expectType<T>(_: T.Type, _ x: inout T) {} func testNSMutableDictionarySubscript( _ dict: NSMutableDictionary, key: NSCopying, value: Any) { var oldValue = dict[key] expectType(Optional<Any>.self, &oldValue) dict[key] = value } class C {} struct S {} func f(_ x: GenericClass<NSString>) -> NSString? { return x.thing() } func f1(_ x: GenericClass<NSString>) -> NSString? { return x.otherThing() } func f2(_ x: GenericClass<NSString>) -> Int32 { return x.count() } func f3(_ x: GenericClass<NSString>) -> NSString? { return x.propertyThing } func f4(_ x: GenericClass<NSString>) -> [NSString] { return x.arrayOfThings() } func f5(_ x: GenericClass<C>) -> [C] { return x.arrayOfThings() } func f6(_ x: GenericSubclass<NSString>) -> NSString? { return x.thing() } func f6(_ x: GenericSubclass<C>) -> C? { return x.thing() } func g() -> NSString? { return GenericClass<NSString>.classThing() } func g1() -> NSString? { return GenericClass<NSString>.otherClassThing() } func h(_ s: NSString?) -> GenericClass<NSString> { return GenericClass(thing: s) } func j(_ x: GenericClass<NSString>?) { takeGenericClass(x) } class Desk {} class Rock: NSObject, Pettable { required init(fur: Any) {} func other() -> Self { return self } class func adopt() -> Self { fatalError("") } func pet() {} func pet(with other: Pettable) {} class var needingMostPets: Pettable { get { fatalError("") } set { } } } class Porcupine: Animal { } class Cat: Animal, Pettable { required init(fur: Any) {} func other() -> Self { return self } class func adopt() -> Self { fatalError("") } func pet() {} func pet(with other: Pettable) {} class var needingMostPets: Pettable { get { fatalError("") } set { } } } func testImportedTypeParamRequirements() { let _ = PettableContainer<Desk>() // expected-error{{type 'Desk' does not conform to protocol 'Pettable'}} let _ = PettableContainer<Rock>() let _ = PettableContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}} let _ = PettableContainer<Cat>() let _ = AnimalContainer<Desk>() // expected-error{{'AnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}} let _ = AnimalContainer<Rock>() // expected-error{{'AnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}} let _ = AnimalContainer<Porcupine>() let _ = AnimalContainer<Cat>() let _ = PettableAnimalContainer<Desk>() // expected-error{{'PettableAnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}} let _ = PettableAnimalContainer<Rock>() // expected-error{{'PettableAnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}} let _ = PettableAnimalContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}} let _ = PettableAnimalContainer<Cat>() } extension GenericClass { func doesntUseGenericParam() {} @objc func doesntUseGenericParam2() -> Self {} // Doesn't use 'T', since ObjC class type params are type-erased func doesntUseGenericParam3() -> GenericClass<T> {} // Doesn't use 'T', since its metadata isn't necessary to pass around instance @objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) -> T { _ = x _ = y return x } // Doesn't use 'T', since its metadata isn't necessary to erase to AnyObject // or to existential metatype func doesntUseGenericParam5(_ x: T, _ y: T.Type) -> T { _ = y as AnyObject.Type _ = y as Any.Type _ = y as AnyObject _ = x as AnyObject } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamD(_ x: Int) { _ = T.self // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamE(_ x: Int) { _ = x as? T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamF(_ x: Int) { _ = x is T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamG(_ x: T) { _ = T.self // expected-note{{used here}} } func doesntUseGenericParamH(_ x: T) { _ = x as Any } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamI(_ y: T.Type) { _ = y as Any // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamJ() -> [(T, T)]? {} // expected-note{{used here}} static func doesntUseGenericParam() {} static func doesntUseGenericParam2() -> Self {} // Doesn't technically use 'T', since it's type-erased at runtime static func doesntUseGenericParam3() -> GenericClass<T> {} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} static func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} static func usesGenericParamD(_ x: Int) { _ = T.self // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} static func usesGenericParamE(_ x: Int) { _ = x as? T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} static func usesGenericParamF(_ x: Int) { _ = x is T // expected-note{{used here}} } func checkThatMethodsAreObjC() { _ = #selector(GenericClass.doesntUseGenericParam) _ = #selector(GenericClass.doesntUseGenericParam2) _ = #selector(GenericClass.doesntUseGenericParam3) _ = #selector(GenericClass.doesntUseGenericParam4) _ = #selector(GenericClass.doesntUseGenericParam5) } } func swiftFunction<T: Animal>(x: T) {} extension AnimalContainer { func doesntUseGenericParam1(_ x: T, _ y: T.Type) { _ = #selector(x.another) _ = #selector(y.create) } func doesntUseGenericParam2(_ x: T, _ y: T.Type) { let a = x.another() _ = a.another() _ = x.another().another() _ = type(of: x).create().another() _ = type(of: x).init(noise: x).another() _ = y.create().another() _ = y.init(noise: x).another() _ = y.init(noise: x.another()).another() x.eat(a) } func doesntUseGenericParam3(_ x: T, _ y: T.Type) { let sup: Animal = x sup.eat(x) _ = x.buddy _ = x[0] x[0] = x } func doesntUseGenericParam4(_ x: T, _ y: T.Type) { _ = type(of: x).apexPredator.another() type(of: x).apexPredator = x _ = y.apexPredator.another() y.apexPredator = x } func doesntUseGenericParam5(y: T) { var x = y x = y _ = x } func doesntUseGenericParam6(y: T?) { var x = y x = y _ = x } // Doesn't use 'T', since dynamic casting to an ObjC generic class doesn't // check its generic parameters func doesntUseGenericParam7() { _ = (self as AnyObject) as! GenericClass<T> _ = (self as AnyObject) as? GenericClass<T> _ = (self as AnyObject) as! AnimalContainer<T> _ = (self as AnyObject) as? AnimalContainer<T> _ = (self as AnyObject) is AnimalContainer<T> _ = (self as AnyObject) is AnimalContainer<T> } // Dynamic casting to the generic parameter would require its generic params, // though // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamZ1() { _ = (self as AnyObject) as! T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamZ2() { _ = (self as AnyObject) as? T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamZ3() { _ = (self as AnyObject) is T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamA(_ x: T) { _ = T(noise: x) // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamB() { _ = T.create() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamC() { _ = T.apexPredator // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamD(_ x: T) { T.apexPredator = x // expected-note{{used here}} } // rdar://problem/27796375 -- allocating init entry points for ObjC // initializers are generated as true Swift generics, so reify type // parameters. // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamE(_ x: T) { _ = GenericClass(thing: x) // expected-note{{used here}} } func checkThatMethodsAreObjC() { _ = #selector(AnimalContainer.doesntUseGenericParam1) _ = #selector(AnimalContainer.doesntUseGenericParam2) _ = #selector(AnimalContainer.doesntUseGenericParam3) _ = #selector(AnimalContainer.doesntUseGenericParam4) } // rdar://problem/26283886 func funcWithWrongArgType(x: NSObject) {} func crashWithInvalidSubscript(x: NSArray) { _ = funcWithWrongArgType(x: x[12]) // expected-error@-1{{cannot convert value of type 'Any' to expected argument type 'NSObject'}} } } extension PettableContainer { func doesntUseGenericParam(_ x: T, _ y: T.Type) { // TODO: rdar://problem/27796375--allocating entry points are emitted as // true generics. // _ = type(of: x).init(fur: x).other() _ = type(of: x).adopt().other() // _ = y.init(fur: x).other() _ = y.adopt().other() x.pet() x.pet(with: x) } // TODO: rdar://problem/27796375--allocating entry points are emitted as // true generics. // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamZ1(_ x: T, _ y: T.Type) { _ = type(of: x).init(fur: x).other() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamZ2(_ x: T, _ y: T.Type) { _ = y.init(fur: x).other() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamA(_ x: T) { _ = T(fur: x) // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamB(_ x: T) { _ = T.adopt() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamC(_ x: T) { _ = T.needingMostPets // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamD(_ x: T) { T.needingMostPets = x // expected-note{{used here}} } func checkThatMethodsAreObjC() { _ = #selector(PettableContainer.doesntUseGenericParam) } } // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassA<X: AnyObject>: GenericClass<X> {} // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassB<X: AnyObject>: GenericClass<GenericClass<X>> {} // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassC<X: NSCopying>: GenericClass<X> {} class SwiftConcreteSubclassA: GenericClass<AnyObject> { override init(thing: AnyObject) { } override func thing() -> AnyObject? { } override func count() -> Int32 { } override class func classThing() -> AnyObject? { } override func arrayOfThings() -> [AnyObject] {} } class SwiftConcreteSubclassB: GenericClass<NSString> { override init(thing: NSString) { } override func thing() -> NSString? { } override func count() -> Int32 { } override class func classThing() -> NSString? { } override func arrayOfThings() -> [NSString] {} } class SwiftConcreteSubclassC<T>: GenericClass<NSString> { override init(thing: NSString) { } override func thing() -> NSString? { } override func count() -> Int32 { } override class func classThing() -> NSString? { } override func arrayOfThings() -> [NSString] {} } // FIXME: Some generic ObjC APIs rely on covariance. We don't handle this well // in Swift yet, but ensure we don't emit spurious warnings when // `as!` is used to force types to line up. func foo(x: GenericClass<NSMutableString>) { let x2 = x as! GenericClass<NSString> takeGenericClass(x2) takeGenericClass(unsafeBitCast(x, to: GenericClass<NSString>.self)) }
apache-2.0
59b88c4a4d29df3d5bab0e9abaf9f5e1
38.398936
204
0.6801
3.919048
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Core/Extensions/UIFonts.swift
1
1269
// // UIFonts.swift // HTWDD // // Created by Mustafa Karademir on 30.06.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation extension UIFont { enum Styles: Float { case big = 23.0 case small = 13.5 case verySmall = 10.0 case description = 16.0 } static func from(style: Styles, isBold: Bool = false) -> UIFont { return isBold ? UIFont.boldSystemFont(ofSize: CGFloat(style.rawValue)) : UIFont.systemFont(ofSize: CGFloat(style.rawValue)) } static var primary: UIFont { return UIFont.systemFont(ofSize: 17.0, weight: .semibold) } } extension HTWNamespace where Base: UIFont { struct Labels { static var primary: UIFont { return UIFont.systemFont(ofSize: 17.0, weight: .semibold) } static var medium: UIFont { return UIFont.systemFont(ofSize: 13) } static var secondary: UIFont { return UIFont.systemFont(ofSize: 11.0, weight: .semibold) } } struct Badges { static var primary: UIFont { return UIFont.systemFont(ofSize: 11.0, weight: .semibold) } } }
gpl-2.0
00425a9d95239d53cc738ade5450fd37
22.924528
131
0.567035
4.298305
false
false
false
false
festrs/ListIO
Listio/AddListItemDataProvider.swift
1
4528
// // AddListItemDataProvider.swift // Listio // // Created by Felipe Dias Pereira on 2017-04-23. // Copyright © 2017 Felipe Dias Pereira. All rights reserved. // import UIKit import RealmSwift class AddListItemDataProvider: NSObject, AddListItemDataProviderProtocol { struct Keys { static let CellIdentifier = "ItemListCell" static let InfoCellIdentifer = "infoCell" } public var tableView: UITableView! var items: [Item] = [Item]() func performFetch() throws { items = try getUniqueItems() tableView.reloadData() } func getUniqueItems() throws -> [Item] { guard let items = Receipt.getUniqueItems() else { return [] } return items } func countItems() -> Int { return items.count } func unselectAll() { DatabaseManager.write(DatabaseManager.realm, writeClosure: { for value in items { value.present = false } }) tableView.reloadData() } func selectAll() { DatabaseManager.write(DatabaseManager.realm, writeClosure: { for value in items { value.present = true } }) tableView.reloadData() } } extension AddListItemDataProvider { // MARk: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) as? AddListItemTableViewCell else { fatalError("Unexpected Index Path") } let itemObj = items[indexPath.row] if itemObj.present { cell.accessoryType = .none DatabaseManager.write(DatabaseManager.realm, writeClosure: { itemObj.present = false }) } else { cell.accessoryType = .checkmark DatabaseManager.write(DatabaseManager.realm, writeClosure: { itemObj.present = true }) } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { tableView.beginUpdates() guard items.count != 0 else { return } let obj = items.remove(at: indexPath.row) DatabaseManager.write(DatabaseManager.realm, writeClosure: { DatabaseManager.realm.delete(obj) }) if items.count == 0 { tableView.setEditing(false, animated: true) } else { tableView.deleteRows(at: [indexPath], with: .fade) } tableView.endUpdates() } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } } extension AddListItemDataProvider { // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if items.count == 0 { return 1 } return items.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if items.isEmpty { return 150 } return 58 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if items.count == 0 { guard let cell = tableView.dequeueReusableCell(withIdentifier: Keys.InfoCellIdentifer, for: indexPath) as? AddListItemTableViewCell else { fatalError("Unexpected Index Path") } return cell } guard let cell = tableView.dequeueReusableCell(withIdentifier: Keys.CellIdentifier, for: indexPath) as? AddListItemTableViewCell else { fatalError("Unexpected Index Path") } let itemObj = items[indexPath.row] cell.nameLabel.text = itemObj.descricao cell.priceLabel.text = NSNumber(value: itemObj.vlUnit).maskToCurrency() cell.unLabel.text = "UN \(itemObj.qtde)" if itemObj.present { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } }
mit
2d3043fd7e0af3a76601f5b3cdf7fda7
30.4375
110
0.572565
5.441106
false
false
false
false
sjml/Metal-Life
LifeSaver/LifeSaverPreferencesController.swift
1
3853
import Cocoa import ScreenSaver import simd class LifeSaverPreferencesController: NSWindowController { let defaults: ScreenSaverDefaults? = ScreenSaverDefaults(forModuleWithName: Bundle(for: LifeSaverPreferencesController.self).bundleIdentifier!) @IBOutlet weak var bgColorWell: NSColorWell! @IBOutlet weak var fgColorWell: NSColorWell! @IBOutlet weak var pointSizeSlider: NSSlider! { didSet { pointSizeSlider.minValue = 1.0 pointSizeSlider.maxValue = 13.0 pointSizeSlider.doubleValue = 9.0 } } @IBOutlet weak var pointSizeLabel: NSTextField! @IBOutlet weak var fpsMenu: NSPopUpButton! @IBAction func okButtonAction(_ sender: Any) { self.defaults?.set(pointSizeSlider.doubleValue, forKey: "pointSize") self.defaults?.set(bgColorWell.color.redComponent, forKey: "bgRed") self.defaults?.set(bgColorWell.color.greenComponent, forKey: "bgGreen") self.defaults?.set(bgColorWell.color.blueComponent, forKey: "bgBlue") self.defaults?.set(fgColorWell.color.redComponent, forKey: "fgRed") self.defaults?.set(fgColorWell.color.greenComponent, forKey: "fgGreen") self.defaults?.set(fgColorWell.color.blueComponent, forKey: "fgBlue") let req = fpsMenu.selectedItem?.title let reqInt = Int(req!)! self.defaults?.set(reqInt, forKey: "frameRate") self.defaults?.synchronize() NSApp.mainWindow?.endSheet(self.window!) } @IBAction func restoreButtonAction(_ sender: Any) { self.defaults?.set(9.0, forKey: "pointSize") self.defaults?.set(0.25, forKey: "bgRed") self.defaults?.set(0.0, forKey: "bgGreen") self.defaults?.set(0.0, forKey: "bgBlue") self.defaults?.set(1.0, forKey: "fgRed") self.defaults?.set(0.0, forKey: "fgGreen") self.defaults?.set(0.0, forKey: "fgBlue") self.defaults?.set(60, forKey: "frameRate") self.syncUI() } @IBAction func sliderValueChanged(_ sender: Any) { self.pointSizeLabel.stringValue = String(format: "%.1f", arguments: [self.pointSizeSlider.doubleValue]) } required init?(coder decoder: NSCoder) { super.init(coder: decoder) } override init(window: NSWindow?) { super.init(window: window) } override func windowDidLoad() { super.windowDidLoad() let prefsFilePath = Bundle(for: LifeSaverPreferencesController.self).path(forResource: "InitialPreferences", ofType: "plist") let nsDefaultPrefs = NSDictionary(contentsOfFile: prefsFilePath!) if let defaultPrefs: Dictionary<String,Any> = nsDefaultPrefs as? Dictionary<String, Any> { self.defaults?.register(defaults: defaultPrefs) } self.syncUI() } func syncUI() { self.pointSizeSlider.doubleValue = self.defaults!.double(forKey: "pointSize") self.pointSizeLabel.stringValue = String(format: "%.1f", arguments: [self.pointSizeSlider.doubleValue]) self.bgColorWell.color = NSColor( red: CGFloat(self.defaults!.double(forKey: "bgRed")), green: CGFloat(self.defaults!.double(forKey: "bgGreen")), blue: CGFloat(self.defaults!.double(forKey: "bgBlue")), alpha: 1.0 ) self.fgColorWell.color = NSColor( red: CGFloat(self.defaults!.double(forKey: "fgRed")), green: CGFloat(self.defaults!.double(forKey: "fgGreen")), blue: CGFloat(self.defaults!.double(forKey: "fgBlue")), alpha: 1.0 ) let frameRate = self.defaults!.integer(forKey: "frameRate") let menuItem = self.fpsMenu.item(withTitle: String(frameRate)) self.fpsMenu.select(menuItem) } }
mit
6f0e13514c28e1ff5264d7b6ce45f8f1
40.880435
147
0.642097
4.238724
false
false
false
false
egnwd/ic-bill-hack
quick-split/Pods/Alamofire/Source/NetworkReachabilityManager.swift
68
8725
// NetworkReachabilityManager.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. #if !os(watchOS) import Foundation import SystemConfiguration /** The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. Reachability can be used to determine background information about why a network operation failed, or to retry network requests when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. */ public class NetworkReachabilityManager { /** Defines the various states of network reachability. - Unknown: It is unknown whether the network is reachable. - NotReachable: The network is not reachable. - ReachableOnWWAN: The network is reachable over the WWAN connection. - ReachableOnWiFi: The network is reachable over the WiFi connection. */ public enum NetworkReachabilityStatus { case Unknown case NotReachable case Reachable(ConnectionType) } /** Defines the various connection types detected by reachability flags. - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. - WWAN: The connection type is a WWAN connection. */ public enum ConnectionType { case EthernetOrWiFi case WWAN } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = NetworkReachabilityStatus -> Void // MARK: - Properties /// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } /// Whether the network is currently reachable over Ethernet or WiFi interface. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } /// The current network reachability status. public var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .Unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() /// A closure executed when the network reachability status changes. public var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability private var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /** Creates a `NetworkReachabilityManager` instance with the specified host. - parameter host: The host used to evaluate network reachability. - returns: The new `NetworkReachabilityManager` instance. */ public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /** Creates a `NetworkReachabilityManager` instance with the default socket address (`sockaddr_in6`). - returns: The new `NetworkReachabilityManager` instance. */ public convenience init?() { var address = sockaddr_in6() address.sin6_len = UInt8(sizeofValue(address)) address.sin6_family = sa_family_t(AF_INET6) guard let reachability = withUnsafePointer(&address, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability self.previousFlags = SCNetworkReachabilityFlags() } deinit { stopListening() } // MARK: - Listening /** Starts listening for changes in network reachability status. - returns: `true` if listening was started successfully, `false` otherwise. */ public func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) dispatch_async(listenerQueue) { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } return callbackEnabled && queueEnabled } /** Stops listening for changes in network reachability status. */ public func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard flags.contains(.Reachable) else { return .NotReachable } var networkStatus: NetworkReachabilityStatus = .NotReachable if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } } #if os(iOS) if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } #endif return networkStatus } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /** Returns whether the two network reachability status values are equal. - parameter lhs: The left-hand side value to compare. - parameter rhs: The right-hand side value to compare. - returns: `true` if the two values are equal, `false` otherwise. */ public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.Unknown, .Unknown): return true case (.NotReachable, .NotReachable): return true case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif
mit
cfd620f117c1760afde365e71881d4f1
35.497908
127
0.702625
5.556051
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/CliqzContextMenu.swift
2
6413
/* 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/. */ // Using suggestions from: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/ class CliqzContextMenu { var tapLocation: CGPoint = CGPoint.zero var tappedElement: ContextMenuHelper.Elements? var timer1_cancelDefaultMenu: Timer = Timer() var timer2_showMenuIfStillPressed: Timer = Timer() static let initialDelayToCancelBuiltinMenu = 0.20 // seconds, must be <0.3 or built-in menu can't be cancelled static let totalDelayToShowContextMenu = 0.65 - initialDelayToCancelBuiltinMenu // 850 is copied from Safari fileprivate func resetTimer() { if (!timer1_cancelDefaultMenu.isValid && !timer2_showMenuIfStillPressed.isValid) { return } // if let url = tappedElement?.link { // getCurrentWebView()?.loadRequest(NSURLRequest(URL: url)) // } [timer1_cancelDefaultMenu, timer2_showMenuIfStillPressed].forEach { $0.invalidate() } tappedElement = nil } fileprivate func isBrowserTopmostAndNoPanelsOpen() -> Bool { let rootViewController = getApp().rootViewController var navigationController: UINavigationController? if let notificatinoViewController = rootViewController as? NotificationRootViewController { navigationController = notificatinoViewController.rootViewController as? UINavigationController } else { navigationController = rootViewController as? UINavigationController } if let _ = navigationController?.visibleViewController as? BrowserViewController { return true } else { return false } } func sendEvent(_ event: UIEvent, window: UIWindow) { if !isBrowserTopmostAndNoPanelsOpen() { resetTimer() return } guard let cliqzWebView = getCurrentWebView() else { return } if let touches = event.touches(for: window), let touch = touches.first, touches.count == 1 { cliqzWebView.lastTappedTime = Date() switch touch.phase { case .began: // A finger touched the screen guard let touchView = event.allTouches?.first?.view, touchView.isDescendant(of: cliqzWebView) else { resetTimer() return } tapLocation = touch.location(in: window) resetTimer() timer1_cancelDefaultMenu = Timer.scheduledTimer(timeInterval: CliqzContextMenu.initialDelayToCancelBuiltinMenu, target: self, selector: #selector(cancelDefaultMenuAndFindTappedItem), userInfo: nil, repeats: false) break case .moved, .stationary: let p1 = touch.location(in: window) let p2 = touch.previousLocation(in: window) let distance = hypotf(Float(p1.x) - Float(p2.x), Float(p1.y) - Float(p2.y)) if distance > 10.0 { // my test for this: tap with edge of finger, then roll to opposite edge while holding finger down, is 5-10 px of movement; don't want this to be a move resetTimer() } break case .ended, .cancelled: if let url = tappedElement?.link { getCurrentWebView()?.loadRequest(URLRequest(url: url as URL)) } resetTimer() break } } else { resetTimer() } } @objc func showContextMenu() { func showContextMenuForElement(_ tappedElement: ContextMenuHelper.Elements) { guard let bvc = getApp().browserViewController else { return } if bvc.urlBar.inOverlayMode { return } bvc.showContextMenu(elements: tappedElement, touchPoint: tapLocation) resetTimer() return } if let tappedElement = tappedElement { showContextMenuForElement(tappedElement) } } // This is called 2x, once at .25 seconds to ensure the native context menu is cancelled, // then again at .5 seconds to show our context menu. (This code was borne of frustration, not ideal flow) @objc func cancelDefaultMenuAndFindTappedItem() { if !isBrowserTopmostAndNoPanelsOpen() { resetTimer() return } guard let webView = getCurrentWebView() else { return } let hit: (url: String?, image: String?, urlTarget: String?)? if [".jpg", ".png", ".gif"].filter({ webView.url?.absoluteString.endsWith($0) ?? false }).count > 0 { // web view is just showing an image hit = (url:nil, image:webView.url!.absoluteString, urlTarget:nil) } else { hit = ElementAtPoint().getHit(tapLocation) } if hit == nil { // No link or image found, not for this class to handle resetTimer() return } tappedElement = ContextMenuHelper.Elements(link: hit!.url != nil ? URL(string: hit!.url!) : nil, image: hit!.image != nil ? URL(string: hit!.image!) : nil) func blockOtherGestures(_ views: [UIView]?) { guard let views = views else { return } for view in views { if let gestures = view.gestureRecognizers as [UIGestureRecognizer]! { for gesture in gestures { if gesture is UILongPressGestureRecognizer { // toggling gets the gesture to ignore this long press gesture.isEnabled = false gesture.isEnabled = true } } } } } blockOtherGestures(getCurrentWebView()?.scrollView.subviews) timer2_showMenuIfStillPressed = Timer.scheduledTimer(timeInterval: CliqzContextMenu.totalDelayToShowContextMenu, target: self, selector: #selector(showContextMenu), userInfo: nil, repeats: false) } }
mpl-2.0
e6564595e00a2204860ebdb6d8edc9a3
41.753333
229
0.587712
5.371022
false
false
false
false
hlprmnky/tree-hugger-ios
Pods/SwiftHamcrest/Hamcrest/StringMatchers.swift
1
993
public func containsString(string: String) -> Matcher<String> { return Matcher("contains \"\(string)\"") {$0.rangeOfString(string) != nil} } public func containsStringsInOrder(strings: String...) -> Matcher<String> { return Matcher("contains in order \(describe(strings))") { (value: String) -> Bool in var range = Range(start: value.startIndex, end: value.endIndex) for string in strings { let r = value.rangeOfString(string, options: .CaseInsensitiveSearch, range: range) if r == nil { return false } range.startIndex = r!.endIndex } return true } } public func hasPrefix(expectedPrefix: String) -> Matcher<String> { return Matcher("has prefix \(describe(expectedPrefix))") {$0.hasPrefix(expectedPrefix)} } public func hasSuffix(expectedSuffix: String) -> Matcher<String> { return Matcher("has suffix \(describe(expectedSuffix))") {$0.hasSuffix(expectedSuffix)} }
mit
77de94a8e5ed3b3248244c185f9d9104
37.192308
94
0.645519
4.472973
false
false
false
false
gregomni/swift
test/decl/protocol/conforms/placement.swift
9
10411
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %S/Inputs/placement_module_A.swift -emit-module -parse-as-library -o %t // RUN: %target-swift-frontend -I %t %S/Inputs/placement_module_B.swift -emit-module -parse-as-library -o %t // RUN: %target-swift-frontend -typecheck -primary-file %s %S/Inputs/placement_2.swift -I %t -verify // Tests for the placement of conformances as well as conflicts // between conformances that come from different sources. import placement_module_A import placement_module_B protocol P1 { } protocol P2a : P1 { } protocol P3a : P2a { } protocol P2b : P1 { } protocol P3b : P2b { } protocol P4 : P3a, P3b { } protocol AnyObjectRefinement : AnyObject { } // =========================================================================== // Tests within a single source file // =========================================================================== // --------------------------------------------------------------------------- // Multiple explicit conformances to the same protocol // --------------------------------------------------------------------------- struct Explicit1 : P1 { } // expected-note{{'Explicit1' declares conformance to protocol 'P1' here}} extension Explicit1 : P1 { } // expected-error{{redundant conformance of 'Explicit1' to protocol 'P1'}} struct Explicit2 { } extension Explicit2 : P1 { } // expected-note 2{{'Explicit2' declares conformance to protocol 'P1' here}} extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}} extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}} // --------------------------------------------------------------------------- // Multiple implicit conformances, with no ambiguities // --------------------------------------------------------------------------- struct MultipleImplicit1 : P2a { } extension MultipleImplicit1 : P3a { } struct MultipleImplicit2 : P4 { } struct MultipleImplicit3 : P4 { } extension MultipleImplicit3 : P1 { } // --------------------------------------------------------------------------- // Multiple implicit conformances, ambiguity resolved because they // land in the same context. // --------------------------------------------------------------------------- struct MultipleImplicit4 : P2a, P2b { } struct MultipleImplicit5 { } extension MultipleImplicit5 : P2a, P2b { } struct MultipleImplicit6 : P4 { } extension MultipleImplicit6 : P3a { } struct MultipleImplicit7 : P2a { } extension MultipleImplicit7 : P2b { } // --------------------------------------------------------------------------- // Multiple implicit conformances, ambiguity resolved via explicit conformance // --------------------------------------------------------------------------- struct ExplicitMultipleImplicit1 : P2a { } extension ExplicitMultipleImplicit1 : P2b { } extension ExplicitMultipleImplicit1 : P1 { } // resolves ambiguity // --------------------------------------------------------------------------- // Implicit conformances superseded by inherited conformances // --------------------------------------------------------------------------- class ImplicitSuper1 : P3a { } class ImplicitSub1 : ImplicitSuper1 { } extension ImplicitSub1 : P4 { } // okay, introduces new conformance to P4; the rest are superseded // --------------------------------------------------------------------------- // Synthesized conformances superseded by implicit conformances // --------------------------------------------------------------------------- enum SuitA { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitA, rhs: SuitA) -> Bool { return false } extension SuitA : Comparable {} // okay, implied conformance to Equatable here is preferred. enum SuitB: Equatable { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitB, rhs: SuitB) -> Bool { return false } extension SuitB : Comparable {} // okay, explicitly declared earlier. enum SuitC { case Spades, Hearts, Clubs, Diamonds } func <(lhs: SuitC, rhs: SuitC) -> Bool { return false } extension SuitC : Equatable, Comparable {} // okay, explicitly declared here. // --------------------------------------------------------------------------- // Explicit conformances conflicting with inherited conformances // --------------------------------------------------------------------------- class ExplicitSuper1 : P3a { } class ExplicitSub1 : ImplicitSuper1 { } // expected-note{{'ExplicitSub1' inherits conformance to protocol 'P1' from superclass here}} extension ExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'ExplicitSub1' to protocol 'P1'}} // --------------------------------------------------------------------------- // Suppression of synthesized conformances // --------------------------------------------------------------------------- class SynthesizedClass1 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedClass2 { } extension SynthesizedClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedClass3 : AnyObjectRefinement { } class SynthesizedClass4 { } extension SynthesizedClass4 : AnyObjectRefinement { } class SynthesizedSubClass1 : SynthesizedClass1, AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedSubClass2 : SynthesizedClass2 { } extension SynthesizedSubClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class SynthesizedSubClass3 : SynthesizedClass1, AnyObjectRefinement { } class SynthesizedSubClass4 : SynthesizedClass2 { } extension SynthesizedSubClass4 : AnyObjectRefinement { } enum SynthesizedEnum1 : Int, RawRepresentable { case none = 0 } enum SynthesizedEnum2 : Int { case none = 0 } extension SynthesizedEnum2 : RawRepresentable { } // =========================================================================== // Tests across different source files // =========================================================================== // --------------------------------------------------------------------------- // Multiple explicit conformances to the same protocol // --------------------------------------------------------------------------- struct MFExplicit1 : P1 { } extension MFExplicit2 : P1 { } // expected-error{{redundant conformance of 'MFExplicit2' to protocol 'P1'}} // --------------------------------------------------------------------------- // Multiple implicit conformances, with no ambiguities // --------------------------------------------------------------------------- extension MFMultipleImplicit1 : P3a { } struct MFMultipleImplicit2 : P4 { } extension MFMultipleImplicit3 : P1 { } extension MFMultipleImplicit4 : P3a { } extension MFMultipleImplicit5 : P2b { } // --------------------------------------------------------------------------- // Explicit conformances conflicting with inherited conformances // --------------------------------------------------------------------------- class MFExplicitSuper1 : P3a { } extension MFExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'MFExplicitSub1' to protocol 'P1'}} // --------------------------------------------------------------------------- // Suppression of synthesized conformances // --------------------------------------------------------------------------- class MFSynthesizedClass1 { } extension MFSynthesizedClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} class MFSynthesizedClass4 { } extension MFSynthesizedClass4 : AnyObjectRefinement { } extension MFSynthesizedSubClass2 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MFSynthesizedSubClass3 : AnyObjectRefinement { } class MFSynthesizedSubClass4 : MFSynthesizedClass2 { } extension MFSynthesizedEnum1 : RawRepresentable { } enum MFSynthesizedEnum2 : Int { case none = 0 } // =========================================================================== // Tests with conformances in imported modules // =========================================================================== extension MMExplicit1 : MMP1 { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMExplicit1 : MMP2a { } // expected-warning{{MMExplicit1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A}} extension MMExplicit1 : MMP3a { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP3a' was already stated in the type's module 'placement_module_A'}} extension MMExplicit1 : MMP3b { } // okay extension MMSuper1 : MMP1 { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSuper1 : MMP2a { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSuper1 : MMP3b { } // okay extension MMSub1 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MMSub2 : MMP1 { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSub2 : MMP2a { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSub2 : MMP3b { } // okay extension MMSub2 : MMAnyObjectRefinement { } // okay extension MMSub3 : MMP1 { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}} extension MMSub3 : MMP2a { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}} extension MMSub3 : MMP3b { } // okay extension MMSub3 : AnyObject { } // expected-error{{only protocols can inherit from 'AnyObject'}} extension MMSub4 : MMP1 { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP1' was already stated in the type's module 'placement_module_B'}} extension MMSub4 : MMP2a { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP2a' was already stated in the type's module 'placement_module_B'}} extension MMSub4 : MMP3b { } // okay extension MMSub4 : AnyObjectRefinement { } // okay
apache-2.0
ca11cf1be7ff4c9695d8d154d72c65aa
46.976959
166
0.581692
4.983724
false
false
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Data/BubbleChartDataEntry.swift
17
1320
// // BubbleDataEntry.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class BubbleChartDataEntry: ChartDataEntry { /// The size of the bubble. public var size = CGFloat(0.0) /// - parameter xIndex: The index on the x-axis. /// - parameter val: The value on the y-axis. /// - parameter size: The size of the bubble. public init(xIndex: Int, value: Double, size: CGFloat) { super.init(value: value, xIndex: xIndex) self.size = size } /// - parameter xIndex: The index on the x-axis. /// - parameter val: The value on the y-axis. /// - parameter size: The size of the bubble. /// - parameter data: Spot for additional data this Entry represents. public init(xIndex: Int, value: Double, size: CGFloat, data: AnyObject?) { super.init(value: value, xIndex: xIndex, data: data) self.size = size } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! BubbleChartDataEntry copy.size = size return copy } }
apache-2.0
fbaac3e74b26924694e893e9e272a95c
25.959184
76
0.625758
4.137931
false
false
false
false
minimoog/MetalToy
MetalToy/TextureSelectorViewController.swift
1
3162
// // TextureSelectorViewController.swift // MetalToy // // Created by minimoog on 8/7/18. // Copyright © 2018 Toni Jovanoski. All rights reserved. // import UIKit // ### TODO: This should be a model struct TextureUnit { let filename: String var textureName: String { get { let urlPath = URL(fileURLWithPath: filename) return urlPath.deletingPathExtension().lastPathComponent } } } class TextureSelectorViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { internal var contentSize: CGSize = CGSize(width: 280, height: 600) internal var selectedFilename: String? = nil @IBOutlet weak var texSelectorTableView: UITableView! // closure invoke when user selects texture unit public var selectedTextureOnTextureUnit: ((String, Int) -> ())? public var textureUnits = [TextureUnit](repeating: TextureUnit(filename: "NULL"), count: 4) override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) // update the current table view if let selectedIndexPath = texSelectorTableView.indexPathForSelectedRow { let selectedRow = selectedIndexPath.row texSelectorTableView.deselectRow(at: selectedIndexPath, animated: true) if let filename = selectedFilename { textureUnits[selectedRow] = TextureUnit(filename: filename) texSelectorTableView.reloadRows(at: [selectedIndexPath], with: .automatic) if let selectedTextureOnTextureUnit = selectedTextureOnTextureUnit { selectedTextureOnTextureUnit(filename, selectedRow) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "TexSelectorToTextureSegue" { if let texturesCollectionViewController = segue.destination as? TexturesCollectionViewController { selectedFilename = nil //setup closures from texture collection view controller // when user select texture from texture list texturesCollectionViewController.selectedTexture = { self.selectedFilename = $0 } } } } // MARK: Table View func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return textureUnits.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellTextureUnit", for: indexPath) let row = indexPath.row cell.textLabel?.text = textureUnits[row].textureName return cell } }
mit
5bf158b6918541a8190f2b3348d042e1
32.62766
110
0.630497
5.716094
false
false
false
false
jasl/MoyaX
Tests/AlamofireBackendTests.swift
2
4039
import XCTest import OHHTTPStubs import Alamofire @testable import MoyaX class AlamofireBackendTests: XCTestCase { let data = "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! let path = "/test" var endpoint: Endpoint! var backend: AlamofireBackend! override func setUp() { super.setUp() self.endpoint = Endpoint(target: SimpliestTarget(path: self.path)) } override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } func testRequest() { // Given stub(isPath(self.path)) { _ in return OHHTTPStubsResponse(data: self.data, statusCode: 200, headers: nil).responseTime(0.5) } self.backend = AlamofireBackend() var result: MoyaX.Result<MoyaX.Response, MoyaX.Error>? let expectation = expectationWithDescription("do request") // When backend.request(self.endpoint) { closureResult in result = closureResult expectation.fulfill() } waitForExpectationsWithTimeout(2, handler: nil) //Then if let result = result { switch result { case .response: break default: XCTFail("the request should be success.") } } else { XCTFail("result should not be nil") } } func testCancelRequest() { // Given stub(isPath(self.path)) { _ in return OHHTTPStubsResponse(data: self.data, statusCode: 200, headers: nil).responseTime(2.0) } self.backend = AlamofireBackend() var result: MoyaX.Result<MoyaX.Response, MoyaX.Error>? let expectation = expectationWithDescription("do request") // When let cancellableToken = backend.request(self.endpoint) { closureResult in result = closureResult expectation.fulfill() } cancellableToken.cancel() waitForExpectationsWithTimeout(3, handler: nil) // Then if let result = result { switch result { case let .incomplete(error): guard case .cancelled = error else { XCTFail("error should be MoyaX.Error.Cancelled") break } default: XCTFail("the request should be fail.") } } else { XCTFail("result should not be nil") } } func testRequestWithHook() { // Given stub(isPath(self.path)) { _ in return OHHTTPStubsResponse(data: self.data, statusCode: 200, headers: nil).responseTime(0.5) } var calledWillPerformRequest = false let willPerformRequest: (Endpoint, Alamofire.Request) -> () = { _, _ in calledWillPerformRequest = true } var calledDidReceiveResponse = false let didReceiveResponse: (Endpoint, Alamofire.Response<NSData, NSError>) -> () = { _, _ in calledDidReceiveResponse = true } self.backend = AlamofireBackend(willPerformRequest: willPerformRequest, didReceiveResponse: didReceiveResponse) var result: MoyaX.Result<MoyaX.Response, MoyaX.Error>? let expectation = expectationWithDescription("do request") // When backend.request(self.endpoint) { closureResult in result = closureResult expectation.fulfill() } waitForExpectationsWithTimeout(2, handler: nil) // Then if let result = result { switch result { case .response: break default: XCTFail("the request should be success.") } XCTAssertTrue(calledWillPerformRequest) XCTAssertTrue(calledDidReceiveResponse) } else { XCTFail("result should not be nil") } } }
mit
8d08816fcc0c02fa5b6cd03270e32ba0
27.244755
119
0.569695
5.385333
false
true
false
false
Lclmyname/BookReader_Swift
Pods/SnapKit/Source/Debugging.swift
2
6028
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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 #else import AppKit #endif public extension LayoutConstraint { override open var description: String { var description = "<" description += descriptionForObject(self) if let firstItem = conditionalOptional(from: self.firstItem) { description += " \(descriptionForObject(firstItem))" } if self.firstAttribute != .notAnAttribute { description += ".\(descriptionForAttribute(self.firstAttribute))" } description += " \(descriptionForRelation(self.relation))" if let secondItem = self.secondItem { description += " \(descriptionForObject(secondItem))" } if self.secondAttribute != .notAnAttribute { description += ".\(descriptionForAttribute(self.secondAttribute))" } if self.multiplier != 1.0 { description += " * \(self.multiplier)" } if self.secondAttribute == .notAnAttribute { description += " \(self.constant)" } else { if self.constant > 0.0 { description += " + \(self.constant)" } else if self.constant < 0.0 { description += " - \(abs(self.constant))" } } if self.priority != 1000.0 { description += " ^\(self.priority)" } description += ">" return description } } private func descriptionForRelation(_ relation: NSLayoutRelation) -> String { switch relation { case .equal: return "==" case .greaterThanOrEqual: return ">=" case .lessThanOrEqual: return "<=" } } private func descriptionForAttribute(_ attribute: NSLayoutAttribute) -> String { #if os(iOS) || os(tvOS) switch attribute { case .notAnAttribute: return "notAnAttribute" case .top: return "top" case .left: return "left" case .bottom: return "bottom" case .right: return "right" case .leading: return "leading" case .trailing: return "trailing" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" case .topMargin: return "topMargin" case .leftMargin: return "leftMargin" case .bottomMargin: return "bottomMargin" case .rightMargin: return "rightMargin" case .leadingMargin: return "leadingMargin" case .trailingMargin: return "trailingMargin" case .centerXWithinMargins: return "centerXWithinMargins" case .centerYWithinMargins: return "centerYWithinMargins" } #else switch attribute { case .notAnAttribute: return "notAnAttribute" case .top: return "top" case .left: return "left" case .bottom: return "bottom" case .right: return "right" case .leading: return "leading" case .trailing: return "trailing" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" } #endif } private func conditionalOptional<T>(from object: Optional<T>) -> Optional<T> { return object } private func conditionalOptional<T>(from object: T) -> Optional<T> { return Optional.some(object) } private func descriptionForObject(_ object: AnyObject) -> String { let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object))) var desc = "" desc += type(of: object).description() if let object = object as? ConstraintView { desc += ":\(object.snp.label() ?? pointerDescription)" } else if let object = object as? LayoutConstraint { desc += ":\(object.label ?? pointerDescription)" } else { desc += ":\(pointerDescription)" } if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 { desc += "@\((file as NSString).lastPathComponent)#\(line)" } desc += "" return desc }
mit
3d7e0bf91dd8d146704678aee527b1e3
36.675
145
0.584605
4.985939
false
false
false
false
frosty/iOSDevUK-StackViews
StackReview/AboutViewController.swift
3
3683
/* * Copyright (c) 2015 Razeware LLC * * 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 AboutViewController: UIViewController { @IBOutlet weak var contentStackView: UIStackView! private var copyrightStackView: UIStackView? @IBOutlet weak var backgroundImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() configureView() } } extension AboutViewController { override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { let image = imageForAspectRatio(size.width / size.height) coordinator.animateAlongsideTransition({ context in // Create a transition and match the context's duration let transition = CATransition() transition.duration = context.transitionDuration() // Make it fade transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionFade self.backgroundImageView.layer.addAnimation(transition, forKey: "Fade") // Set the new image self.backgroundImageView.image = image }, completion: nil) } private func configureView() { let aspectRatio = view.bounds.size.width / view.bounds.size.height self.backgroundImageView.image = imageForAspectRatio(aspectRatio) } private func imageForAspectRatio(aspectRatio : CGFloat) -> UIImage? { return UIImage(named: aspectRatio > 1 ? "pancake3" : "placeholder") } } extension AboutViewController { @IBAction func handleCopyrightButtonTapped(sender: AnyObject) { if copyrightStackView != .None { UIView.animateWithDuration(0.8, animations: { self.copyrightStackView?.hidden = true }, completion: { _ in self.copyrightStackView?.removeFromSuperview() self.copyrightStackView = nil }) } else { copyrightStackView = createCopyrightStackView() copyrightStackView?.hidden = true contentStackView.addArrangedSubview(copyrightStackView!) UIView.animateWithDuration(0.8) { self.copyrightStackView?.hidden = false } } } private func createCopyrightStackView() -> UIStackView? { let imageView = UIImageView(image: UIImage(named: "rw_logo")) imageView.contentMode = .ScaleAspectFit let label = UILabel() label.text = "© Razeware 2015" let stackView = UIStackView(arrangedSubviews: [imageView, label]) stackView.axis = .Horizontal stackView.alignment = .Center stackView.distribution = .FillEqually return stackView } }
mit
f3e7f8a94439f7391edfe5087b54be50
32.779817
134
0.723248
5.121001
false
false
false
false
LeaderQiu/SwiftWeibo
HMWeibo04/HMWeibo04/Classes/UI/Main/MainTabBarController.swift
1
2716
// // MainTabBarController.swift // HMWeibo04 // // Created by apple on 15/3/5. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { // 不能起 tabBar 的名字 @IBOutlet weak var mainTabBar: MainTabBar! override func viewDidLoad() { super.viewDidLoad() // 使用代码添加视图控制器 addControllers() // 定义回调 - Swift 中的闭包同样会对外部变量进行强引用 // 提示:weak 变量必须是 var,不能使用 let // 在 swift 中判断闭包的循环引用和 oc 中几乎是一样的,使用 deinit weak var weakSelf = self mainTabBar.composedButtonClicked = { println("hello") // modal 撰写微博 视图控制器 let sb = UIStoryboard(name: "Compose", bundle: nil) weakSelf!.presentViewController(sb.instantiateInitialViewController() as! UIViewController, animated: true, completion: nil) } } /// deinit 和 OC 中的 dealloc 作用是类似的 deinit { println("没有循环引用") } /// 添加子控制器 func addControllers() { addchildController("Home", "首页", "tabbar_home", "tabbar_home_highlighted") addchildController("Message", "消息", "tabbar_message_center", "tabbar_message_center_highlighted") addchildController("Discover", "发现", "tabbar_discover", "tabbar_discover_highlighted") addchildController("Profile", "我", "tabbar_profile", "tabbar_profile_highlighted") } /// 添加视图控制器 /// /// :param: name sb name /// :param: title 标题 /// :param: imageName 图像名称 /// :param: highlight 高亮名称 func addchildController(name: String, _ title: String, _ imageName: String, _ highlight: String) { let sb = UIStoryboard(name: name, bundle: nil) let vc = sb.instantiateInitialViewController() as! UINavigationController // 添加图标&文字 vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: highlight)?.imageWithRenderingMode(.AlwaysOriginal) vc.title = title // 设置文字颜色,在 UIKit 框架中,大概有 7~9 个头文件是以 NS 开头的,都是和文本相关的 // NSAttributedString 中定义的文本属性,主要用在"图文混排" vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orangeColor()], forState: UIControlState.Selected) self.addChildViewController(vc) } }
mit
a1816f0a3708c63252f7c3d5f59ebbee
33.028986
136
0.628194
4.364312
false
false
false
false
avinassh/Psycologist-Swift
Psycologist/FaceView.swift
2
4085
// // FaceView.swift // Happiness // // Created by avi on 28/02/15. // Copyright (c) 2015 avi. All rights reserved. // import UIKit protocol FaceViewDataSource: class { func smilinessForFaceView(sender: FaceView) -> Double? } @IBDesignable class FaceView: UIView { @IBInspectable var linewidth: CGFloat = 3 { didSet { setNeedsDisplay() } } @IBInspectable var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } @IBInspectable var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } } var faceCenter: CGPoint { return convertPoint(center, fromView: superview) } var faceRadius: CGFloat { return min(bounds.size.width, bounds.size.height) / 2 * scale } private struct Scaling { static let FaceRadiusToEyeRadiusRatio: CGFloat = 10 static let FaceRadiusToEyeOffsetRatio: CGFloat = 3 static let FaceRadiusToEyeSeparatationRadio: CGFloat = 1.5 static let FaceRadiusToMouthWidthRatio: CGFloat = 1 static let FaceRadiusToMouthHeightRatio: CGFloat = 3 static let FaceRadiusToMouthOffsetRatio: CGFloat = 3 } private enum Eye { case Left, Right } weak var dataSource: FaceViewDataSource? private func bezierPathForEye(whichEye: Eye) -> UIBezierPath { let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparatationRadio var eyeCenter = faceCenter eyeCenter.y -= eyeVerticalOffset switch whichEye { case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2 case .Right: eyeCenter.x += eyeHorizontalSeparation / 2 } let path = UIBezierPath( arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true ) path.lineWidth = linewidth return path } private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath { let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset) let end = CGPoint(x: start.x + mouthWidth, y: start.y) let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight) let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y) let path = UIBezierPath() path.moveToPoint(start) path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = linewidth return path } override func drawRect(rect: CGRect) { let facePath = UIBezierPath( arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true ) facePath.lineWidth = linewidth color.set() facePath.stroke() bezierPathForEye(.Left).stroke() bezierPathForEye(.Right).stroke() let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0 let smilePath = bezierPathForSmile(smiliness) smilePath.stroke() } func scale(gesture: UIPinchGestureRecognizer) { if gesture.state == .Changed { scale *= gesture.scale gesture.scale = 1 } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
c0f723c0e0bddad267cac39a3d1df79d
31.420635
91
0.625704
5.055693
false
false
false
false
masahiko24/CRToastSwift
CRToastSwift/Presenter.swift
2
12334
// // Presenter.swift // CRToastSwift // // Copyright (c) 2015 Masahiko Tsujita <[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 CRToast /// A notification presenter. public class Presenter { public init() { } /** Presents a notification. - parameter notification: The notification to be presented. - parameter context: The presentation context. - parameter animation: The animation. - parameter duration: The time interval that determines how long the notification will be presented. - parameter handler: A handler to be called when the notification is presented. - returns: The presentation object for the presentation. */ public func present<Notification: NotificationType, Context:PresentationContextType where Notification == Context.Notification>(notification: Notification, context: Context, animation: Animation = .Linear, duration: NSTimeInterval? = 2.0, handler: ((Notification, Dismisser<Notification>) -> Void)? = nil) -> Presentation<Notification> { // Initializing variables and constants let attributes = context.attributesForNotification(notification) let identifier = NSUUID().UUIDString let presentation = Presentation<Notification>(identifier: identifier) let dismisser = Dismisser(presentation: presentation) var options = [String : AnyObject]() // ID options[kCRToastIdentifierKey] = identifier // Configuring Texts options[kCRToastTextKey] = notification.text options[kCRToastTextAlignmentKey] = attributes.textAlignment.rawValue options[kCRToastFontKey] = attributes.textFont options[kCRToastTextColorKey] = attributes.textColor options[kCRToastTextMaxNumberOfLinesKey] = attributes.textMaxNumberOfLines options[kCRToastTextShadowColorKey] = attributes.textShadowColor options[kCRToastTextShadowOffsetKey] = NSValue(CGSize: attributes.textShadowOffset) if notification.subtext != nil { options[kCRToastSubtitleTextKey] = notification.subtext } options[kCRToastSubtitleTextAlignmentKey] = attributes.subtextAlignment.rawValue options[kCRToastSubtitleFontKey] = attributes.subtextFont options[kCRToastSubtitleTextColorKey] = attributes.subtextColor options[kCRToastSubtitleTextMaxNumberOfLinesKey] = attributes.subtextMaxNumberOfLines options[kCRToastSubtitleTextShadowColorKey] = attributes.subtextShadowColor options[kCRToastSubtitleTextShadowOffsetKey] = NSValue(CGSize: attributes.subtextShadowOffset) // Configuring Appearances options[kCRToastNotificationTypeKey] = attributes.size.CRToastTypeValue.rawValue switch attributes.size { case .Custom(let preferredHeight): options[kCRToastNotificationPreferredHeightKey] = preferredHeight default: break } options[kCRToastBackgroundColorKey] = attributes.backgroundColor options[kCRToastBackgroundViewKey] = attributes.backgroundView options[kCRToastNotificationPreferredPaddingKey] = attributes.preferredPadding options[kCRToastUnderStatusBarKey] = attributes.showsStatusBar options[kCRToastStatusBarStyleKey] = attributes.statusBarStyle.rawValue options[kCRToastImageKey] = attributes.image options[kCRToastImageTintKey] = attributes.imageTintColor options[kCRToastImageAlignmentKey] = attributes.imageAlignment.rawValue options[kCRToastImageContentModeKey] = attributes.imageContentMode.rawValue options[kCRToastShowActivityIndicatorKey] = attributes.showsActivityIndicatorView options[kCRToastActivityIndicatorAlignmentKey] = attributes.activityIndicatorAlignment.rawValue options[kCRToastActivityIndicatorViewStyleKey] = attributes.activityIndicatorViewStyle.rawValue options[kCRToastKeepNavigationBarBorderKey] = attributes.keepsNavigationBarBorder // Configuring Animations options[kCRToastAnimationInTypeKey] = animation.inCurve.rawValue options[kCRToastAnimationInDirectionKey] = animation.inDirection.rawValue options[kCRToastAnimationInTimeIntervalKey] = animation.inDuration options[kCRToastAnimationOutTypeKey] = animation.outCurve.rawValue options[kCRToastAnimationOutDirectionKey] = animation.outDirection.rawValue options[kCRToastAnimationOutTimeIntervalKey] = animation.outDuration options[kCRToastAnimationSpringDampingKey] = animation.springDamping options[kCRToastAnimationSpringInitialVelocityKey] = animation.springInitialVelocity options[kCRToastAnimationGravityMagnitudeKey] = animation.gravityMagnitude options[kCRToastNotificationPresentationTypeKey] = animation.backgroundHidingStyle.rawValue // Configuring User Interactions if let duration = duration { options[kCRToastForceUserInteractionKey] = false options[kCRToastTimeIntervalKey] = duration } else { options[kCRToastForceUserInteractionKey] = true } options[kCRToastInteractionRespondersKey] = [CRToastInteractionResponder(interactionType: .All, automaticallyDismiss: false, block: { userInteraction in presentation.userInteractionSignal.send((notification, UserInteraction(rawValue: userInteraction.rawValue), dismisser)) })] // Others options[kCRToastAutorotateKey] = attributes.rotatesAutomatically options[kCRToastCaptureDefaultWindowKey] = attributes.capturesDefaultWindow // Presenting Notification if let handler = handler { presentation.onPresented(handler) } dispatch_async(dispatch_get_main_queue()) { CRToastManager.showNotificationWithOptions(options, apperanceBlock: { presentation.presentationSignal.send(notification, dismisser) }, completionBlock: { presentation.dismissalSignal.send(notification) }) } return presentation } } public extension Presenter { /// Shared presenter for static methods public static let sharedPresenter = Presenter() // MARK: Static Presentation Methods /** Presents a notification with a presentation context. - parameter notification: The notification to be presented. - parameter context: The presentation context. - parameter animation: The animation. - parameter duration: The time interval that determines how long the notification will be presented. - parameter handler: A handler to be called when the notification is presented. - returns: The presentation object for the presentation. */ public static func present<Notification: NotificationType, Context:PresentationContextType where Notification == Context.Notification>(notification: Notification, context: Context, animation: Animation = .Linear, duration: NSTimeInterval? = 2.0, handler: ((Notification, Dismisser<Notification>) -> Void)? = nil) -> Presentation<Notification> { return self.sharedPresenter.present(notification, context: context, animation: animation, duration: duration, handler: handler) } /** Presents a notification without presentation context. - parameter notification: The notification to be presented. - parameter animation: The animation. - parameter duration: The time interval that determines how long the notification will be presented. - parameter handler: A handler to be called when the notification is presented. - returns: The presentation object for the presentation. */ public static func present<Notification: NotificationType>(notification: Notification, animation: Animation = .Linear, duration: NSTimeInterval? = 2.0, handler: ((Notification, Dismisser<Notification>) -> Void)? = nil) -> Presentation<Notification> { return self.sharedPresenter.present(notification, context: PresentationContext { _ in NotificationAttributeCollection() }, animation: animation, duration: duration, handler: handler) } /** Presents a notification with given text and subtext with a presentation context. - parameter text: The main text of the notification. - parameter subtext: The subsidiary text of the notification. - parameter context: The presentation context. - parameter animation: The animation. - parameter duration: The time interval that determines how long the notification will be presented. - parameter handler: A handler to be called when the notification is presented. - returns: The presentation object for the presentation. */ public static func present<Context:PresentationContextType where Context.Notification == CRToastSwift.Notification>(text text: String, subtext: String?, context: Context, animation: Animation = .Linear, duration: NSTimeInterval? = 2.0, handler: ((Notification, Dismisser<Notification>) -> Void)? = nil) -> Presentation<Notification> { return self.sharedPresenter.present(Notification(text: text, subtext: subtext), context: context, animation: animation, duration: duration, handler: handler) } /** Presents a notification with given text and subtext without presentation context. - parameter text: The main text of the notification. - parameter subtext: The subsidiary text of the notification. - parameter animation: The animation. - parameter duration: The time interval that determines how long the notification will be presented. - parameter handler: A handler to be called when the notification is presented. - returns: The presentation object for the presentation. */ public static func present(text text: String, subtext: String?, animation: Animation = .Linear, duration: NSTimeInterval? = 2.0, handler: ((Notification, Dismisser<Notification>) -> Void)? = nil) -> Presentation<Notification> { return self.sharedPresenter.present(Notification(text: text, subtext: subtext), context: PresentationContext { _ in NotificationAttributeCollection() }, animation: animation, duration: duration, handler: handler) } }
mit
c722f96323794581c64034ce8659bd48
52.393939
348
0.682017
5.715477
false
false
false
false
JadenGeller/Handbag
Sources/Bag.swift
1
5735
// // Bag.swift // Handbag // // Created by Jaden Geller on 1/11/16. // Copyright © 2016 Jaden Geller. All rights reserved. // public struct Bag<Element: Hashable> { private var backing: [Element : Int] public init() { backing = [:] } } extension Bag { public subscript(element: Element) -> Int { get { return backing[element] ?? 0 } set { precondition(newValue >= 0, "Bag cannot contain a negative count of a given element.") backing[element] = (newValue == 0) ? nil : newValue } } public init<S: SequenceType where S.Generator.Element == Element>(_ sequence: S) { self.init() insertContentsOf(sequence) } } extension Bag { public mutating func insert(element: Element, count: Int = 1) { precondition(count >= 0, "Number of elements inserted must be non-negative.") self[element] += count } public mutating func remove(element: Element, count: Int = 1) { precondition(count >= 0, "Number of elements removed must be non-negative.") self[element] = max(0, self[element] - count) } public mutating func insertContentsOf<S: SequenceType where S.Generator.Element == Element>(sequence: S) { sequence.forEach{ insert($0) } } public mutating func removeContentsOf<S: SequenceType where S.Generator.Element == Element>(sequence: S) { sequence.forEach{ remove($0) } } } extension Set { public init(_ bag: Bag<Element>) { self.init(bag.backing.keys) } } extension Bag: DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (Element, Int)...) { self.init() for (element, count) in elements { insert(element, count: count) } } } extension Bag: ArrayLiteralConvertible { public init(arrayLiteral elements: Element...) { self.init(elements) } } extension Bag: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return backing.description } public var debugDescription: String { return backing.debugDescription } } extension Bag: Equatable, Hashable { public var hashValue: Int { return backing.map{ $0.hashValue ^ $1.hashValue }.reduce(0, combine: ^) } } public func ==<Element: Hashable>(lhs: Bag<Element>, rhs: Bag<Element>) -> Bool { return lhs.backing == rhs.backing } extension Bag: SequenceType { public func generate() -> BagGenerator<Element> { return BagGenerator(backing) } } // Note that the collection only contains elements with positive count. extension Bag: Indexable { public var startIndex: BagIndex<Element> { return BagIndex(offset: 0) } public var endIndex: BagIndex<Element> { return BagIndex(offset: count) } public subscript(index: BagIndex<Element>) -> Element { let generator = AnySequence(self).dropFirst(index.offset).generate() return generator.next()! } } extension Bag: CollectionType { public var isEmpty: Bool { return backing.isEmpty } public var count: Int { return backing.values.lazy.filter{ $0 > 0 }.reduce(0, combine: +) } public func contains(element: Element) -> Bool { return self[element] > 0 } /// Removes `element` and returns the count prior to removal. /// If count is `nil`, removes all copies of `element`. public mutating func remove(element: Element, count: Int? = nil) -> Int { let oldCount = self[element] self[element] -= count ?? self[element] return oldCount } public mutating func removeAll(keepCapacity: Bool = false) { backing.removeAll(keepCapacity: keepCapacity) } public var uniqueElements: LazyMapCollection<Dictionary<Element, Int>, Element> { return backing.keys } public var elementCounts: Dictionary<Element, Int> { return backing } } extension Bag { public mutating func unionInPlace(bag: Bag) { for (element, count) in bag.elementCounts { insert(element, count: count) } } public func union(bag: Bag) -> Bag { var copy = self copy.unionInPlace(bag) return copy } public mutating func subtractInPlace(bag: Bag) { for (element, count) in bag.elementCounts { remove(element, count: count) } } public func subtract(bag: Bag) -> Bag { var copy = self copy.subtractInPlace(bag) return copy } public mutating func intersectInPlace(bag: Bag) { self = intersect(bag) } public func intersect(bag: Bag) -> Bag { var result = Bag() for (element, count) in bag.elementCounts { result[element] = min(count, self[element]) } return result } } extension Bag { public func isSubsetOf(bag: Bag) -> Bool { return subtract(bag).isEmpty } public func isStrictSubsetOf(bag: Bag) -> Bool { return isSubsetOf(bag) && self != bag } public func isSupersetOf(bag: Bag) -> Bool { return bag.isSubsetOf(self) } public func isStrictSupersetOf(bag: Bag) -> Bool { return bag.isStrictSubsetOf(self) } public func isDisjointWith(bag: Bag) -> Bool { return intersect(bag).isEmpty } } public func +<Element>(lhs: Bag<Element>, rhs: Bag<Element>) -> Bag<Element> { return lhs.union(rhs) } public func -<Element>(lhs: Bag<Element>, rhs: Bag<Element>) -> Bag<Element> { return lhs.subtract(rhs) }
mit
c984f8eb608f4214cec8e8a1e3fa631c
25.302752
110
0.610917
4.2823
false
false
false
false
luckymore0520/leetcode
N-Queens.playground/Contents.swift
1
3132
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. // // // //Given an integer n, return all distinct solutions to the n-queens puzzle. // //Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. // //For example, //There exist two distinct solutions to the 4-queens puzzle: // //[ //[".Q..", // Solution 1 //"...Q", //"Q...", //"..Q."], // //["..Q.", // Solution 2 //"Q...", //"...Q", //".Q.."] //] class Solution { func solveNQueens(_ n: Int) -> [[String]] { var result:[[String]] = [] let row:[Character] = Array(repeating: ".", count: n) var matric:[[Character]] = Array(repeating: row, count: n) var i = 0; var qArray = Array(repeating: -1, count: n) while qArray[0] < n { while i < n { var j = qArray[i] + 1 if (qArray[i] >= 0) { matric[i][qArray[i]] = "." qArray[i] = -1 } //判断这里如果j超过了最后一个了 if (j >= n && i == 0) { break } while j < n { qArray[i] = j if checkNQueens(qArray: qArray, targetRow: i) == false { j += 1 qArray[i] = -1 } else { matric[i][j] = "Q" break } } //如果遍历到最后一个依然找不到,需要回溯 if (j == n) { i -= 1 } else { i += 1 } } if (i == n) { result.append(matric.map({ (character) -> String in String(character) })) i -= 1 } else { break } } return result } func checkNQueens(qArray:[Int], targetRow:Int) -> Bool { let count = qArray.count //检查一列 for i in 0...count-1 { if qArray[i] != -1 && i != targetRow && qArray[i] == qArray[targetRow] { return false } } //检查 \ 方向 差相同 for i in 0...count - 1 { let minus = i - qArray[i] if (qArray[i] != -1 && i != targetRow && minus == targetRow - qArray[targetRow]) { return false } } // 检查 / 方向 和相同 for i in 0...count - 1 { let sum = i + qArray[i] if (qArray[i] != -1 && i != targetRow && sum == targetRow + qArray[targetRow]) { return false } } return true } } let solution = Solution() print(solution.solveNQueens(4))
mit
f4cada60a3c9c7b1ec5fc3c8560f48ab
26.288288
156
0.413008
4.098782
false
false
false
false
dreamsxin/swift
test/Reflection/Inputs/ConcreteTypes.swift
3
1737
public class Box<Treasure> { public let item: Treasure public init(item: Treasure) { self.item = item } } public class C { public let aClass: C public let aStruct: S public let anEnum: E public let aTuple: (C, S, E, Int) public let aTupleWithLabels: (a: C, s: S, e: E) public let aMetatype: C.Type public let aFunction: (C, S, E, Int) -> (Int) public let aFunctionWithVarArgs: (C, S...) -> () public init(aClass: C, aStruct: S, anEnum: E, aTuple: (C, S, E, Int), aTupleWithLabels: (a: C, s: S, e: E), aMetatype: C.Type, aFunction: (C, S, E, Int) -> Int, aFunctionWithVarArgs: (C, S...) -> ()) { self.aClass = aClass self.aStruct = aStruct self.anEnum = anEnum self.aTuple = aTuple self.aTupleWithLabels = aTupleWithLabels self.aMetatype = aMetatype self.aFunction = aFunction self.aFunctionWithVarArgs = aFunctionWithVarArgs } } public struct S { public let aClass: C public let aStruct: Box<S> public let anEnum: Box<E> public let aTuple: (C, Box<S>, Box<E>, Int) public let aMetatype: C.Type public let aFunction: (C, S, E, Int) -> (Int) public let aFunctionWithThinRepresentation: @convention(thin) () -> () public let aFunctionWithCRepresentation: @convention(c) () -> () public struct NestedS { public let aField: Int } } public enum E { case Class(C) case Struct(S) indirect case Enum(E) case Function((C,S,E,Int) -> ()) case Tuple(C, S, Int) indirect case IndirectTuple(C, S, E, Int) case Metatype(E.Type) case NestedStruct(S.NestedS) case EmptyCase } public struct References { public let strongRef: C public weak var weakRef: C? public unowned var unownedRef: C public unowned(unsafe) var unownedUnsafeRef: C }
apache-2.0
5c640010eb69cfe76aca2e5160f2e5a3
27.47541
203
0.667242
3.359768
false
false
false
false
Msr-B/FanFan-iOS
WeCenterMobile/View/Home/ArticlePublishmentActionCell.swift
3
1945
// // ArticlePublishmentActionCell.swift // WeCenterMobile // // Created by Darren Liu on 14/12/29. // Copyright (c) 2014年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class ArticlePublishmentActionCell: UITableViewCell { @IBOutlet weak var userAvatarView: MSRRoundedImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var articleTitleLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var articleButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var articleContainerView: UIView! @IBOutlet weak var separator: UIView! override func awakeFromNib() { super.awakeFromNib() msr_scrollView?.delaysContentTouches = false let theme = SettingsManager.defaultManager.currentTheme for v in [userContainerView, articleContainerView] { v.backgroundColor = theme.backgroundColorB } containerView.msr_borderColor = theme.borderColorA separator.backgroundColor = theme.borderColorA for v in [userButton, articleButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [userNameLabel, articleTitleLabel] { v.textColor = theme.titleTextColor } typeLabel.textColor = theme.subtitleTextColor } func update(action action: Action) { let action = action as! ArticlePublishmentAction userAvatarView.wc_updateWithUser(action.user) userNameLabel.text = action.user?.name ?? "匿名用户" articleTitleLabel.text = action.article!.title userButton.msr_userInfo = action.user articleButton.msr_userInfo = action.article setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
1600fd67cd2cb07f80f984b6f39143dc
36.230769
99
0.698708
5.243902
false
false
false
false
rain2540/RGUICategory
AC/Application/Vendors/PullRefresh/MHRefreshNormalHeader.swift
1
3324
// // MHRefreshNormalHeader.swift // 妙汇 // // Created by 韩威 on 2016/10/21. // Copyright © 2016年 韩威. All rights reserved. // import UIKit class MHRefreshNormalHeader: MHRefreshHeader { @IBOutlet weak var refresh_arrow: UIImageView! @IBOutlet weak var refresh_indicator: UIActivityIndicatorView! override class func headerWithHandler(handler: MHRefreshHeaderBlock?) -> MHRefreshNormalHeader { let views = Bundle.main.loadNibNamed("MHRefreshNormalHeader", owner: nil, options: nil) let header = views!.last as! MHRefreshNormalHeader header.refreshHeaderBlock = handler return header } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() refresh_indicator.isHidden = true refresh_arrow.isHidden = false } override func layoutSubviews() { super.layoutSubviews() self.frame = CGRect.init(x: MHRefreshHeaderX, y: MHRefreshHeaderY, width: Double(MHRefreshHeaderW), height: Double(MHRefreshHeaderH)) /* <¶ôʱá.MHRefreshNormalHeader: 0x155671810; frame = (0 -40; 375 0); autoresize = W+H; layer = <CALayer: 0x1556032b0>> */ // 15 40 refresh_arrow.frame = CGRect.init(x: SCREEN_WIDTH / 2.0 - 15.0 / 2.0, y: self.bounds.height / 2.0 - 40.0 / 2.0, width: 15, height: 40) refresh_indicator.frame = CGRect.init(x: SCREEN_WIDTH / 2.0 - 20.0 / 2.0, y: self.bounds.height / 2.0 - 20.0 / 2.0, width: 20, height: 20) } // MARK: - Override override func changeRefreshState(state: MHRefreshState) { let oldState = refreshState //print("MHRefreshNormalHeader set state. oldState = \(oldState), state = \(state)") if state == oldState { return } super.changeRefreshState(state: state) if state == .normal { if oldState == .refreshing { refresh_arrow.transform = CGAffineTransform.identity UIView.animate(withDuration: MHRefreshAnimationDuration, animations: { self.refresh_indicator.alpha = 0.0 }, completion: { (com) in self.refresh_indicator.alpha = 1.0 self.refresh_indicator.stopAnimating() self.refresh_arrow.isHidden = false }) } else { self.refresh_indicator.stopAnimating() self.refresh_arrow.isHidden = false UIView.animate(withDuration: MHRefreshAnimationDuration, animations: { self.refresh_arrow.transform = CGAffineTransform.identity }) } } else if state == .pulling { refresh_indicator.stopAnimating() refresh_arrow.isHidden = false UIView.animate(withDuration: MHRefreshAnimationDuration, animations: { self.refresh_arrow.transform = CGAffineTransform(rotationAngle: CGFloat.pi) }) } else if state == .refreshing { refresh_indicator.alpha = 1.0 refresh_indicator.startAnimating() refresh_arrow.isHidden = true } } }
mit
2632bb350d600d83116c039f7fe0119b
37.406977
146
0.582198
4.665254
false
false
false
false
velvetroom/columbus
Source/View/Abstract/Generic/VMenuCell.swift
1
1484
import UIKit final class VMenuCell:UICollectionViewCell { private weak var imageView:UIImageView! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { imageView.tintColor = UIColor.colourBackgroundDark } else { imageView.tintColor = UIColor.colourBackgroundDark.withAlphaComponent(0.2) } } //MARK: internal func config(model:MMenuItemProtocol) { imageView.image = model.icon.withRenderingMode(UIImageRenderingMode.alwaysTemplate) hover() } }
mit
fc255477e18ea085d0214a0a49913d2f
20.507246
91
0.57345
5.751938
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Dependencies/Anchorage.swift
1
28203
// // Anchorage.swift // Anchorage // // Created by Rob Visentin on 2/6/16. // // Copyright 2016 Raizlabs and other contributors // http://raizlabs.com/ // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if os(macOS) import Cocoa public enum Alias { public typealias View = NSView public typealias ViewController = NSViewController public typealias LayoutPriority = NSLayoutPriority public typealias LayoutGuide = NSLayoutGuide public static let LayoutPriorityRequired = NSLayoutPriorityRequired public static let LayoutPriorityHigh = NSLayoutPriorityDefaultHigh public static let LayoutPriorityLow = NSLayoutPriorityDefaultLow public static let LayoutPriorityFittingSize = NSLayoutPriorityFittingSizeCompression } #else import UIKit public enum Alias { public typealias View = UIView public typealias ViewController = UIViewController public typealias LayoutPriority = UILayoutPriority public typealias LayoutGuide = UILayoutGuide public static let LayoutPriorityRequired = UILayoutPriority.required public static let LayoutPriorityHigh = UILayoutPriority.defaultHigh public static let LayoutPriorityLow = UILayoutPriority.defaultLow public static let LayoutPriorityFittingSize = UILayoutPriority.fittingSizeLevel } #endif public protocol LayoutAnchorType {} extension NSLayoutDimension : LayoutAnchorType {} extension NSLayoutXAxisAnchor : LayoutAnchorType {} extension NSLayoutYAxisAnchor : LayoutAnchorType {} public protocol LayoutAxisType {} extension NSLayoutXAxisAnchor : LayoutAxisType {} extension NSLayoutYAxisAnchor : LayoutAxisType {} #if swift(>=3.0) // MARK: - Equality Constraints @discardableResult public func == (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalToConstant: rhs)) } @discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(equalTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(equalToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func == (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsEqualToEdges: rhs) } @discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func == <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsEqualToEdges: rhs) } @discardableResult public func == <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } // MARK: - Inequality Constraints @discardableResult public func <= (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs)) } @discardableResult public func <= <T: NSLayoutDimension>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(lessThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func <= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func <= <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs)) } @discardableResult public func >=<T: NSLayoutDimension>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >=<T: NSLayoutXAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >=<T: NSLayoutYAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >= <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func >= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= <T, U>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= <T, U>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } // MARK: - Priority precedencegroup PriorityPrecedence { associativity: none higherThan: ComparisonPrecedence lowerThan: AdditionPrecedence } infix operator ~: PriorityPrecedence // LayoutPriority @discardableResult public func ~ (lhs: CGFloat, rhs: LayoutPriority) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(constant: lhs, priority: rhs) } @discardableResult public func ~ <T>(lhs: T, rhs: LayoutPriority) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, priority: rhs) } @discardableResult public func ~ <T>(lhs: LayoutExpression<T>, rhs: LayoutPriority) -> LayoutExpression<T> { var expr = lhs expr.priority = rhs return expr } // UILayoutPriority @discardableResult public func ~ (lhs: CGFloat, rhs: Alias.LayoutPriority) -> LayoutExpression<NSLayoutDimension> { return lhs ~ .custom(rhs) } @discardableResult public func ~ <T>(lhs: T, rhs: Alias.LayoutPriority) -> LayoutExpression<T> { return lhs ~ .custom(rhs) } @discardableResult public func ~ <T>(lhs: LayoutExpression<T>, rhs: Alias.LayoutPriority) -> LayoutExpression<T> { return lhs ~ .custom(rhs) } // MARK: Layout Expressions @discardableResult public func * (lhs: NSLayoutDimension, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: lhs, multiplier: rhs) } @discardableResult public func * (lhs: CGFloat, rhs: NSLayoutDimension) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: rhs, multiplier: lhs) } @discardableResult public func * (lhs: LayoutExpression<NSLayoutDimension>, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { var expr = lhs expr.multiplier *= rhs return expr } @discardableResult public func * (lhs: CGFloat, rhs: LayoutExpression<NSLayoutDimension>) -> LayoutExpression<NSLayoutDimension> { var expr = rhs expr.multiplier *= lhs return expr } @discardableResult public func / (lhs: NSLayoutDimension, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: lhs, multiplier: 1.0 / rhs) } @discardableResult public func / (lhs: LayoutExpression<NSLayoutDimension>, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { var expr = lhs expr.multiplier /= rhs return expr } @discardableResult public func + <T>(lhs: T, rhs: CGFloat) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, constant: rhs) } @discardableResult public func + <T>(lhs: CGFloat, rhs: T) -> LayoutExpression<T> { return LayoutExpression(anchor: rhs, constant: lhs) } @discardableResult public func + <T>(lhs: LayoutExpression<T>, rhs: CGFloat) -> LayoutExpression<T> { var expr = lhs expr.constant += rhs return expr } @discardableResult public func + <T>(lhs: CGFloat, rhs: LayoutExpression<T>) -> LayoutExpression<T> { var expr = rhs expr.constant += lhs return expr } @discardableResult public func - <T>(lhs: T, rhs: CGFloat) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, constant: -rhs) } @discardableResult public func - <T>(lhs: CGFloat, rhs: T) -> LayoutExpression<T> { return LayoutExpression(anchor: rhs, constant: -lhs) } @discardableResult public func - <T>(lhs: LayoutExpression<T>, rhs: CGFloat) -> LayoutExpression<T> { var expr = lhs expr.constant -= rhs return expr } @discardableResult public func - <T>(lhs: CGFloat, rhs: LayoutExpression<T>) -> LayoutExpression<T> { var expr = rhs expr.constant -= lhs return expr } // Adding to and subtracting from LayoutPriority public func + (lhs: LayoutPriority, rhs: CGFloat) -> LayoutPriority { return .custom(lhs.value + Alias.LayoutPriority(Float(rhs))) } public func - (lhs: LayoutPriority, rhs: CGFloat) -> LayoutPriority { return .custom(lhs.value - Alias.LayoutPriority(Float(rhs))) } public func + (lhs: CGFloat, rhs: LayoutPriority) -> LayoutPriority { return .custom(Alias.LayoutPriority(Float(lhs)) + rhs.value) } public func - (lhs: CGFloat, rhs: LayoutPriority) -> LayoutPriority { return .custom(Alias.LayoutPriority(Float(lhs)) - rhs.value) } private func + (lhs: Alias.LayoutPriority, rhs: Alias.LayoutPriority) -> Alias.LayoutPriority { return Alias.LayoutPriority(lhs.rawValue + rhs.rawValue) } private func - (lhs: Alias.LayoutPriority, rhs: Alias.LayoutPriority) -> Alias.LayoutPriority { return Alias.LayoutPriority(lhs.rawValue - rhs.rawValue) } #endif public struct LayoutExpression<T : LayoutAnchorType> { var anchor: T? var constant: CGFloat var multiplier: CGFloat var priority: LayoutPriority init(anchor: T? = nil, constant: CGFloat = 0.0, multiplier: CGFloat = 1.0, priority: LayoutPriority = .required) { self.anchor = anchor self.constant = constant self.multiplier = multiplier self.priority = priority } } // MARK: - LayoutPriority public enum LayoutPriority { case required case high case low case fittingSize case custom(Alias.LayoutPriority) var value: Alias.LayoutPriority { switch self { case .required: return Alias.LayoutPriorityRequired case .high: return Alias.LayoutPriorityHigh case .low: return Alias.LayoutPriorityLow case .fittingSize: return Alias.LayoutPriorityFittingSize case .custom(let priority): return priority } } } // MARK: - EdgeAnchorsProvider public protocol AnchorGroupProvider { var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { get } var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { get } var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { get } } extension AnchorGroupProvider { public var edgeAnchors: EdgeAnchors { return EdgeAnchors(horizontal: horizontalAnchors, vertical: verticalAnchors) } } extension Alias.View: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } } extension Alias.ViewController: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: view.leadingAnchor, second: view.trailingAnchor) } #if os(macOS) public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: view.bottomAnchor, second: view.topAnchor) } #else public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { // if #available(iOS 11.0, *) { // return AnchorPair(first: view.safeAreaLayoutGuide.topAnchor, // second: view.safeAreaLayoutGuide.bottomAnchor) // } else { return AnchorPair(first: topLayoutGuide.bottomAnchor, second: bottomLayoutGuide.topAnchor) // } } #endif public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: view.centerXAnchor, second: view.centerYAnchor) } } extension Alias.LayoutGuide: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } } // MARK: - AnchorGroup public struct AnchorPair<T: LayoutAxisType, U: LayoutAxisType>: LayoutAnchorType { private var first: T private var second: U init(first: T, second: U) { self.first = first self.second = second } public func activate(constraintsEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> AxisGroup { let builder = ConstraintBuilder(horizontal: ==, vertical: ==) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsLessThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> AxisGroup { let builder = ConstraintBuilder(leading: <=, top: <=, trailing: >=, bottom: >=, centerX: <=, centerY: <=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsGreaterThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> AxisGroup { let builder = ConstraintBuilder(leading: >=, top: >=, trailing: <=, bottom: <=, centerX: >=, centerY: >=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } func constraints(forAnchors anchors: AnchorPair<T, U>?, constant c: CGFloat, priority: LayoutPriority, builder: ConstraintBuilder) -> AxisGroup { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } switch (first, anchors.first, second, anchors.second) { // Leading, trailing case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, secondX as NSLayoutXAxisAnchor, otherSecondX as NSLayoutXAxisAnchor): return AxisGroup(first: builder.leadingBuilder(firstX, otherFirstX + c ~ priority), second: builder.trailingBuilder(secondX, otherSecondX - c ~ priority)) //Top, bottom case let (firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor, secondY as NSLayoutYAxisAnchor, otherSecondY as NSLayoutYAxisAnchor): return AxisGroup(first: builder.topBuilder(firstY, otherFirstY + c ~ priority), second: builder.bottomBuilder(secondY, otherSecondY - c ~ priority)) //CenterX, centerY case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor): return AxisGroup(first: builder.leadingBuilder(firstX, otherFirstX + c ~ priority), second: builder.topBuilder(firstY, otherFirstY - c ~ priority)) default: preconditionFailure("Layout axes of constrained anchors must match.") } } } public struct EdgeAnchors: LayoutAnchorType { var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> init(horizontal: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor>, vertical: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor>) { self.horizontalAnchors = horizontal self.verticalAnchors = vertical } public func activate(constraintsEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> EdgeGroup { let builder = ConstraintBuilder(horizontal: ==, vertical: ==) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsLessThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> EdgeGroup { let builder = ConstraintBuilder(leading: <=, top: <=, trailing: >=, bottom: >=, centerX: <=, centerY: <=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsGreaterThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: LayoutPriority = .required) -> EdgeGroup { let builder = ConstraintBuilder(leading: >=, top: >=, trailing: <=, bottom: <=, centerX: >=, centerY: >=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } func constraints(forAnchors anchors: EdgeAnchors?, constant c: CGFloat, priority: LayoutPriority, builder: ConstraintBuilder) -> EdgeGroup { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } let horizontalConstraints = horizontalAnchors.constraints(forAnchors: anchors.horizontalAnchors, constant: c, priority: priority, builder: builder) let verticalConstraints = verticalAnchors.constraints(forAnchors: anchors.verticalAnchors, constant: c, priority: priority, builder: builder) return EdgeGroup(top: verticalConstraints.first, leading: horizontalConstraints.first, bottom: verticalConstraints.second, trailing: verticalConstraints.second) } } // MARK: - ConstraintGroup public struct EdgeGroup { public var top: NSLayoutConstraint public var leading: NSLayoutConstraint public var bottom: NSLayoutConstraint public var trailing: NSLayoutConstraint public var horizontal: [NSLayoutConstraint] { return [leading, trailing] } public var vertical: [NSLayoutConstraint] { return [top, bottom] } public var all: [NSLayoutConstraint] { return [top, leading, bottom, trailing] } } public struct AxisGroup { public var first: NSLayoutConstraint public var second: NSLayoutConstraint } // MARK: - Constraint Builders struct ConstraintBuilder { typealias Horizontal = (NSLayoutXAxisAnchor, LayoutExpression<NSLayoutXAxisAnchor>) -> NSLayoutConstraint typealias Vertical = (NSLayoutYAxisAnchor, LayoutExpression<NSLayoutYAxisAnchor>) -> NSLayoutConstraint var topBuilder: Vertical var leadingBuilder: Horizontal var bottomBuilder: Vertical var trailingBuilder: Horizontal var centerYBuilder: Vertical var centerXBuilder: Horizontal #if swift(>=3.0) init(horizontal: @escaping Horizontal, vertical: @escaping Vertical) { topBuilder = vertical leadingBuilder = horizontal bottomBuilder = vertical trailingBuilder = horizontal centerYBuilder = vertical centerXBuilder = horizontal } init(leading: @escaping Horizontal, top: @escaping Vertical, trailing: @escaping Horizontal, bottom: @escaping Vertical, centerX: @escaping Horizontal, centerY: @escaping Vertical) { leadingBuilder = leading topBuilder = top trailingBuilder = trailing bottomBuilder = bottom centerYBuilder = centerY centerXBuilder = centerX } #else init(horizontal: Horizontal, vertical: Vertical) { topBuilder = vertical leadingBuilder = horizontal bottomBuilder = vertical trailingBuilder = horizontal centerYBuilder = vertical centerXBuilder = horizontal } init(leading: Horizontal, top: Vertical, trailing: Horizontal, bottom: Vertical, centerX: Horizontal, centerY: Vertical) { leadingBuilder = leading topBuilder = top trailingBuilder = trailing bottomBuilder = bottom centerYBuilder = centerY centerXBuilder = centerX } #endif } // MARK: - Constraint Activation func activate(constraint theConstraint: NSLayoutConstraint, withPriority priority: LayoutPriority = .required) -> NSLayoutConstraint { // Only disable autoresizing constraints on the LHS item, which is the one definitely intended to be governed by Auto Layout if let first = theConstraint.firstItem as? Alias.View{ first.translatesAutoresizingMaskIntoConstraints = false } theConstraint.priority = priority.value theConstraint.isActive = true return theConstraint }
mit
6b818b8b5cd32c8a8145ef9922747ef1
40.720414
168
0.703932
5.21216
false
false
false
false
hankbao/raven-swift
Raven/RavenConfig.swift
2
1962
// // RavenConfig.swift // Raven-Swift // // Created by Tommy Mikalsen on 03.09.14. // import Foundation public class RavenConfig { let serverUrl: NSURL! let publicKey: String! let secretKey: String! let projectId: String! public init? (DSN : String) { if let DSNURL = NSURL(string: DSN), host = DSNURL.host { var pathComponents = DSNURL.pathComponents as! [String] pathComponents.removeAtIndex(0) // always remove the first slash if let projectId = pathComponents.last { self.projectId = projectId pathComponents.removeLast() // remove the project id... var path = "/".join(pathComponents) // ...and construct the path again // Add a slash to the end of the path if there is a path if (path != "") { path += "/" } var scheme: String = DSNURL.scheme ?? "http" var port = DSNURL.port if (port == nil) { if (DSNURL.scheme == "https") { port = 443; } else { port = 80; } } //Setup the URL serverUrl = NSURL(string: "\(scheme)://\(host):\(port!)\(path)/api/\(projectId)/store/") //Set the public and secret keys if the exist publicKey = DSNURL.user ?? "" secretKey = DSNURL.password ?? "" return } } //The URL couldn't be parsed, so initialize to blank values and return nil serverUrl = NSURL() publicKey = "" secretKey = "" projectId = "" return nil } }
mit
c4c2b19ad9b6e516e3a3e13fb4a84e65
29.65625
104
0.441386
5.526761
false
false
false
false
frootloops/swift
stdlib/public/core/MutableCollection.swift
1
10133
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements. /// /// In most cases, it's best to ignore this protocol and use the /// `MutableCollection` protocol instead, because it has a more complete /// interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'MutableCollection' instead") public typealias MutableIndexable = MutableCollection /// A collection that supports subscript assignment. /// /// Collections that conform to `MutableCollection` gain the ability to /// change the value of their elements. This example shows how you can /// modify one of the names in an array of students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] /// if let i = students.index(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Max"]" /// /// In addition to changing the value of an individual element, you can also /// change the values of a slice of elements in a mutable collection. For /// example, you can sort *part* of a mutable collection by calling the /// mutable `sort()` method on a subscripted subsequence. Here's an /// example that sorts the first half of an array of integers: /// /// var numbers = [15, 40, 10, 30, 60, 25, 5, 100] /// numbers[0..<4].sort() /// print(numbers) /// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]" /// /// The `MutableCollection` protocol allows changing the values of a /// collection's elements but not the length of the collection itself. For /// operations that require adding or removing elements, see the /// `RangeReplaceableCollection` protocol instead. /// /// Conforming to the MutableCollection Protocol /// ============================================ /// /// To add conformance to the `MutableCollection` protocol to your own /// custom collection, upgrade your type's subscript to support both read /// and write access. /// /// A value stored into a subscript of a `MutableCollection` instance must /// subsequently be accessible at that same position. That is, for a mutable /// collection instance `a`, index `i`, and value `x`, the two sets of /// assignments in the following code sample must be equivalent: /// /// a[i] = x /// let y = a[i] /// /// // Must be equivalent to: /// a[i] = x /// let y = x public protocol MutableCollection: Collection where SubSequence: MutableCollection { // FIXME(ABI): Associated type inference requires this. associatedtype Element // FIXME(ABI): Associated type inference requires this. associatedtype Index // FIXME(ABI): Associated type inference requires this. associatedtype SubSequence = Slice<Self> /// Accesses the element at the specified position. /// /// For example, you can replace an element of an array by using its /// subscript. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one /// past the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. subscript(position: Index) -> Element { get set } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence { get set } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*) mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index /// Exchanges the values at the specified indices of the collection. /// /// Both parameters must be valid indices of the collection and not /// equal to `endIndex`. Passing the same index as both `i` and `j` has no /// effect. /// /// - Parameters: /// - i: The index of the first value to swap. /// - j: The index of the second value to swap. mutating func swapAt(_ i: Index, _ j: Index) /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? } // TODO: swift-3-indexing-model - review the following extension MutableCollection { @_inlineable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. @_inlineable public subscript(bounds: Range<Index>) -> Slice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } /// Exchanges the values at the specified indices of the collection. /// /// Both parameters must be valid indices of the collection that are not /// equal to `endIndex`. Calling `swapAt(_:_:)` with the same index as both /// `i` and `j` has no effect. /// /// - Parameters: /// - i: The index of the first value to swap. /// - j: The index of the second value to swap. @_inlineable public mutating func swapAt(_ i: Index, _ j: Index) { guard i != j else { return } let tmp = self[i] self[i] = self[j] self[j] = tmp } }
apache-2.0
f3d903e6ca3e54d7bb3ce35aca0b63aa
39.532
110
0.645515
4.282756
false
false
false
false
adrfer/swift
test/SILGen/init_ref_delegation.swift
4
8177
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation1SC{{.*}} : $@convention(thin) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $S // CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1SC{{.*}} : $@convention(thin) (X, @thin S.Type) -> S // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(thin) (@thin X.Type) -> X // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(thin) (@thin X.Type) -> X // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(thin) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[SELF]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [[SELF]] : $*S // CHECK-NEXT: strong_release [[SELF_BOX]] : $@box S // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // CHECK-LABEL: sil hidden @_TFO19init_ref_delegation1EC{{.*}} : $@convention(thin) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box $E // CHECK: [[PB:%.*]] = project_box [[E_BOX]] // CHECK: [[E_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*E // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFO19init_ref_delegation1EC{{.*}} : $@convention(thin) (X, @thin E.Type) -> E // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(thin) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(thin) (@thin X.Type) -> X // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(thin) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[E_SELF]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [[E_SELF]] : $*E self.init(x: X()) // CHECK: strong_release [[E_BOX]] : $@box E // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(thin) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $S2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S2 // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(thin) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(thin) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(thin) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [[X_BOX]] : $*X // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(thin) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: assign [[SELF_BOX1]] to [[SELF]] : $*S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: [[SELF_BOX4:%[0-9]+]] = load [[SELF]] : $*S2 self.init(t: X()) // CHECK: strong_release [[SELF_BOX]] : $@box S2 // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C1c{{.*}} : $@convention(method) (X, @owned C1) -> @owned C1 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $C1 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C1 // CHECK: store [[ORIG_SELF]] to [[SELF]] : $*C1 // CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load [[SELF]] : $*C1 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : C1.Type -> (x1: X, x2: X) -> C1 , $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: store [[SELFP]] to [[SELF]] : $*C1 // CHECK: [[SELFP:%[0-9]+]] = load [[SELF]] : $*C1 // CHECK: strong_retain [[SELFP]] : $C1 // CHECK: strong_release [[SELF_BOX]] : $@box C1 // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2c{{.*}} : $@convention(method) (X, @owned C2) -> @owned C2 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $C2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C2 // CHECK: store [[ORIG_SELF]] to [[UNINIT_SELF]] : $*C2 // CHECK: [[SELF:%[0-9]+]] = load [[UNINIT_SELF]] : $*C2 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : C2.Type -> (x1: X, x2: X) -> C2 , $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: store [[REPLACE_SELF]] to [[UNINIT_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [[UNINIT_SELF]] : $*C2 // CHECK: strong_retain [[VAR_15]] : $C2 // CHECK: strong_release [[SELF_BOX]] : $@box C2 // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2C{{.*}} : $@convention(thin) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C3c{{.*}} : $@convention(method) (@owned C3) -> @owned C3 convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : C3.Type -> (x: X) -> C3 , $@convention(method) (X, @owned C3) -> @owned C3 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: [[PEER:%[0-9]+]] = function_ref @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
apache-2.0
14719e1e9e840516e2dc93b28f66c66a
40.277778
189
0.530894
2.778987
false
false
false
false
mac-cain13/R.swift
Sources/RswiftCore/SwiftTypes/CodeGenerators/OSPrinter.swift
2
871
// // OSPrinter.swift // RswiftCore // // Created by Lammert Westerhoff on 28/08/2018. // import Foundation /// Prints the code wrapped inside #if os(...) / #endif preprocessors if the code is only supported by certain operating systems struct OSPrinter: SwiftCodeConverible { let swiftCode: String init(code: String, supportedOS: [String]) { guard supportedOS.count > 0 else { swiftCode = code return } let preprocessorStartString = supportedOS.enumerated().reduce("") { result, item in let (index, os) = item var result = result if index == 0 { result += "#if " } else { result += " || " } return result + "os(\(os))" } swiftCode = "\(preprocessorStartString)\n\(code)\n#endif" } }
mit
5ae9e721419117413233cbcbf2c019e1
26.21875
128
0.551091
4.24878
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Transition/PickerInteractiveTransition.swift
1
28874
// // PickerInteractiveTransition.swift // HXPHPickerExample // // Created by Slience on 2020/12/26. // Copyright © 2020 Silence. All rights reserved. // import UIKit public enum PickerInteractiveTransitionType { case pop case dismiss } class PickerInteractiveTransition: UIPercentDrivenInteractiveTransition, UIGestureRecognizerDelegate { var type: PickerInteractiveTransitionType weak var previewViewController: PhotoPreviewViewController? weak var pickerController: PhotoPickerController? lazy var panGestureRecognizer: UIPanGestureRecognizer = { let panGestureRecognizer = UIPanGestureRecognizer( target: self, action: #selector(panGestureRecognizerAction(panGR:)) ) return panGestureRecognizer }() lazy var backgroundView: UIView = { let backgroundView = UIView() return backgroundView }() var previewView: PhotoPreviewViewCell? var toView: UIView? var beforePreviewFrame: CGRect = .zero var previewCenter: CGPoint = .zero var beganPoint: CGPoint = .zero var canInteration: Bool = false var beganInterPercent: Bool = false var previewBackgroundColor: UIColor? var pickerControllerBackgroundColor: UIColor? weak var transitionContext: UIViewControllerContextTransitioning? var slidingGap: CGPoint = .zero var navigationBarAlpha: CGFloat = 1 var canTransition: Bool = false init( panGestureRecognizerFor previewViewController: PhotoPreviewViewController, type: PickerInteractiveTransitionType ) { self.type = type super.init() self.previewViewController = previewViewController panGestureRecognizer.delegate = self previewViewController.view.addGestureRecognizer(panGestureRecognizer) } init( panGestureRecognizerFor pickerController: PhotoPickerController, type: PickerInteractiveTransitionType) { self.type = type super.init() self.pickerController = pickerController panGestureRecognizer.delegate = self pickerController.view.addGestureRecognizer(panGestureRecognizer) } public func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer is UITapGestureRecognizer && otherGestureRecognizer.view is UIScrollView { return false } return !(previewViewController?.collectionView.isDragging ?? false) } @objc func panGestureRecognizerAction(panGR: UIPanGestureRecognizer) { let preposition = prepositionInteration(panGR: panGR) if !preposition.0 { return } let isTracking = preposition.1 switch panGR.state { case .began: beginInteration(panGR: panGR) case .changed: changeInteration( panGR: panGR, isTracking: isTracking ) case .ended, .cancelled, .failed: endInteration(panGR: panGR) default: break } } func prepositionInteration( panGR: UIPanGestureRecognizer) -> (Bool, Bool) { var isTracking = false if type == .pop { if let cell = previewViewController?.getCell( for: previewViewController?.currentPreviewIndex ?? 0), let contentView = cell.scrollContentView { let toRect = contentView.convert(contentView.bounds, to: cell.scrollView) if (cell.scrollView.isZooming || cell.scrollView.isZoomBouncing || cell.scrollView.contentOffset.y > 0 || !cell.allowInteration || (toRect.minX != 0 && contentView.width > cell.scrollView.width)) && !canInteration { return (false, isTracking) }else { isTracking = cell.scrollView.isTracking } } }else { let previewVC = pickerController?.previewViewController if pickerController?.topViewController != previewVC { return (false, isTracking) } if let cell = previewVC?.getCell( for: previewVC?.currentPreviewIndex ?? 0), let contentView = cell.scrollContentView { let toRect = contentView.convert(contentView.bounds, to: cell.scrollView) if (cell.scrollView.isZooming || cell.scrollView.isZoomBouncing || cell.scrollView.contentOffset.y > 0 || !cell.allowInteration || (toRect.minX != 0 && contentView.width > cell.scrollView.width)) && !canInteration { return (false, isTracking) }else { isTracking = cell.scrollView.isTracking } } } return (true, isTracking) } func beginInteration(panGR: UIPanGestureRecognizer) { if canInteration { return } if type == .pop, let previewViewController = previewViewController { let velocity = panGR.velocity(in: previewViewController.view) let isVerticalGesture = (abs(velocity.y) > abs(velocity.x) && velocity.y > 0) if !isVerticalGesture { return } beganPoint = panGR.location(in: panGR.view) canInteration = true canTransition = true previewViewController.navigationController?.popViewController(animated: true) }else if type == .dismiss, let pickerController = pickerController { let velocity = panGR.velocity(in: pickerController.view) let isVerticalGesture = (abs(velocity.y) > abs(velocity.x) && velocity.y > 0) if !isVerticalGesture { return } beganPoint = panGR.location(in: panGR.view) canInteration = true canTransition = true pickerController.dismiss(animated: true, completion: nil) } } func changeInteration( panGR: UIPanGestureRecognizer, isTracking: Bool) { if !canInteration || !beganInterPercent { if isTracking { beginInteration(panGR: panGR) if canInteration { slidingGap = panGR.translation(in: panGR.view) } } return } if let previewViewController = previewViewController, let previewView = previewView { let translation = panGR.translation(in: panGR.view) var scale = (translation.y - slidingGap.y) / (previewViewController.view.height) if scale > 1 { scale = 1 }else if scale < 0 { scale = 0 } var previewViewScale = 1 - scale if previewViewScale < 0.4 { previewViewScale = 0.4 } previewView.center = CGPoint( x: previewCenter.x + (translation.x - slidingGap.x), y: previewCenter.y + (translation.y - slidingGap.y) ) previewView.transform = CGAffineTransform.init(scaleX: previewViewScale, y: previewViewScale) var alpha = 1 - scale * 2 if alpha < 0 { alpha = 0 } backgroundView.alpha = alpha let toVC = transitionContext?.viewController(forKey: .to) as? PhotoPickerViewController if !previewViewController.statusBarShouldBeHidden { let hasPreviewMask = previewViewController.bottomView.mask != nil if hasPreviewMask { var bottomViewAlpha = 1 - scale * 1.5 if bottomViewAlpha < 0 { bottomViewAlpha = 0 } previewViewController.bottomView.alpha = bottomViewAlpha }else { previewViewController.bottomView.alpha = alpha } if type == .pop { var maskScale = 1 - scale * 2.85 if maskScale < 0 { maskScale = 0 } if hasPreviewMask { let maskY = 70 * (1 - maskScale) let maskWidth = previewViewController.bottomView.width let maskHeight = previewViewController.bottomView.height - maskY previewViewController.bottomView.mask?.frame = CGRect( x: 0, y: maskY, width: maskWidth, height: maskHeight ) } if toVC?.bottomView.mask != nil { let maskY = 70 * maskScale let maskWidth = previewViewController.bottomView.width let maskHeight = 50 + UIDevice.bottomMargin + 70 * (1 - maskScale) toVC?.bottomView.mask?.frame = CGRect(x: 0, y: maskY, width: maskWidth, height: maskHeight) } }else { previewViewController.navigationController?.navigationBar.alpha = alpha navigationBarAlpha = alpha } }else { if type == .pop { toVC?.navigationController?.navigationBar.alpha = 1 - alpha toVC?.bottomView.alpha = 1 - alpha } } if let picker = pickerController { picker.pickerDelegate? .pickerController(picker, interPercentUpdate: alpha, type: type) } update(1 - alpha) } } func endInteration( panGR: UIPanGestureRecognizer) { canTransition = false if !canInteration { return } if let previewViewController = previewViewController { let translation = panGR.translation(in: panGR.view) let scale = (translation.y - slidingGap.y) / (previewViewController.view.height) if scale < 0.15 { cancel() interPercentDidCancel() }else { finish() interPercentDidFinish() } }else { finish() backgroundView.removeFromSuperview() previewView?.removeFromSuperview() previewView = nil previewViewController = nil toView = nil transitionContext?.completeTransition(true) transitionContext = nil } slidingGap = .zero } func interPercentDidCancel() { if let previewViewController = previewViewController, let previewView = previewView { panGestureRecognizer.isEnabled = false previewViewController.navigationController?.view.isUserInteractionEnabled = false let toVC = self.transitionContext?.viewController(forKey: .to) as? PhotoPickerViewController UIView.animate(withDuration: 0.25) { previewView.transform = .identity previewView.center = self.previewCenter self.backgroundView.alpha = 1 if !previewViewController.statusBarShouldBeHidden { previewViewController.bottomView.alpha = 1 if self.type == .pop { let maskWidth = previewViewController.bottomView.width if previewViewController.bottomView.mask != nil { let maskHeight = previewViewController.bottomView.height previewViewController.bottomView.mask?.frame = CGRect( origin: .zero, size: CGSize( width: maskWidth, height: maskHeight ) ) } if toVC?.bottomView.mask != nil { let maskHeight = 50 + UIDevice.bottomMargin toVC?.bottomView.mask?.frame = CGRect(x: 0, y: 70, width: maskWidth, height: maskHeight) } }else { previewViewController.navigationController?.navigationBar.alpha = 1 } }else { if self.type == .pop { toVC?.navigationController?.navigationBar.alpha = 0 toVC?.bottomView.alpha = 0 } } if let picker = self.pickerController { picker.pickerDelegate? .pickerController(picker, interPercentDidCancelAnimation: self.type) } } completion: { (isFinished) in previewViewController.bottomView.mask = nil toVC?.bottomView.mask = nil self.toView?.isHidden = false let toVC = self.transitionContext?.viewController(forKey: .to) as? PhotoPickerViewController if previewViewController.statusBarShouldBeHidden { if self.type == .pop { previewViewController.navigationController?.setNavigationBarHidden(true, animated: false) toVC?.navigationController?.setNavigationBarHidden(true, animated: false) toVC?.bottomView.alpha = 1 toVC?.navigationController?.navigationBar.alpha = 1 } } self.resetScrollView(for: true) previewView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) previewView.frame = self.beforePreviewFrame previewViewController.collectionView.addSubview(previewView) previewView.scrollContentView.showOtherSubview() self.backgroundView.removeFromSuperview() self.previewView = nil self.toView = nil self.panGestureRecognizer.isEnabled = true self.canInteration = false self.beganInterPercent = false previewViewController.navigationController?.view.isUserInteractionEnabled = true self.transitionContext?.completeTransition(false) self.transitionContext = nil } }else { toView?.isHidden = false toView = nil } } func interPercentDidFinish() { if let previewViewController = previewViewController, let previewView = previewView { panGestureRecognizer.isEnabled = false var toRect = toView?.convert(toView?.bounds ?? .zero, to: transitionContext?.containerView) ?? .zero if type == .dismiss, let pickerController = pickerController { if toRect.isEmpty { toRect = pickerController.pickerDelegate?.pickerController( pickerController, dismissPreviewFrameForIndexAt: previewViewController.currentPreviewIndex ) ?? .zero } if let toView = toView, toView.layer.cornerRadius > 0 { previewView.layer.masksToBounds = true } if pickerController.config.prefersStatusBarHidden && !previewViewController.statusBarShouldBeHidden { previewViewController.navigationController?.navigationBar.alpha = navigationBarAlpha } } previewView.scrollContentView.isBacking = true let toVC = self.transitionContext?.viewController(forKey: .to) as? PhotoPickerViewController UIView.animate( withDuration: 0.45, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [.layoutSubviews, .curveEaseOut] ) { if let toView = self.toView, toView.layer.cornerRadius > 0 { previewView.layer.cornerRadius = toView.layer.cornerRadius } if !toRect.isEmpty { previewView.transform = .identity previewView.frame = toRect previewView.scrollView.contentOffset = .zero previewView.scrollContentView.frame = CGRect(x: 0, y: 0, width: toRect.width, height: toRect.height) }else { previewView.alpha = 0 previewView.transform = CGAffineTransform.init(scaleX: 0.1, y: 0.1) } self.backgroundView.alpha = 0 if !previewViewController.statusBarShouldBeHidden { previewViewController.bottomView.alpha = 0 if self.type == .pop { let maskWidth = previewViewController.bottomView.width if previewViewController.bottomView.mask != nil { let maskHeight = previewViewController.bottomView.height - 70 previewViewController.bottomView.mask?.frame = CGRect( x: 0, y: 70, width: maskWidth, height: maskHeight ) } if toVC?.bottomView.mask != nil { let maskHeight = UIDevice.bottomMargin + 120 toVC?.bottomView.mask?.frame = CGRect(x: 0, y: 0, width: maskWidth, height: maskHeight) } }else { previewViewController.navigationController?.navigationBar.alpha = 0 } }else { if self.type == .pop { toVC?.bottomView.alpha = 1 toVC?.navigationController?.navigationBar.alpha = 1 } } if let picker = self.pickerController { picker.pickerDelegate? .pickerController(picker, interPercentDidFinishAnimation: self.type) } } completion: { (isFinished) in previewViewController.bottomView.mask = nil toVC?.bottomView.mask = nil self.toView?.isHidden = false UIView.animate(withDuration: 0.2) { previewView.alpha = 0 } completion: { (isFinished) in self.backgroundView.removeFromSuperview() previewView.removeFromSuperview() if self.type == .dismiss, let pickerController = self.pickerController { pickerController.pickerDelegate?.pickerController( pickerController, previewDismissComplete: previewViewController.currentPreviewIndex ) }else if self.type == .pop { toVC?.collectionView.layer.removeAllAnimations() } self.previewView = nil self.previewViewController = nil self.toView = nil self.panGestureRecognizer.isEnabled = true self.transitionContext?.completeTransition(true) self.transitionContext = nil } } }else { toView?.isHidden = false toView = nil } } public override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext if type == .pop { popTransition(transitionContext) }else { dismissTransition(transitionContext) } } func popTransition(_ transitionContext: UIViewControllerContextTransitioning) { let previewViewController = transitionContext.viewController(forKey: .from) as! PhotoPreviewViewController previewBackgroundColor = previewViewController.view.backgroundColor previewViewController.view.backgroundColor = .clear let pickerViewController = transitionContext.viewController(forKey: .to) as! PhotoPickerViewController let containerView = transitionContext.containerView containerView.addSubview(pickerViewController.view) containerView.addSubview(previewViewController.view) if !canTransition { self.previewViewController?.view.removeGestureRecognizer(panGestureRecognizer) canInteration = false beganInterPercent = false self.cancel() UIView.animate(withDuration: 0.25) { if !previewViewController.statusBarShouldBeHidden { previewViewController.bottomView.alpha = 1 if AssetManager.authorizationStatusIsLimited() && pickerViewController.config.bottomView.showPrompt { pickerViewController.bottomView.alpha = 0 } } } completion: { (_) in transitionContext.completeTransition(false) self.previewViewController?.view.addGestureRecognizer(self.panGestureRecognizer) } return } backgroundView.frame = pickerViewController.view.bounds backgroundView.backgroundColor = previewBackgroundColor pickerViewController.view.insertSubview(backgroundView, at: 1) if !previewViewController.previewAssets.isEmpty { let photoAsset = previewViewController.previewAssets[previewViewController.currentPreviewIndex] pickerViewController.setCellLoadMode(.complete) if let pickerCell = pickerViewController.getCell(for: photoAsset) { pickerViewController.scrollCellToVisibleArea(pickerCell) DispatchQueue.main.async { pickerViewController.cellReloadImage() } toView = pickerCell }else { pickerViewController.scrollToCenter(for: photoAsset) pickerViewController.reloadCell(for: photoAsset) DispatchQueue.main.async { pickerViewController.cellReloadImage() } let pickerCell = pickerViewController.getCell(for: photoAsset) toView = pickerCell } } if let previewCell = previewViewController.getCell(for: previewViewController.currentPreviewIndex) { beforePreviewFrame = previewCell.frame previewView = previewCell } previewView?.scrollView.clipsToBounds = false if let previewView = previewView { let anchorPoint = CGPoint(x: beganPoint.x / previewView.width, y: beganPoint.y / previewView.height) previewView.layer.anchorPoint = anchorPoint previewView.frame = pickerViewController.view.bounds previewCenter = previewView.center pickerViewController.view.insertSubview(previewView, aboveSubview: backgroundView) } var pickerShowParompt = false var previewShowSelectedView = false if previewViewController.statusBarShouldBeHidden { pickerViewController.bottomView.alpha = 0 pickerViewController.navigationController?.navigationBar.alpha = 0 previewViewController.navigationController?.setNavigationBarHidden(false, animated: false) }else { if previewViewController.config.bottomView.showSelectedView == true && previewViewController.pickerController?.config.selectMode == .multiple && !previewViewController.statusBarShouldBeHidden { if previewViewController.pickerController?.selectedAssetArray.isEmpty == false { previewShowSelectedView = true } } if AssetManager.authorizationStatusIsLimited() && previewViewController.config.bottomView.showPrompt { pickerShowParompt = true } } if previewShowSelectedView && !pickerShowParompt { let maskView = UIView( frame: CGRect( x: 0, y: 0, width: previewViewController.view.width, height: 120 + UIDevice.bottomMargin ) ) maskView.backgroundColor = .white previewViewController.bottomView.mask = maskView }else if !previewShowSelectedView && pickerShowParompt { let maskView = UIView( frame: CGRect( x: 0, y: 70, width: previewViewController.view.width, height: 50 + UIDevice.bottomMargin ) ) maskView.backgroundColor = .white pickerViewController.bottomView.mask = maskView } resetScrollView(for: false) toView?.isHidden = true beganInterPercent = true } func dismissTransition(_ transitionContext: UIViewControllerContextTransitioning) { let pickerController = transitionContext.viewController(forKey: .from) as! PhotoPickerController pickerControllerBackgroundColor = pickerController.view.backgroundColor pickerController.view.backgroundColor = .clear if let previewViewController = pickerController.previewViewController { self.previewViewController = previewViewController previewBackgroundColor = previewViewController.view.backgroundColor previewViewController.view.backgroundColor = .clear let containerView = transitionContext.containerView backgroundView.frame = containerView.bounds backgroundView.backgroundColor = previewBackgroundColor containerView.addSubview(backgroundView) if let view = pickerController.pickerDelegate?.pickerController( pickerController, dismissPreviewViewForIndexAt: previewViewController.currentPreviewIndex) { toView = view } if let previewCell = previewViewController.getCell(for: previewViewController.currentPreviewIndex) { previewCell.scrollContentView.hiddenOtherSubview() beforePreviewFrame = previewCell.frame previewView = previewCell } previewView?.scrollView.clipsToBounds = false if let previewView = previewView { let anchorPoint = CGPoint(x: beganPoint.x / previewView.width, y: beganPoint.y / previewView.height) previewView.layer.anchorPoint = anchorPoint previewView.frame = pickerController.view.bounds previewCenter = previewView.center containerView.addSubview(previewView) } containerView.addSubview(pickerController.view) previewViewController.collectionView.isScrollEnabled = false previewView?.scrollView.isScrollEnabled = false previewView?.scrollView.pinchGestureRecognizer?.isEnabled = false if let photoBrowser = pickerController as? PhotoBrowser { if photoBrowser.hideSourceView { toView?.isHidden = true } }else { toView?.isHidden = true } beganInterPercent = true } } func resetScrollView(for enabled: Bool) { previewViewController?.collectionView.isScrollEnabled = enabled previewView?.scrollView.isScrollEnabled = enabled previewView?.scrollView.pinchGestureRecognizer?.isEnabled = enabled previewView?.scrollView.clipsToBounds = enabled if enabled { previewViewController?.view.backgroundColor = self.previewBackgroundColor pickerController?.view.backgroundColor = self.pickerControllerBackgroundColor } } }
mit
f9c212a7ee53bb1d399200f9b0c912ee
44.976115
120
0.567935
6.640524
false
false
false
false
tiehuaz/iOS-Application-for-AURIN
AurinProject/SidebarMenu/FilterViewController.swift
1
11823
// // FilterViewController.swift // AurinProject // // Created by tiehuaz on 8/29/15. // Copyright (c) 2015 AppCoda. All rights reserved. // import UIKit import SWXMLHash /* This class controls the first interface of this app, which allows user to selection conditions * for cities, organisations, data types, and aggregation level. * this controller will first send GetCapibilities service in WFS to GeoServer to retrieve all simple information * for each dataset, the information is in XML format and will be parsed in this controller as well. * the parsed information will be stored into Singleton in order to dynamicallly generate GetFeature WFS query later */ class FilterViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate{ var URL: String? let user = Singleton.sharedInstance @IBOutlet weak var menuButton:UIBarButtonItem! @IBOutlet weak var city: UITextField! @IBOutlet weak var organisationType: UITextField! @IBOutlet weak var dataType: UITextField! @IBOutlet weak var aggChoices: UITextField! var pickOption = ["Sydney","Melbourne","Brisbane","Perth","Canberra","Default"] var organisation = ["ABS","DSDBI","VicHealth","Default"] var data = ["Housing","Population","Alcohol","Health","Default"] var Aggregation = ["SA4","SA3","SA2","SA1","LGA","SLA","Default"] var myPickerForCity = UIPickerView() var myPickerForOrganisation = UIPickerView() var myPickerForData = UIPickerView() var myPickerForAggregation = UIPickerView() var toolBarCity = UIToolbar() var toolBarOrganisation = UIToolbar() var toolBarData = UIToolbar() var toolBarAggregation = UIToolbar() override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } HTTPGetXML("https://geoserver.aurin.org.au/ows?service=WFS&version=1.0.0&request=GetCapabilities"){ (data: String, error: String?) -> Void in if error != nil{ print(error) }else { let xml = SWXMLHash.parse(data) let choices = xml["WFS_Capabilities"]["FeatureTypeList"]["FeatureType"] for element in choices{ var key : String = element["Title"].element!.text! var abstract = element["Abstract"].element!.text if abstract == nil{ abstract = "There is no description in this dataset." } var temp : String = abstract! if key == "housingstress" { var keyWordstoAdd = element["Keywords"].element!.text! var keyWordsAdded = "\(keyWordstoAdd), ABS" self.user.dataSet[key] = [element["Name"].element!.text!,keyWordsAdded,temp] }else if key == "LGA_IA_2011_population_by_gender" || key == "LGA_IA_2006_population_by_gender"{ var keyWordstoAdd = element["Keywords"].element!.text! var keyWordsAdded = "\(keyWordstoAdd), DSDBI, LGA" self.user.dataSet[key] = [element["Name"].element!.text!,keyWordsAdded,temp] }else if key == "alcohol_purchased_last_7_days"{ var keyWordstoAdd = element["Keywords"].element!.text! var keyWordsAdded = "\(keyWordstoAdd), vichealth, LGA, health" self.user.dataSet[key] = [element["Name"].element!.text!,keyWordsAdded,temp] }else{ self.user.dataSet[key] = [element["Name"].element!.text!,element["Keywords"].element!.text!,temp] } } } } } override func viewWillAppear(animated: Bool) { toolBarCity.barStyle = UIBarStyle.Default toolBarCity.translucent = true toolBarOrganisation.barStyle = UIBarStyle.Default toolBarOrganisation.translucent = true toolBarData.barStyle = UIBarStyle.Default toolBarData.translucent = true toolBarAggregation.barStyle = UIBarStyle.Default toolBarAggregation.translucent = true myPickerForCity.delegate=self myPickerForOrganisation.delegate = self myPickerForData.delegate = self myPickerForAggregation.delegate = self toolBarCity.sizeToFit() toolBarOrganisation.sizeToFit() toolBarData.sizeToFit() toolBarAggregation.sizeToFit() myPickerForCity.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height/5, UIScreen.mainScreen().bounds.width, 100) myPickerForOrganisation.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height/5, UIScreen.mainScreen().bounds.width, 100) myPickerForData.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height/5, UIScreen.mainScreen().bounds.width, 100) myPickerForAggregation.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height/5, UIScreen.mainScreen().bounds.width, 100) var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePressed1") var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "cancelPressed1") var doneButton1 = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePressed2") var spaceButton1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var cancelButton1 = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "cancelPressed2") var doneButton2 = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePressed3") var spaceButton2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var cancelButton2 = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "cancelPressed3") var doneButton3 = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePressed4") var spaceButton3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var cancelButton3 = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "cancelPressed4") toolBarCity.setItems([cancelButton, spaceButton, doneButton], animated: false) toolBarOrganisation.setItems([cancelButton1, spaceButton1, doneButton1], animated: false) toolBarData.setItems([cancelButton2, spaceButton2, doneButton2], animated: false) toolBarAggregation.setItems([cancelButton3, spaceButton3, doneButton3], animated: false) self.city.inputView = myPickerForCity; self.organisationType.inputView = myPickerForOrganisation; self.dataType.inputView = myPickerForData self.aggChoices.inputView = myPickerForAggregation city.inputAccessoryView = toolBarCity organisationType.inputAccessoryView = toolBarOrganisation dataType.inputAccessoryView = toolBarData aggChoices.inputAccessoryView = toolBarAggregation } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func filterCondition(sender: AnyObject) { self.user.dataCollection = [] print("\(organisationType.text!.lowercaseString)+++\(dataType.text!.lowercaseString)+++\(aggChoices.text!.lowercaseString)") var orgTemp = organisationType.text!.lowercaseString var dataTemp = dataType.text!.lowercaseString var aggTemp = aggChoices.text!.lowercaseString if (orgTemp=="" || orgTemp=="default"){ orgTemp=" " } if (dataTemp=="" || dataTemp=="default"){ dataTemp=" " } if (aggTemp=="" || aggTemp=="default"){ aggTemp=" " } for (key,value) in self.user.dataSet{ var keyEle = key as! String var keyWords = value[1].lowercaseString as! String if (keyWords.containsString(orgTemp)&&keyWords.containsString(dataTemp)&&keyWords.containsString(aggTemp)){ if keyEle == "housingstress"{ self.user.dataCollection.insert(keyEle, atIndex: 0) }else{ self.user.dataCollection.append(keyEle) } } } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{ return 1 } // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ if(pickerView == myPickerForCity){ return pickOption.count }else if (pickerView == myPickerForOrganisation){ return organisation.count }else if(pickerView == myPickerForData){ return data.count }else{ return Aggregation.count } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if(pickerView == myPickerForCity){ return pickOption[row] }else if(pickerView == myPickerForData){ return data[row] }else if(pickerView == myPickerForAggregation){ return Aggregation[row] }else{ return organisation[row] } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if(pickerView == myPickerForCity){ city.text = "\(pickOption[pickerView.selectedRowInComponent(0)])" }else if(pickerView == myPickerForData){ dataType.text = "\(data[pickerView.selectedRowInComponent(0)])" }else if(pickerView == myPickerForAggregation){ aggChoices.text = "\(Aggregation[pickerView.selectedRowInComponent(0)])" }else{ organisationType.text = "\(organisation[pickerView.selectedRowInComponent(0)])" } } func donePressed1() { city.resignFirstResponder() } func cancelPressed1() { city.text = "" city.resignFirstResponder() } func donePressed2() { organisationType.resignFirstResponder() } func cancelPressed2() { organisationType.text = "" organisationType.resignFirstResponder() } func donePressed3() { dataType.resignFirstResponder() } func cancelPressed3() { dataType.text = "" dataType.resignFirstResponder() } func donePressed4() { aggChoices.resignFirstResponder() } func cancelPressed4() { aggChoices.text = "" aggChoices.resignFirstResponder() } }
apache-2.0
22637e4acc27d4769a8bab4547835a93
40.052083
138
0.624884
5.415941
false
false
false
false
radu-costea/ATests
ATests/ATests/UI/EditAnswerViewController.swift
1
5053
// // EditAnswerViewController.swift // ATests // // Created by Radu Costea on 30/05/16. // Copyright © 2016 Radu Costea. All rights reserved. // import UIKit import Parse class EditAnswerViewController: EditContentController, EditVariantControllerDelegate { @IBOutlet var stackView: UIStackView! @IBOutlet var addAnswerView: UIView! @IBOutlet var activityView: UIActivityIndicatorView! var allowedTypes: [ContentType] = [.Text, .Image] var content: ParseAnswer? var variants: [ParseAnswerVariant] = [] override class var storyboardName: String { return "EditQuestionStoryboard" } override class var storyboardId: String { return "editAnswer" } class func controllerWithContent(content: ParseAnswer?) -> EditAnswerViewController? { let controller = self.controller() as? EditAnswerViewController controller?.content = content return controller } override func loadWith(content: PFObject?) { if let content = content as? ParseAnswer { self.content = content } } override func startEditing() { /* STUB */ } override func viewDidLoad() { super.viewDidLoad() /// Load variants addAnswerView.hidden = true content?.fetchIfNeededInBackgroundWithBlock { (success, error) in self.activityView.stopAnimating() self.addAnswerView.hidden = !self.editingEnabled self.variants = self.content?.variants ?? [] let controllers = self.variants.flatMap{ EditVariantController.controllerWithVariant($0) } for controller in controllers { self.setupVariantController(controller) } } } func setupVariantController(controller: EditVariantController) { controller.editingEnabled = editingEnabled controller.view.translatesAutoresizingMaskIntoConstraints = false addChildViewController(controller) let idx = stackView.arrangedSubviews.count - 1 stackView.insertArrangedSubview(controller.view, atIndex: idx) ///insertSubview(controller.view, aboveSubview: addAnswerView) controller.didMoveToParentViewController(self) controller.delegate = self print("insert at index: \(idx)") } @IBAction func didTapAddAnswer(sender: AnyObject?) { guard let answer = content else { return } showSelectContentType { [unowned self] type in let variantContent = type.createNewParseContent() let variant = ParseAnswerVariant() variant.index = Int32(self.variants.count) variant.content = variantContent self.variants.append(variant) answer.variants = self.variants AnimatingViewController.hide { let controller = self.addVariant(variant) controller?.startEditing() } } } func showSelectContentType(completion: (type: ContentType) -> Void) { let alert = UIAlertController(title: nil, message: "Please select content type", preferredStyle: .ActionSheet) var actions = allowedTypes.map { type in return UIAlertAction(title: type.name(), style: .Default, handler: { _ in completion(type: type) }) } actions.append(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) actions.forEach{ alert.addAction($0) } presentViewController(alert, animated: true, completion: nil) } /// MARK: - /// MARK: Edit Variant Controller Delegate func addVariant(variant: ParseAnswerVariant) -> EditVariantController? { guard let controller = EditVariantController.controllerWithVariant(variant) else { return nil } setupVariantController(controller) return controller } func editVariantControllerDidSelectDeleteVariant(controller: EditVariantController) { var answerVariants = variants guard let variant = controller.variant, let idx = answerVariants.indexOf({ $0.objectId == variant.objectId }) else { return } for i in (idx + 1)..<(answerVariants.count) { answerVariants[i - 1].index = answerVariants[i].index } answerVariants.removeAtIndex(idx) controller.removeFromParentViewController() controller.view.removeFromSuperview() if let answer = content { answer.variants = answerVariants AnimatingViewController.showInController(self, status: "Cleaning up data") variant.deleteInBackgroundWithBlock { (success, err) in AnimatingViewController.hide() } } } } extension EditContentFabric { class func variantsController(variants: ParseAnswer?) -> EditAnswerViewController? { return EditAnswerViewController.controllerWithContent(variants) } }
mit
94b150ad6fe54246b438b900ede10b9d
35.608696
133
0.645487
5.527352
false
false
false
false
Derek316x/iOS8-day-by-day
13-coreimage-detectors/LiveDetection/LiveDetection/CoreImageVideoFilter.swift
1
4879
// // Copyright 2014 Scott Logic // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import GLKit import AVFoundation import CoreMedia import CoreImage import OpenGLES import QuartzCore class CoreImageVideoFilter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { var applyFilter: ((CIImage) -> CIImage?)? var videoDisplayView: GLKView! var videoDisplayViewBounds: CGRect! var renderContext: CIContext! var avSession: AVCaptureSession? var sessionQueue: dispatch_queue_t! var detector: CIDetector? init(superview: UIView, applyFilterCallback: ((CIImage) -> CIImage?)?) { self.applyFilter = applyFilterCallback videoDisplayView = GLKView(frame: superview.bounds, context: EAGLContext(API: .OpenGLES2)) videoDisplayView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) videoDisplayView.frame = superview.bounds superview.addSubview(videoDisplayView) superview.sendSubviewToBack(videoDisplayView) renderContext = CIContext(EAGLContext: videoDisplayView.context) sessionQueue = dispatch_queue_create("AVSessionQueue", DISPATCH_QUEUE_SERIAL) videoDisplayView.bindDrawable() videoDisplayViewBounds = CGRect(x: 0, y: 0, width: videoDisplayView.drawableWidth, height: videoDisplayView.drawableHeight) } deinit { stopFiltering() } func startFiltering() { // Create a session if we don't already have one if avSession == nil { avSession = createAVSession() } // And kick it off avSession?.startRunning() } func stopFiltering() { // Stop the av session avSession?.stopRunning() } func createAVSession() -> AVCaptureSession? { // Input from video camera let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: device) // Start out with low quality let session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetMedium // Output let videoOutput = AVCaptureVideoDataOutput() videoOutput.videoSettings = nil videoOutput.alwaysDiscardsLateVideoFrames = true videoOutput.setSampleBufferDelegate(self, queue: sessionQueue) // Join it all together session.addInput(input) session.addOutput(videoOutput) return session } catch { return nil } } //MARK: <AVCaptureVideoDataOutputSampleBufferDelegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { // Need to shimmy this through type-hell let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)! // Force the type change - pass through opaque buffer let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer).toOpaque() let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue() let sourceImage = CIImage(CVPixelBuffer: pixelBuffer, options: nil) // Do some detection on the image let detectionResult = applyFilter?(sourceImage) var outputImage = sourceImage if detectionResult != nil { outputImage = detectionResult! } // Do some clipping var drawFrame = outputImage.extent let imageAR = drawFrame.width / drawFrame.height let viewAR = videoDisplayViewBounds.width / videoDisplayViewBounds.height if imageAR > viewAR { drawFrame.origin.x += (drawFrame.width - drawFrame.height * viewAR) / 2.0 drawFrame.size.width = drawFrame.height / viewAR } else { drawFrame.origin.y += (drawFrame.height - drawFrame.width / viewAR) / 2.0 drawFrame.size.height = drawFrame.width / viewAR } videoDisplayView.bindDrawable() if videoDisplayView.context != EAGLContext.currentContext() { EAGLContext.setCurrentContext(videoDisplayView.context) } // clear eagl view to grey glClearColor(0.5, 0.5, 0.5, 1.0); glClear(0x00004000) // set the blend mode to "source over" so that CI will use that glEnable(0x0BE2); glBlendFunc(1, 0x0303); renderContext.drawImage(outputImage, inRect: videoDisplayViewBounds, fromRect: drawFrame) videoDisplayView.display() } }
apache-2.0
2d5772af6ee596f1d8bf99f1fb248c21
31.972973
157
0.711416
5.050725
false
false
false
false
y16ra/CookieCrunch
CookieCrunch/GameViewController.swift
1
7135
// // GameViewController.swift // CookieCrunch // // Created by Ichimura Yuichi on 2015/07/31. // Copyright (c) 2015年 Ichimura Yuichi. All rights reserved. // import UIKit import SpriteKit import iAd import TwitterKit extension SKNode { } class GameViewController: UIViewController, ADBannerViewDelegate { @IBOutlet weak var adBanner: ADBannerView! var scene: GameScene! var level: Level! var movesLeft = 0 var score = 0 var currentLevel = 0 // ステージを増やしたら値を変更する必要がある let MAX_LEVEL = 4 @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var movesLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var gameOverPanel: UIImageView! var tapGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var shuffleButton: UIButton! @IBAction func shuffleButtonPressed(_: AnyObject) { shuffle() decrementMoves() } override func viewDidLoad() { super.viewDidLoad() // let logInButton = TWTRLogInButton { (session, error) in // if let unwrappedSession = session { // let alert = UIAlertController(title: "Logged In", // message: "User \(unwrappedSession.userName) has logged in", // preferredStyle: UIAlertControllerStyle.Alert // ) // alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) // self.presentViewController(alert, animated: true, completion: nil) // } else { // NSLog("Login error: %@", error!.localizedDescription); // } // } // // TODO: Change where the log in button is positioned in your view // logInButton.center = self.view.center // self.view.addSubview(logInButton) // Configure the view. //let skView = view as! SKView let skView = originalContentView as! SKView skView.multipleTouchEnabled = false //for Dubug //skView.showsFPS = true //skView.showsNodeCount = true // Show iAd Banner //self.canDisplayBannerAds = true self.adBanner.delegate = self self.adBanner.hidden = true // Create and configure the scene. //scene = GameScene(size: skView.bounds.size) scene = GameScene(size: skView.frame.size) scene.scaleMode = .AspectFill level = Level(filename: "Level_" + String(currentLevel)) scene.level = level scene.addTiles() scene.swipeHandler = handleSwipe gameOverPanel.hidden = true // Present the scene. skView.presentScene(scene) beginGame() } func beginGame() { level.resetComboMultiplier() scene.animateBeginGame() { self.shuffleButton.hidden = false } shuffle() movesLeft = level.maximumMoves score = 0 updateLabels() } func shuffle() { scene.removeAllCookieSprites() let newCookies = level.shuffle() scene.addSpritesForCookies(newCookies) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } func handleSwipe(swap: Swap) { view.userInteractionEnabled = false if level.isPossibleSwap(swap) { level.performSwap(swap) scene.animateSwap(swap, completion: handleMatches) } else { scene.animateInvalidSwap(swap) { self.view.userInteractionEnabled = true } } } func handleMatches() { let chains = level.removeMatches() if chains.count == 0 { beginNextTurn() return } // TODO: do something with the chains set scene.animateMatchedCookies(chains) { for chain in chains { self.score += chain.score } self.updateLabels() let columns = self.level.fillHoles() self.scene.animateFallingCookies(columns) { let columns = self.level.topUpCookies() self.scene.animateNewCookies(columns) { //self.view.userInteractionEnabled = true self.handleMatches() } } } } func beginNextTurn() { level.resetComboMultiplier() level.detectPossibleSwaps() view.userInteractionEnabled = true decrementMoves() } func updateLabels() { targetLabel.text = String(format: "%ld", level.targetScore) movesLabel.text = String(format: "%ld", movesLeft) scoreLabel.text = String(format: "%ld", score) } func decrementMoves() { movesLeft -= 1 updateLabels() if score >= level.targetScore { gameOverPanel.image = UIImage(named: "LevelComplete") showGameOver() } else if movesLeft == 0 { gameOverPanel.image = UIImage(named: "GameOver") showGameOver() } } func showGameOver() { gameOverPanel.hidden = false scene.userInteractionEnabled = false shuffleButton.hidden = true // next level if currentLevel == MAX_LEVEL { currentLevel = 0 // 全部クリアしたら最初から } else { currentLevel += 1 } level = Level(filename: "Level_" + String(currentLevel)) scene.level = level scene.removeAllTiles() scene.addTiles() scene.animateGameOver() { self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GameViewController.hideGameOver)) self.view.addGestureRecognizer(self.tapGestureRecognizer) } } func hideGameOver() { view.removeGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer = nil gameOverPanel.hidden = true scene.userInteractionEnabled = true beginGame() } // iAd func bannerViewDidLoadAd(banner: ADBannerView!) { self.adBanner?.hidden = false } func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool { return willLeave } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { self.adBanner?.hidden = true } }
mit
f36402cf15906a7d046917c7d5425595
28.818565
128
0.590208
5.087833
false
false
false
false
Mobilette/MobiletteDashboardiOS
Pods/OAuthSwift/OAuthSwift/String+OAuthSwift.swift
1
3859
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { internal func indexOf(sub: String) -> Int? { var pos: Int? if let range = self.rangeOfString(sub) { if !range.isEmpty { pos = self.startIndex.distanceTo(range.startIndex) } } return pos } internal subscript (r: Range<Int>) -> String { get { let startIndex = self.startIndex.advancedBy(r.startIndex) let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String { let originalString: NSString = self let customAllowedSet = NSCharacterSet(charactersInString:" :/?&=;+!@#$()',*=\"#%/<>?@\\^`{|}").invertedSet let escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) return escapedString! as String } func parametersFromQueryString() -> Dictionary<String, String> { return dictionaryBySplitting("&", keyValueSeparator: "=") } var urlQueryEncoded: String? { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) } func dictionaryBySplitting(elementSeparator: String, keyValueSeparator: String) -> Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = NSScanner(string: self) var key: NSString? var value: NSString? while !scanner.atEnd { key = nil scanner.scanUpToString(keyValueSeparator, intoString: &key) scanner.scanString(keyValueSeparator, intoString: nil) value = nil scanner.scanUpToString(elementSeparator, intoString: &value) scanner.scanString(elementSeparator, intoString: nil) if (key != nil && value != nil) { parameters.updateValue(value! as String, forKey: key! as String) } } return parameters } public var headerDictionary: Dictionary<String, String> { return dictionaryBySplitting(",", keyValueSeparator: "=") } var safeStringByRemovingPercentEncoding: String { return self.stringByRemovingPercentEncoding ?? self } func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self.characters{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } func length()->Int{ return self.utf16.count } func size()->Int{ return self.utf16.count } func `repeat`(times: Int) -> String{ var result = "" for _ in 0..<times { result += self } return result } func reverse()-> String{ let s=Array(self.split("").reverse()) var x="" for y in s{ x+=y } return x } }
mit
3c5f501523fa014831c7f64986faf9f2
26.963768
116
0.571392
5.064304
false
false
false
false
Kofktu/KUIPopOver
Example/ViewController.swift
1
5849
// // ViewController.swift // Example // // Created by kofktu on 2017. 8. 31.. // Copyright © 2017년 Kofktu. All rights reserved. // import UIKit import KUIPopOver import WebKit class ViewController: UIViewController { // MARK: - Action @IBAction func onDefaultPopoverShow(_ sender: UIButton) { let popOverViewController = DefaultPopOverViewController() popOverViewController.preferredContentSize = CGSize(width: 200.0, height: 300.0) popOverViewController.popoverPresentationController?.sourceView = sender let customView = CustomPopOverView(frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: 200.0, height: 300.0))) popOverViewController.view.addSubview(customView) popOverViewController.popoverPresentationController?.sourceRect = sender.bounds present(popOverViewController, animated: true, completion: nil) } @IBAction func onBarButtonItem(_ sender: UIBarButtonItem) { let customView = CustomPopOverView(frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: 150.0, height: 200.0))) customView.showPopover(barButtonItem: sender) { print("CustomPopOverView.BarButtonItem.show.completion") } DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { customView.dismissPopover(animated: true, completion: { print("CustomPopOverView.BarButtonItem.dismiss.completion") }) } } @IBAction func onCustomPopOverView(_ sender: UIButton) { let customView = CustomPopOverView(frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: 150.0, height: 200.0))) customView.showPopover(sourceView: sender) { print("CustomPopOverView.show.completion") } } @IBAction func onCustomPopOverViewController(_ sender: UIButton) { let customViewController = CustomPopOverViewController() customViewController.showPopover(sourceView: sender) DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { customViewController.dismissPopover(animated: true, completion: { print("CustomPopOverViewController.dismiss.completion") }) } } @IBAction func onPopOverNavigationViewController(_ sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "CustomPushViewController") as! CustomPushViewController viewController.showPopoverWithNavigationController(sourceView: sender, shouldDismissOnTap: false) } } class DefaultPopOverViewController: UIViewController, UIPopoverPresentationControllerDelegate { init() { super.init(nibName: nil, bundle: nil) modalPresentationStyle = .popover popoverPresentationController?.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } } class CustomPopOverView: UIView, KUIPopOverUsable { var contentSize: CGSize { return CGSize(width: 300.0, height: 400.0) } var popOverBackgroundColor: UIColor? { return .black } var arrowDirection: UIPopoverArrowDirection { return .up } lazy var webView: WKWebView = { let webView: WKWebView = WKWebView(frame: self.frame) webView.load(URLRequest(url: URL(string: "http://github.com")!)) return webView }() override init(frame: CGRect) { super.init(frame: frame) addSubview(webView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() webView.frame = self.bounds } } class CustomPopOverViewController: UIViewController, KUIPopOverUsable { var contentSize: CGSize { return CGSize(width: 300.0, height: 400.0) } var popOverBackgroundColor: UIColor? { return .blue } lazy var webView: WKWebView = { let webView: WKWebView = WKWebView(frame: self.view.frame) webView.load(URLRequest(url: URL(string: "http://github.com")!)) return webView }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } } class CustomPushViewController: UIViewController, KUIPopOverUsable { private lazy var size: CGSize = { return CGSize(width: 250.0, height: 100.0 + CGFloat(arc4random_uniform(200))) }() var contentSize: CGSize { return size } override func viewDidLoad() { super.viewDidLoad() preferredContentSize = size navigationItem.title = size.debugDescription navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(onDoneButton(_:))) } @IBAction func onPushViewController(_ sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "CustomPushViewController") as! CustomPushViewController navigationController?.pushViewController(viewController, animated: true) } @objc private func onDoneButton(_ sender: UIButton) { dismissPopover(animated: true) } }
mit
2615ae0c689f12f2313581b23fe9de6f
32.405714
139
0.664215
5.018026
false
false
false
false
slepcat/mint
MINT/MintLeafPanelController.swift
1
4539
// // MintLeafPanelController.swift // mint // // Created by NemuNeko on 2015/09/23. // Copyright © 2015年 Taizo A. All rights reserved. // import Foundation import Cocoa // Provide Tool List [toolName:String], [toolImage:NSImage] for Popover // Using 'toolSet: String' in 'init()', load '.toolset' text file to determine contents of // NSPopover Interface class MintLeafPanelController:NSWindowController, NSTableViewDataSource, NSTableViewDelegate, NSWindowDelegate { @IBOutlet weak var leafList : NSTableView! @IBOutlet weak var toolList : NSPopUpButton! @IBOutlet weak var toggleMenu : NSMenuItem! var leafDic : [String : [String]] = [:] var selectedCate : String = "" var toolImages : [String : NSImage] = [:] @IBAction func changeCategory(_ sender: AnyObject?) { if let selected = toolList.selectedItem { selectedCate = selected.title leafList.reloadData() } } @IBAction func togglePanel(_ sender: AnyObject?) { if let panel = window { if panel.isVisible { close() toggleMenu.title = "Show Leaf Panel" } else { showWindow(sender) toggleMenu.title = "Hide Leaf Panel" } } } func windowShouldClose(sender: AnyObject) -> Bool { toggleMenu.title = "Show Leaf Panel" return true } func updateContents(_ leafDic: [String : [String]]) { self.leafDic = leafDic selectedCate = leafDic.keys.first! // set categories to popup button toolList.removeAllItems() toolList.addItems(withTitles: [String](leafDic.keys)) toolList.selectItem(at: 0) // set data source and delegate for NSTableView leafList.dataSource = self as NSTableViewDataSource leafList.delegate = self as NSTableViewDelegate // set drag operation mask leafList.setDraggingSourceOperationMask(NSDragOperation.generic, forLocal: true) // load icon images let appBundle = Bundle.main // load default icon let toolIconPath = appBundle.path(forResource: "Cube", ofType: "tiff") var defaultIcon : NSImage? if let path = toolIconPath { defaultIcon = NSImage(contentsOfFile: path) } // load unique icons for cate in leafDic { for name in cate.1 { // load icon let toolIconPath = appBundle.path(forResource: name, ofType: "tiff") if let path = toolIconPath { let iconImage = NSImage(contentsOfFile: path) if let image = iconImage { toolImages[name] = image } } else { // if there is no icon image for tool name, load default icon if let image = defaultIcon { toolImages[name] = image } } } } // fin load image } func numberOfRows(in: NSTableView) -> Int { if let leaves = leafDic[selectedCate] { return leaves.count } return 0 } // Provide data for NSTableView func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let result: AnyObject? = tableView.make(withIdentifier: "leafCell" , owner: self) if let toolView = result as? NSTableCellView { let name = leafDic[selectedCate]![row] toolView.textField?.stringValue = name toolView.imageView?.image = toolImages[name] } return result as? NSView } // Provide leaf type (=tool name) to NSPasteboard for dragging operation func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool { pboard.clearContents() pboard.declareTypes(["leaf", "type"], owner: self) if let i = rowIndexes.first { if pboard.setString(leafDic[selectedCate]![i], forType:"leaf" ) { if pboard.setString(selectedCate, forType: "type") { return true } } } return false } }
gpl-3.0
287bd48121d3f44f4d2f1eba3bf18f38
31.4
115
0.553351
5.256083
false
false
false
false
a2/Natalie
natalie.swift
1
44597
#!/usr/bin/env xcrun -sdk macosx swift // // Natalie - Storyboard Generator Script // // Generate swift file based on storyboard files // // Usage: // natalie.swift Main.storyboard > Storyboards.swift // natalie.swift path/toproject/with/storyboards > Storyboards.swift // // Licence: MIT // Author: Marcin Krzyżanowski http://blog.krzyzanowskim.com // //MARK: SWXMLHash // // SWXMLHash.swift // // Copyright (c) 2014 David Mohundro // // 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 let rootElementName = "SWXMLHash_Root_Element" /// Simple XML parser. public class SWXMLHash { /** Method to parse XML passed in as a string. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(xml: String) -> XMLIndexer { return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!) } /** Method to parse XML passed in as an NSData instance. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(data: NSData) -> XMLIndexer { var parser = XMLParser() return parser.parse(data) } class public func lazy(xml: String) -> XMLIndexer { return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!) } class public func lazy(data: NSData) -> XMLIndexer { var parser = LazyXMLParser() return parser.parse(data) } } struct Stack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } mutating func removeAll() { items.removeAll(keepCapacity: false) } func top() -> T { return items[items.count - 1] } } class LazyXMLParser : NSObject, NSXMLParserDelegate { override init() { super.init() } var root = XMLElement(name: rootElementName) var parentStack = Stack<XMLElement>() var elementStack = Stack<String>() var data: NSData? var ops: [IndexOp] = [] func parse(data: NSData) -> XMLIndexer { self.data = data return XMLIndexer(self) } func startParsing(ops: [IndexOp]) { // clear any prior runs of parse... expected that this won't be necessary, but you never know parentStack.removeAll() root = XMLElement(name: rootElementName) parentStack.push(root) self.ops = ops let parser = NSXMLParser(data: data!) parser.delegate = self parser.parse() } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { elementStack.push(elementName) if !onMatch() { return } let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict) parentStack.push(currentNode) } func parser(parser: NSXMLParser, foundCharacters string: String?) { if !onMatch() { return } let current = parentStack.top() if current.text == nil { current.text = "" } parentStack.top().text! += string! } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let match = onMatch() elementStack.pop() if match { parentStack.pop() } } func onMatch() -> Bool { // we typically want to compare against the elementStack to see if it matches ops, *but* // if we're on the first element, we'll instead compare the other direction. if elementStack.items.count > ops.count { return startsWith(elementStack.items, ops.map { $0.key }) } else { return startsWith(ops.map { $0.key }, elementStack.items) } } } /// The implementation of NSXMLParserDelegate and where the parsing actually happens. class XMLParser : NSObject, NSXMLParserDelegate { override init() { super.init() } var root = XMLElement(name: rootElementName) var parentStack = Stack<XMLElement>() func parse(data: NSData) -> XMLIndexer { // clear any prior runs of parse... expected that this won't be necessary, but you never know parentStack.removeAll() parentStack.push(root) let parser = NSXMLParser(data: data) parser.delegate = self parser.parse() return XMLIndexer(root) } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict) parentStack.push(currentNode) } func parser(parser: NSXMLParser, foundCharacters string: String?) { let current = parentStack.top() if current.text == nil { current.text = "" } parentStack.top().text! += string! } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { parentStack.pop() } } public class IndexOp { var index: Int let key: String init(_ key: String) { self.key = key self.index = -1 } func toString() -> String { if index >= 0 { return key + " " + index.description } return key } } public class IndexOps { var ops: [IndexOp] = [] let parser: LazyXMLParser init(parser: LazyXMLParser) { self.parser = parser } func findElements() -> XMLIndexer { parser.startParsing(ops) let indexer = XMLIndexer(parser.root) var childIndex = indexer for op in ops { childIndex = childIndex[op.key] if op.index >= 0 { childIndex = childIndex[op.index] } } ops.removeAll(keepCapacity: false) return childIndex } func stringify() -> String { var s = "" for op in ops { s += "[" + op.toString() + "]" } return s } } /// Returned from SWXMLHash, allows easy element lookup into XML data. public enum XMLIndexer : SequenceType { case Element(XMLElement) case List([XMLElement]) case Stream(IndexOps) case Error(NSError) /// The underlying XMLElement at the currently indexed level of XML. public var element: XMLElement? { get { switch self { case .Element(let elem): return elem case .Stream(let ops): let list = ops.findElements() return list.element default: return nil } } } /// All elements at the currently indexed level public var all: [XMLIndexer] { get { switch self { case .List(let list): var xmlList = [XMLIndexer]() for elem in list { xmlList.append(XMLIndexer(elem)) } return xmlList case .Element(let elem): return [XMLIndexer(elem)] case .Stream(let ops): let list = ops.findElements() return list.all default: return [] } } } /// All child elements from the currently indexed level public var children: [XMLIndexer] { get { var list = [XMLIndexer]() for elem in all.map({ $0.element! }) { for elem in elem.children { list.append(XMLIndexer(elem)) } } return list } } /** Allows for element lookup by matching attribute values. :param: attr should the name of the attribute to match on :param: _ should be the value of the attribute to match on :returns: instance of XMLIndexer */ public func withAttr(attr: String, _ value: String) -> XMLIndexer { let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"] let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"] switch self { case .Stream(let opStream): opStream.stringify() let match = opStream.findElements() return match.withAttr(attr, value) case .List(let list): if let elem = list.filter({$0.attributes[attr] == value}).first { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) case .Element(let elem): if let attr = elem.attributes[attr] { if attr == value { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) } } /** Initializes the XMLIndexer :param: _ should be an instance of XMLElement, but supports other values for error handling :returns: instance of XMLIndexer */ public init(_ rawObject: AnyObject) { switch rawObject { case let value as XMLElement: self = .Element(value) case let value as LazyXMLParser: self = .Stream(IndexOps(parser: value)) default: self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil)) } } /** Find an XML element at the current level by element name :param: key The element name to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(key: String) -> XMLIndexer { get { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"] switch self { case .Stream(let opStream): let op = IndexOp(key) opStream.ops.append(op) return .Stream(opStream) case .Element(let elem): let match = elem.children.filter({ $0.name == key }) if match.count > 0 { if match.count == 1 { return .Element(match[0]) } else { return .List(match) } } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } } /** Find an XML element by index within a list of XML Elements at the current level :param: index The 0-based index to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(index: Int) -> XMLIndexer { get { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"] switch self { case .Stream(let opStream): opStream.ops[opStream.ops.count - 1].index = index return .Stream(opStream) case .List(let list): if index <= list.count { return .Element(list[index]) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) case .Element(let elem): if index == 0 { return .Element(elem) } else { return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } } typealias GeneratorType = XMLIndexer public func generate() -> IndexingGenerator<[XMLIndexer]> { return all.generate() } } /// XMLIndexer extensions extension XMLIndexer: BooleanType { /// True if a valid XMLIndexer, false if an error type public var boolValue: Bool { get { switch self { case .Error: return false default: return true } } } } extension XMLIndexer: Printable { public var description: String { get { switch self { case .List(let list): return "\n".join(list.map { $0.description }) case .Element(let elem): if elem.name == rootElementName { return "\n".join(elem.children.map { $0.description }) } return elem.description default: return "" } } } } /// Models an XML element, including name, text and attributes public class XMLElement { /// The name of the element public let name: String /// The inner text of the element, if it exists public var text: String? /// The attributes of the element public var attributes = [String:String]() var children = [XMLElement]() var count: Int = 0 var index: Int /** Initialize an XMLElement instance :param: name The name of the element to be initialized :returns: a new instance of XMLElement */ init(name: String, index: Int = 0) { self.name = name self.index = index } /** Adds a new XMLElement underneath this instance of XMLElement :param: name The name of the new element to be added :param: withAttributes The attributes dictionary for the element being added :returns: The XMLElement that has now been added */ func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement { let element = XMLElement(name: name, index: count) count++ children.append(element) for (keyAny,valueAny) in attributes { let key = keyAny as! String let value = valueAny as! String element.attributes[key] = value } return element } } extension XMLElement: Printable { public var description:String { get { var attributesStringList = [String]() if !attributes.isEmpty { for (key, val) in attributes { attributesStringList.append("\(key)=\"\(val)\"") } } var attributesString = " ".join(attributesStringList) if (!attributesString.isEmpty) { attributesString = " " + attributesString } if children.count > 0 { var xmlReturn = [String]() xmlReturn.append("<\(name)\(attributesString)>") for child in children { xmlReturn.append(child.description) } xmlReturn.append("</\(name)>") return "\n".join(xmlReturn) } if text != nil { return "<\(name)\(attributesString)>\(text!)</\(name)>" } else { return "<\(name)\(attributesString)/>" } } } } //MARK: - Natalie //MARK: Objects enum OS: String, Printable { case iOS = "iOS" case OSX = "OSX" static let allValues = [iOS, OSX] enum Runtime: String { case iOSCocoaTouch = "iOS.CocoaTouch" case MacOSXCocoa = "MacOSX.Cocoa" init(os: OS) { switch os { case iOS: self = .iOSCocoaTouch case OSX: self = .MacOSXCocoa } } } enum Framework: String { case UIKit = "UIKit" case Cocoa = "Cocoa" init(os: OS) { switch os { case iOS: self = .UIKit case OSX: self = .Cocoa } } } init(targetRuntime: String) { switch (targetRuntime) { case Runtime.iOSCocoaTouch.rawValue: self = .iOS case Runtime.MacOSXCocoa.rawValue: self = .OSX case "iOS.CocoaTouch.iPad": self = iOS default: fatalError("Unsupported") } } var description: String { return self.rawValue } var framework: String { return Framework(os: self).rawValue } var targetRuntime: String { return Runtime(os: self).rawValue } var storyboardType: String { switch self { case iOS: return "UIStoryboard" case OSX: return "NSStoryboard" } } var storyboardSegueType: String { switch self { case iOS: return "UIStoryboardSegue" case OSX: return "NSStoryboardSegue" } } var storyboardTypeUnwrap: String { switch self { case iOS: return "" case OSX: return "!" } } var storyboardSegueUnwrap: String { switch self { case iOS: return "" case OSX: return "!" } } var storyboardControllerTypes: [String] { switch self { case iOS: return ["UIViewController"] case OSX: return ["NSViewController", "NSWindowController"] } } var storyboardControllerSignatureType: String { switch self { case iOS: return "ViewController" case OSX: return "Controller" // NSViewController or NSWindowController } } var viewType: String { switch self { case iOS: return "UIView" case OSX: return "NSView" } } var resuableViews: [String]? { switch self { case iOS: return ["UICollectionReusableView","UITableViewCell"] case OSX: return nil } } var storyboardControllerReturnType: String { switch self { case iOS: return "UIViewController" case OSX: return "AnyObject" // NSViewController or NSWindowController } } var storyboardControllerInitialReturnTypeCast: String { switch self { case iOS: return "as? \(self.storyboardControllerReturnType)" case OSX: return "" } } var storyboardControllerReturnTypeCast: String { switch self { case iOS: return " as! \(self.storyboardControllerReturnType)" case OSX: return "!" } } func storyboardControllerInitialReturnTypeCast(initialClass: String) -> String { switch self { case iOS: return "as! \(initialClass)" case OSX: return "" } } func controllerTypeForElementName(name: String) -> String? { switch self { case iOS: switch name { case "navigationController": return "UINavigationController" case "tableViewController": return "UITableViewController" case "tabBarController": return "UITabBarController" case "splitViewController": return "UISplitViewController" case "pageViewController": return "UIPageViewController" default: return nil } case OSX: switch name { case "pagecontroller": return "NSPageController" case "tabViewController": return "NSTabViewController" case "splitViewController": return "NSSplitViewController" default: return nil } } } } class XMLObject { var xml: XMLIndexer lazy var name: String? = self.xml.element?.name init(xml: XMLIndexer) { self.xml = xml } func searchAll(attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? { return searchAll(self.xml, attributeKey: attributeKey, attributeValue: attributeValue) } func searchAll(root: XMLIndexer, attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? { var result = Array<XMLIndexer>() for child in root.children { for childAtLevel in child.all { if let attributeValue = attributeValue { if let element = childAtLevel.element where element.attributes[attributeKey] == attributeValue { result += [childAtLevel] } } else if let element = childAtLevel.element where element.attributes[attributeKey] != nil { result += [childAtLevel] } if let found = searchAll(childAtLevel, attributeKey: attributeKey, attributeValue: attributeValue) { result += found } } } return result.count > 0 ? result : nil } func searchNamed(name: String) -> [XMLIndexer]? { return self.searchNamed(self.xml, name: name) } func searchNamed(root: XMLIndexer, name: String) -> [XMLIndexer]? { var result = Array<XMLIndexer>() for child in root.children { for childAtLevel in child.all { if let elementName = childAtLevel.element?.name where elementName == name { result += [child] } if let found = searchNamed(childAtLevel, name: name) { result += found } } } return result.count > 0 ? result : nil } func searchById(id: String) -> XMLIndexer? { return searchAll("id", attributeValue: id)?.first } } class Scene: XMLObject { lazy var viewController: ViewController? = { if let vcs = self.searchAll("sceneMemberID", attributeValue: "viewController"), vc = vcs.first { return ViewController(xml: vc) } return nil }() lazy var segues: [Segue]? = { return self.searchNamed("segue")?.map { Segue(xml: $0) } }() } class ViewController: XMLObject { lazy var customClass: String? = self.xml.element?.attributes["customClass"] lazy var customModuleProvider: String? = self.xml.element?.attributes["customModuleProvider"] lazy var storyboardIdentifier: String? = self.xml.element?.attributes["storyboardIdentifier"] lazy var customModule: String? = self.xml.element?.attributes["customModule"] lazy var reusables: [Reusable]? = { if let reusables = self.searchAll(self.xml, attributeKey: "reuseIdentifier"){ return reusables.map { Reusable(xml: $0) } } return nil }() private func showCustomImport() -> Bool { return self.customModule != nil && self.customModuleProvider == nil } } class Segue: XMLObject { lazy var identifier: String? = self.xml.element?.attributes["identifier"] lazy var kind: String? = self.xml.element?.attributes["kind"] lazy var destination: String? = self.xml.element?.attributes["destination"] } class Reusable: XMLObject { lazy var reuseIdentifier: String? = self.xml.element?.attributes["reuseIdentifier"] lazy var customClass: String? = self.xml.element?.attributes["customClass"] lazy var kind: String? = self.xml.element?.name } class Storyboard: XMLObject { lazy var os:OS = self.initOS() ?? OS.iOS private func initOS() -> OS? { if let targetRuntime = self.xml["document"].element?.attributes["targetRuntime"] { return OS(targetRuntime: targetRuntime) } return nil } lazy var initialViewControllerClass: String? = self.initInitialViewControllerClass() private func initInitialViewControllerClass() -> String? { if let initialViewControllerId = xml["document"].element?.attributes["initialViewController"], xmlVC = searchById(initialViewControllerId) { let vc = ViewController(xml: xmlVC) if let customClassName = vc.customClass { return customClassName } if let name = vc.name, controllerType = os.controllerTypeForElementName(name) { return controllerType } } return nil } lazy var version: String? = self.xml["document"].element?.attributes["version"] lazy var scenes: [Scene] = { if let scenes = self.searchAll(self.xml, attributeKey: "sceneID"){ return scenes.map { Scene(xml: $0) } } return [] }() func processStoryboard(storyboardName: String, os: OS) { println() println(" struct \(storyboardName) {") println() println(" static let identifier = \"\(storyboardName)\"") println() println(" static var storyboard:\(os.storyboardType) {") println(" return \(os.storyboardType)(name: self.identifier, bundle: nil)\(os.storyboardTypeUnwrap)") println(" }") if let initialViewControllerClass = self.initialViewControllerClass { println() println(" static func instantiateInitial\(os.storyboardControllerSignatureType)() -> \(initialViewControllerClass)! {") println(" return self.storyboard.instantiateInitial\(os.storyboardControllerSignatureType)() \(os.storyboardControllerInitialReturnTypeCast(initialViewControllerClass))") println(" }") } println() println(" static func instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier: String) -> \(os.storyboardControllerReturnType) {") println(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier)\(os.storyboardControllerReturnTypeCast)") println(" }") for scene in self.scenes { if let viewController = scene.viewController, customClass = viewController.customClass, storyboardIdentifier = viewController.storyboardIdentifier { println() println(" static func instantiate\(storyboardIdentifier)() -> \(customClass)! {") println(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(\"\(storyboardIdentifier)\") as! \(customClass)\n") println(" }") } } println(" }") } func processViewControllers() { for scene in self.scenes { if let viewController = scene.viewController { if let customClass = viewController.customClass { println() println("//MARK: - \(customClass)") if viewController.showCustomImport() { println("import \(viewController.customModule)") println() } if let segues = scene.segues?.filter({ return $0.identifier != nil }) where segues.count > 0 { println("extension \(os.storyboardSegueType) {") println(" func selection() -> \(customClass).Segue? {") println(" if let identifier = self.identifier {") println(" return \(customClass).Segue(rawValue: identifier)") println(" }") println(" return nil") println(" }") println("}") println() } if let segues = scene.segues?.filter({ return $0.identifier != nil }) where segues.count > 0 { println("extension \(customClass) { ") println() println(" enum Segue: String, Printable, SegueProtocol {") for segue in segues { if let identifier = segue.identifier { println(" case \(identifier) = \"\(identifier)\"") } } println() println(" var kind: SegueKind? {") println(" switch (self) {") for segue in segues { if let identifier = segue.identifier, kind = segue.kind { println(" case \(identifier):") println(" return SegueKind(rawValue: \"\(kind)\")") } } println(" default:") println(" preconditionFailure(\"Invalid value\")") println(" break") println(" }") println(" }") println() println(" var destination: \(self.os.storyboardControllerReturnType).Type? {") println(" switch (self) {") for segue in segues { if let identifier = segue.identifier, destination = segue.destination, destinationCustomClass = searchById(destination)?.element?.attributes["customClass"] { println(" case \(identifier):") println(" return \(destinationCustomClass).self") } } println(" default:") println(" assertionFailure(\"Unknown destination\")") println(" return nil") println(" }") println(" }") println() println(" var identifier: String? { return self.description } ") println(" var description: String { return self.rawValue }") println(" }") println() println("}") } if let reusables = viewController.reusables?.filter({ return $0.reuseIdentifier != nil }) where reusables.count > 0 { println("extension \(customClass) { ") println() println(" enum Reusable: String, Printable, ReusableProtocol {") for reusable in reusables { if let identifier = reusable.reuseIdentifier { println(" case \(identifier) = \"\(identifier)\"") } } println() println(" var kind: ReusableKind? {") println(" switch (self) {") for reusable in reusables { if let identifier = reusable.reuseIdentifier, kind = reusable.kind { println(" case \(identifier):") println(" return ReusableKind(rawValue: \"\(kind)\")") } } println(" default:") println(" preconditionFailure(\"Invalid value\")") println(" break") println(" }") println(" }") println() println(" var viewType: \(self.os.viewType).Type? {") println(" switch (self) {") for reusable in reusables { if let identifier = reusable.reuseIdentifier, customClass = reusable.customClass { println(" case \(identifier):") println(" return \(customClass).self") } } println(" default:") println(" return nil") println(" }") println(" }") println() println(" var identifier: String? { return self.description } ") println(" var description: String { return self.rawValue }") println(" }") println() println("}\n") } } } } } } class StoryboardFile { let filePath: String init(filePath: String){ self.filePath = filePath } lazy var storyboardName: String = self.filePath.lastPathComponent.stringByDeletingPathExtension lazy var data: NSData? = NSData(contentsOfFile: self.filePath) lazy var xml: XMLIndexer? = { if let d = self.data { return SWXMLHash.parse(d) } return nil }() lazy var storyboard: Storyboard? = { if let xml = self.xml { return Storyboard(xml:xml) } return nil }() } //MARK: Functions func findStoryboards(rootPath: String, suffix: String) -> [String]? { var result = Array<String>() let fm = NSFileManager.defaultManager() var error:NSError? if let paths = fm.subpathsAtPath(rootPath) as? [String] { let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)}) // result = storyboardPaths for p in storyboardPaths { result.append(rootPath.stringByAppendingPathComponent(p)) } } return result.count > 0 ? result : nil } func processStoryboards(storyboards: [StoryboardFile], os: OS) { println("//") println("// Autogenerated by Natalie - Storyboard Generator Script.") println("// http://blog.krzyzanowskim.com") println("//") println() println("import \(os.framework)") println() println("//MARK: - Storyboards") println("struct Storyboards {") for file in storyboards { file.storyboard?.processStoryboard(file.storyboardName, os: os) } println("}") println() println("//MARK: - ReusableKind") println("enum ReusableKind: String, Printable {") println(" case TableViewCell = \"tableViewCell\"") println(" case CollectionViewCell = \"collectionViewCell\"") println() println(" var description: String { return self.rawValue }") println("}") println() println("//MARK: - SegueKind") println("enum SegueKind: String, Printable { ") println(" case Relationship = \"relationship\" ") println(" case Show = \"show\" ") println(" case Presentation = \"presentation\" ") println(" case Embed = \"embed\" ") println(" case Unwind = \"unwind\" ") println() println(" var description: String { return self.rawValue } ") println("}") println() println("//MARK: - SegueProtocol") println("public protocol IdentifiableProtocol: Equatable {") println(" var identifier: String? { get }") println("}") println() println("public protocol SegueProtocol: IdentifiableProtocol {") println("}") println() println("public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {") println(" return lhs.identifier == rhs.identifier") println("}") println() println("public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {") println(" return lhs.identifier == rhs.identifier") println("}") println() println("//MARK: - ReusableProtocol") println("public protocol ReusableProtocol: IdentifiableProtocol {") println(" var viewType: \(os.viewType).Type? {get}") println("}") println() println("public func ==<T: ReusableProtocol, U: ReusableProtocol>(lhs: T, rhs: U) -> Bool {") println(" return lhs.identifier == rhs.identifier") println("}") println() println("//MARK: - Protocol Implementation") println("extension \(os.storyboardSegueType): SegueProtocol {") println("}") println() if let reusableViews = os.resuableViews { for reusableView in reusableViews { println("extension \(reusableView): ReusableProtocol {") println(" public var viewType: UIView.Type? { return self.dynamicType}") println(" public var identifier: String? { return self.reuseIdentifier}") println("}") println() } } for controllerType in os.storyboardControllerTypes { println("//MARK: - \(controllerType) extension") println("extension \(controllerType) {") println(" func performSegue<T: SegueProtocol>(segue: T, sender: AnyObject?) {") println(" performSegueWithIdentifier(segue.identifier\(os.storyboardSegueUnwrap), sender: sender)") println(" }") println("}") println() } if os == OS.iOS { println("//MARK: - UICollectionViewController") println() println("extension UICollectionViewController {") println() println(" func dequeueReusableCell<T: ReusableProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> AnyObject {") println(" return self.collectionView!.dequeueReusableCellWithReuseIdentifier(reusable.identifier!, forIndexPath: forIndexPath)") println(" }") println() println(" func registerReusable<T: ReusableProtocol>(reusable: T) {") println(" if let type = reusable.viewType, identifier = reusable.identifier {") println(" self.collectionView?.registerClass(type, forCellWithReuseIdentifier: identifier)") println(" }") println(" }") println() println(" func dequeueReusableSupplementaryViewOfKind<T: ReusableProtocol>(elementKind: String, withReusable reusable: T, forIndexPath: NSIndexPath!) -> AnyObject {") println(" return self.collectionView!.dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: reusable.identifier!, forIndexPath: forIndexPath)") println(" }") println() println(" func registerReusable<T: ReusableProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {") println(" if let type = reusable.viewType, identifier = reusable.identifier {") println(" self.collectionView?.registerClass(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)") println(" }") println(" }") println("}") println("//MARK: - UITableViewController") println() println("extension UITableViewController {") println() println(" func dequeueReusableCell<T: ReusableProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> AnyObject {") println(" return self.tableView!.dequeueReusableCellWithIdentifier(reusable.identifier!, forIndexPath: forIndexPath)") println(" }") println() println(" func registerReusableCell<T: ReusableProtocol>(reusable: T) {") println(" if let type = reusable.viewType, identifier = reusable.identifier {") println(" self.tableView?.registerClass(type, forCellReuseIdentifier: identifier)") println(" }") println(" }") println() println(" func dequeueReusableHeaderFooter<T: ReusableProtocol>(reusable: T) -> AnyObject? {") println(" if let identifier = reusable.identifier {") println(" return self.tableView?.dequeueReusableHeaderFooterViewWithIdentifier(identifier)") println(" }") println(" return nil") println(" }") println() println(" func registerReusableHeaderFooter<T: ReusableProtocol>(reusable: T) {") println(" if let type = reusable.viewType, identifier = reusable.identifier {") println(" self.tableView?.registerClass(type, forHeaderFooterViewReuseIdentifier: identifier)") println(" }") println(" }") println("}") } for file in storyboards { file.storyboard?.processViewControllers() } } //MARK: MAIN() if Process.arguments.count == 1 { println("Invalid usage. Missing path to storyboard.") exit(0) } let argument = Process.arguments[1] var storyboards:[String] = [] let storyboardSuffix = ".storyboard" if argument.hasSuffix(storyboardSuffix) { storyboards = [argument] } else if let s = findStoryboards(argument, storyboardSuffix) { storyboards = s } let storyboardFiles: [StoryboardFile] = storyboards.map { StoryboardFile(filePath: $0) } for os in OS.allValues { var storyboardsForOS = storyboardFiles.filter { $0.storyboard?.os == os } if !storyboardsForOS.isEmpty { if storyboardsForOS.count != storyboardFiles.count { println("#if os(\(os.rawValue))") } processStoryboards(storyboardsForOS, os) if storyboardsForOS.count != storyboardFiles.count { println("#endif") } } }
mit
2964f02b17770ea8e79d29f971dbebc8
33.570543
193
0.539129
5.433898
false
false
false
false
BrantSteven/SinaProject
BSweibo/BSweibo/class/newFeature/WelcomeVC.swift
1
2595
// // WelcomeVC.swift // BSweibo // // Created by 上海旅徒电子商务有限公司 on 16/9/27. // Copyright © 2016年 白霜. All rights reserved. // import UIKit class WelcomeVC: UIViewController { /// 图像底部约束 private var iconBottomCons: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() //1.初始化UI createUI() //2.设置用户信息 if let iconUrlStr = UserAccount.readAccount()?.avatar_large { bsLog(message: iconUrlStr) iconView.sd_setImage(with: NSURL(string: iconUrlStr) as URL!) } } override func viewDidAppear(_ animated: Bool) {//头像从底部滑上去 super.viewDidAppear(animated) UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.iconView.frame = CGRect(x: BSWidth/2-50, y: 100, width: 100, height: 100) self.message.frame = CGRect(x: self.iconView.left, y: self.iconView.bottom+10, width: 100, height: 39) }) { (_) -> Void in self.message.alpha = 1.0//完成头像的滑动 label展示 //去主页 注意点: 企业开发中如果要切换根控制器 最好都在appdelegate中切换 NotificationCenter.default.post(name: NSNotification.Name(rawValue: ChangeRootViewControllerNotifacationtion), object: true) } } //初始化UI func createUI(){ view.addSubview(imageView) view.addSubview(iconView) view.addSubview(message) imageView.frame = view.bounds iconView.frame = CGRect(x: BSWidth/2-50, y: BSHeight - 100, width: 100, height: 100) // message.frame = CGRect(x: iconView.left, y: iconView.bottom+10, width: 100, height: 39) } //MARK:懒加载控件 //背景图片 lazy var imageView:UIImageView = { let imageV = UIImageView.init(image: UIImage.init(named: "ad_background")) return imageV }() ///头像 lazy var iconView:UIImageView = { let iconV = UIImageView(image: UIImage(named: "avatar_default_big")) iconV.layer.masksToBounds = true iconV.layer.cornerRadius = 50 return iconV }() ///消息文字 lazy var message:UILabel = { let messageLabel = UILabel.init() messageLabel.text = "欢迎归来" messageLabel.textAlignment = NSTextAlignment.center messageLabel.alpha = 0//隐藏label return messageLabel }() }
mit
ab1eed7dc6018f0822f7aefdd778c3e8
36.40625
180
0.630744
3.886364
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/erect-the-fence.swift
2
1896
/** * https://leetcode.com/problems/erect-the-fence/ * * */ // Date: Mon Sep 6 23:32:44 PDT 2021 /// - Tag: Geometry class Solution { /// Reference: https://leetcode.com/problems/erect-the-fence/solution/ /// Jarvis Algorithm. /// - Complexity: /// - Time: O(n^2), n = trees.count /// - Space: O(n), n = trees.count func outerTrees(_ trees: [[Int]]) -> [[Int]] { if trees.count < 4 { return Array(Set(trees)) } var hulls = Set<Int>() var p = 0 for index in 0 ..< trees.count { if trees[index][0] < trees[p][0] { p = index } } let leftMost = p // print("LeftMost", leftMost) repeat { var q = (p + 1) % trees.count for index in 0 ..< trees.count { if orientation(trees[p], trees[index], trees[q]) < 0 { q = index } } for index in 0 ..< trees.count { if index != p, index != q, orientation(trees[p], trees[index], trees[q]) == 0, inBetween(trees[p], trees[index], trees[q]) { hulls.insert(index) } } hulls.insert(q) // print("q", q) p = q } while leftMost != p // print("So far so good.") return Array(hulls).map { trees[$0] } } private func orientation(_ p: [Int], _ q: [Int], _ r: [Int]) -> Int { let a = (q[1] - p[1]) * (r[0] - q[0]) let b = (q[0] - p[0]) * (r[1] - q[1]) return a - b ; } private func inBetween(_ p: [Int], _ i: [Int], _ q: [Int]) -> Bool { let a = i[0] >= p[0] && i[0] <= q[0] || i[0] <= p[0] && i[0] >= q[0]; let b = i[1] >= p[1] && i[1] <= q[1] || i[1] <= p[1] && i[1] >= q[1]; return a && b; } }
mit
c0d6a1376016e19275d3eb35af2ddf75
31.152542
140
0.414557
3.229983
false
false
false
false
rundfunk47/Juice
Example/Tests/JSONDictionaryTransformTests.swift
1
15878
// // JSONDictionaryTransformTests.swift // JuiceTests // // Created by Narek M on 19/06/16. // Copyright © 2016 Narek. All rights reserved. // import XCTest @testable import Juice fileprivate struct MyError: Error, CustomNSError { var localizedDescription: String { return "MyError" } /// The user-info dictionary. public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: localizedDescription] } /// The error code within the given domain. public var errorCode: Int { return 1 } /// The domain of the error. public static var errorDomain = "MyErrorDomain" } class JSONDictionaryDecodingTypeTransformTests: XCTestCase { func testTransform() { do { let webpage = JSONDictionary(["url": "http://www.apple.com"]) let url : URL = try webpage.decode("url", transform: { (input: String) -> URL in return URL(string: input)! }) XCTAssertEqual(url.absoluteString, "http://www.apple.com") } catch { XCTFail(error.localizedDescription) } } func testFailingTransform() { do { let webpage = JSONDictionary(["url": 1984]) _ = try webpage.decode("url", transform: { (input: String) -> URL in XCTFail("Shouldn't be called...") return URL(string: input)! }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["url"]) let keypathError = "Expected \"String\" got \"Int\" with value 1984." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"url\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? MismatchError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testOptionalTransform() { do { let webpage = JSONDictionary(["apple": "http://www.apple.com"]) let url : URL? = try webpage.decode(["url"], transform: { (input: String?) -> URL? in if let url = input { XCTFail("Shouldn't call this") return URL(string: url) } else { return nil } }) XCTAssertNil(url) } catch { XCTFail(error.localizedDescription) } } func testOptionalInputTransform() { do { let person = JSONDictionary(["name": "Jane Doe"]) let id : String = try person.decode("id", transform: { (input: String?) -> String in if let id = input { return id } else { return "Unknown ID" } }) XCTAssertEqual(id, "Unknown ID") } catch { XCTFail(error.localizedDescription) } } func testNoKeyTransform() { do { let webpage = JSONDictionary(["apple": "http://www.apple.com"]) _ = try webpage.decode("url", transform: { (input: String) -> URL in XCTFail("Shouldn't be called...") return URL(string: input)! }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["url"]) let keypathError = "Key not found." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"url\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? KeyNotFoundError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testErrorPropagationTransform() { do { let webpage = JSONDictionary(["url": "http://www.apple.com"]) _ = try webpage.decode("url", transform: { (input: String) -> URL in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["url"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"url\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } func testErrorPropagationOptionalTransform() { do { let webpage = JSONDictionary(["url": "http://www.apple.com"]) _ = try webpage.decode("url", transform: { (input: String?) -> URL in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["url"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"url\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } } class JSONDictionaryDecodingDictionaryTypeTransformTests: XCTestCase { func testTransform() { do { let company = JSONDictionary(["company": JSONDictionary(["url": "http://www.apple.com"])]) let url : URL = try company.decode("company", transform: {(input: Dictionary<String, String>) -> URL in return URL(string: input["url"]!)! }) XCTAssertEqual(url.absoluteString, "http://www.apple.com") } catch { XCTFail(error.localizedDescription) } } func testFailingTransform() { do { let company = JSONDictionary(["company": 1984]) _ = try company.decode("company", transform: {(input: Dictionary<String, String>) -> URL in XCTFail("Shouldn't be called...") return URL(string: input["url"]!)! }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["company"]) let keypathError = "Expected \"JSONDictionary\" got \"Int\" with value 1984." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"company\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? MismatchError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testOptionalTransform() { do { let company = JSONDictionary(["company": JSONDictionary(["url": "http://www.apple.com"])]) let url : URL? = try company.decode(["characters"], transform: { (input: Dictionary<String, String>?) -> URL? in if input != nil { XCTFail("Shouldn't call this") return URL(string: input!["company"]!)! } else { return nil } }) XCTAssertNil(url) } catch { XCTFail(error.localizedDescription) } } func testOptionalInputTransform() { do { let person = JSONDictionary(["name": "Jane Doe"]) let owns : String = try person.decode(["owns"], transform: { (input: Dictionary<String, String>?) -> String in if let _ = input { return "Owns stuff" } else { return "Owns nothing" } }) XCTAssertEqual(owns, "Owns nothing") } catch { XCTFail(error.localizedDescription) } } func testNoKeyTransform() { do { let webpage = JSONDictionary(["apple": "http://www.apple.com"]) _ = try webpage.decode("site", transform: { (input: Dictionary<String, String>) -> URL in XCTFail("Shouldn't be called...") return URL(string: input["address"]!)! }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["site"]) let keypathError = "Key not found." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"site\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? KeyNotFoundError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testErrorPropagationTransform() { do { let company = JSONDictionary(["company": JSONDictionary(["url": "http://www.apple.com"])]) _ = try company.decode("company", transform: { (input: Dictionary<String, String>) -> URL in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["company"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"company\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } func testErrorPropagationOptionalTransform() { do { let company = JSONDictionary(["company": JSONDictionary(["url": "http://www.apple.com"])]) _ = try company.decode("company", transform: { (input: Dictionary<String, String>?) -> URL in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["company"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"company\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } } class JSONDictionaryDecodingArrayTypeTransformTests: XCTestCase { func testTransform() { do { let company = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) let added : Int = try company.decode("numbers", transform: { (input: Array<Int>) -> Int in return input.reduce(0, {$0 + $1}) }) XCTAssertEqual(added, 15) } catch { XCTFail(error.localizedDescription) } } func testFailingTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) _ = try numbers.decode("numbers", transform: { (input: Array<String>) -> String in XCTFail("Shouldn't be called...") return input.reduce("", {$0 + $1}) }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["numbers"]) let keypathError = "Expected \"String\" got \"Int\" with value 1." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"numbers\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? MismatchError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testOptionalTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) let url : String? = try numbers.decode(["letters"], transform: { (input: Array<String>?) -> String? in if input != nil { XCTFail("Shouldn't call this") return input!.reduce("", {$0! + $1}) } else { return nil } }) XCTAssertNil(url) } catch { XCTFail(error.localizedDescription) } } func testOptionalInputTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) let owns : String = try numbers.decode("letters", transform: { (input: Array<String>?) -> String in if let _ = input { return "Letters" } else { return "No letters" } }) XCTAssertEqual(owns, "No letters") } catch { XCTFail(error.localizedDescription) } } func testNoKeyTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) _ = try numbers.decode("added", transform: { (input: Int) -> String in XCTFail("Shouldn't be called...") return String(input) }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["added"]) let keypathError = "Key not found." XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"added\"]: " + keypathError) guard let mismatchError = decodingError.underlyingError as? KeyNotFoundError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(mismatchError.localizedDescription, keypathError) } } func testErrorPropagationTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) _ = try numbers.decode("numbers", transform: { (input: Array<Int>) -> Int in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["numbers"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"numbers\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } func testErrorPropagationOptionalTransform() { do { let numbers = JSONDictionary(["numbers": JSONArray([1, 2, 3, 4, 5])]) _ = try numbers.decode("numbers", transform: { (input: Array<Int>?) -> Int in throw MyError() // fake error }) XCTFail("Shouldn't get here...") } catch { guard let decodingError = error as? DictionaryDecodingError else {XCTFail("Wrong kind of error..."); return} XCTAssertEqual(decodingError.keyPath, ["numbers"]) XCTAssertEqual(decodingError.localizedDescription, "Error at key path [\"numbers\"]: MyError") XCTAssertTrue(decodingError.underlyingError is MyError) } } }
mit
cdc2f2f63fc06795bc0c363163a68698
42.144022
137
0.563771
5.37111
false
true
false
false
triestpa/BlueSky
BlueSky/WeatherViewController.swift
1
6310
// // DetailViewController.swift // BlueSky // // Created by Patrick on 11/18/14. // Copyright (c) 2014 Patrick Triest. All rights reserved. // import UIKit class WeatherViewController: UIViewController { @IBOutlet weak var currentTempLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var minTempLabel: UILabel! @IBOutlet weak var maxTempLabel: UILabel! @IBOutlet weak var weatherConditionLabel: UILabel! var urlSession: NSURLSession! let apiID = "6b120251e9c87a7c31a21ee14f0a8eef" var weatherReport: NSDictionary! var weatherLocation: String? { didSet { if isViewLoaded() { queryOpenWeather(Location: weatherLocation!) } } } func setLocation (location: NSString) { self.weatherLocation = location } override func viewDidLoad() { super.viewDidLoad() if (weatherLocation != nil) { navigationItem.title = weatherLocation? navigationController queryOpenWeather(Location: weatherLocation!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func queryOpenWeather(Location location: String) { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() urlSession = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) //Remove spaces to avoid malformed URLs let formatedLocation = location.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) let urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + formatedLocation + "&APPID=" + apiID + "&units=metric" println(urlString) if let url = NSURL(string: urlString as NSString) { makeNetworkRequest(url) } else { //Catch NSURL formation error showErrorAlert("Invalid URL. You Must Be Trying to Find A Really Weird Place") } } func makeNetworkRequest(url: NSURL) { let dataTask = urlSession.dataTaskWithURL(url, completionHandler: {data, response, error in let response = NSString(data: data, encoding: NSUTF8StringEncoding) // Detect http request error if error != nil { self.showErrorAlert("Web Request Failed, Make Sure The Internet on Your Device is Working") } else { println(response) self.parseResult(data) } //Hide progress indicator UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) //Show progress indicator UIApplication.sharedApplication().networkActivityIndicatorVisible = true dataTask.resume() } func parseResult(data: NSData) { // Parse JSON if let weatherReport: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as?NSDictionary { self.weatherReport = weatherReport as NSDictionary //Check for an error message within the response if let errorMessage: NSString = weatherReport["message"] as? NSString { let errorCode: NSString = weatherReport["cod"] as NSString println(errorMessage + ", Code: " + errorCode) self.showErrorAlert(errorMessage) } else { let weatherDataArray = weatherReport["weather"] as NSArray let weatherDataDict = weatherDataArray[0] as NSDictionary let temperatureDict = weatherReport["main"] as NSDictionary let currentTemp = temperatureDict["temp"] as NSNumber self.currentTempLabel.text = currentTemp.stringValue + " °C" self.iconImageView.image = UIImage(named: weatherDataDict["icon"] as NSString) self.minTempLabel.text = (temperatureDict["temp_min"] as NSNumber).stringValue + " °C" self.maxTempLabel.text = (temperatureDict["temp_max"] as NSNumber).stringValue + " °C" self.weatherConditionLabel.text = weatherDataDict["description"] as NSString setBackgroundPicture(weatherDataDict["id"] as Int) } } else { //Catch parsing error print("JSON Parse Error") self.showErrorAlert("JSON Parse Error") } } func showErrorAlert(errorMessage: NSString) { var alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert, animated: true, completion: nil) var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { action in //TODO why doesnt this work? self.navigationController?.popToRootViewControllerAnimated(true) //self.navigationController?.dismissViewControllerAnimated(false, completion: nil) return }) alert.addAction(okAction) } func setBackgroundPicture(code: Int) { println(code) var backgroudImage: UIImage if (code < 600) { backgroudImage = UIImage(named: "rain.png")! } else if (code < 700) { backgroudImage = UIImage(named: "snow.png")! } else if (code == 800) { backgroudImage = UIImage(named: "bluesky.png")! } else if (code < 800) { backgroudImage = UIImage(named: "mist.png")! } else if (code < 900) { backgroudImage = UIImage(named: "cloudy.png")! } else if (code < 950){ backgroudImage = UIImage(named: "rain.png")! } else { backgroudImage = UIImage(named: "bluesky.png")! } self.view.backgroundColor = UIColor(patternImage: backgroudImage) } }
gpl-2.0
99e4d1910676bec34d4dd86feb33ee33
36.541667
156
0.603932
5.451167
false
false
false
false
christijohn/Swift-Demos
Tip_Calculator/Tip_Calculator/TipDetailViewController.swift
1
2347
// // TipDetailViewController.swift // Tip_Calculator // // Created by Christi John on 22/01/16. // Copyright © 2016 Christi John. All rights reserved. // import UIKit @objc protocol TableUpdates{ func cellTappedAtIndexPath(indexPath:NSIndexPath) optional func tableScrolled() } class TipDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var dataArray:Array <(tipAmount:Double,billAmount:Double)>? var tipArray:Array<Double>? weak var delegate:TableUpdates? override func viewDidLoad() { super.viewDidLoad() //self.navigationController?.navigationBarHidden = false tipArray = [0.10,0.15,0.20,0.25,0.30] // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ guard let count = dataArray?.count else{ return 0; } return count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let tableViewCell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") let item = dataArray?[indexPath.row] tableViewCell?.textLabel?.text = String(format: "Percentage :%.1f %%, Tip Amount : %.1f",tipArray![indexPath.row],item!.tipAmount) return tableViewCell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { delegate?.cellTappedAtIndexPath(indexPath) } func scrollViewDidScroll(scrollView: UIScrollView) { delegate?.tableScrolled?() } deinit{ delegate = nil } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
66dd0e455131eea65636ae1e6a511870
27.609756
138
0.664535
5.178808
false
false
false
false
larryhou/swift
TexasHoldem/TexasHoldem/HandV3TwoPair.swift
1
1460
// // HandV3TwoPair.swift // TexasHoldem // // Created by larryhou on 6/3/2016. // Copyright © 2016 larryhou. All rights reserved. // import Foundation // 两对 class HandV3TwoPair: PatternEvaluator { static func getOccurrences() -> UInt { var count: UInt = 0 count += // 2-2-1-1-1 combinate(13, select: 2) * combinate(4, select: 2) * combinate(11, select: 3) * pow(4, exponent: 3) count += // 2-2-2-1 combinate(13, select: 3) * combinate(4, select: 2) * (52 - 4 * 3) return count } static func evaluate(_ hand: PokerHand) { var cards = (hand.givenCards + hand.tableCards).sort() var dict: [Int: [PokerCard]] = [:] var group: [PokerCard] = [] for i in 0..<cards.count { let item = cards[i] if dict[item.value] == nil { dict[item.value] = [] } dict[item.value]?.append(item) if let count = dict[item.value]?.count where count == 2 { group.append(item) } } let list = group.sorted(isOrderedBefore: {$0 > $1}).map({$0.value}) var result: [PokerCard] = dict[list[0]]! + dict[list[1]]! for i in 0..<cards.count { if list.index(of: cards[i].value) < 0 && result.count < 5 { result.append(cards[i]) } } hand.matches = result } }
mit
948c2e16b050f23fcff03b51b02d4851
24.982143
75
0.504467
3.557457
false
false
false
false
mattrajca/swift-corelibs-foundation
Foundation/Dictionary.swift
4
3675
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation extension Dictionary : _ObjectTypeBridgeable { public typealias _ObjectType = NSDictionary public func _bridgeToObjectiveC() -> _ObjectType { let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: count) let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: count) var idx = 0 self.forEach { (keyItem, valueItem) in let key = _SwiftValue.store(keyItem) let value = _SwiftValue.store(valueItem) keyBuffer.advanced(by: idx).initialize(to: key) valueBuffer.advanced(by: idx).initialize(to: value) idx += 1 } let dict = NSDictionary(objects: valueBuffer, forKeys: keyBuffer, count: count) keyBuffer.deinitialize(count: count) valueBuffer.deinitialize(count: count) keyBuffer.deallocate() valueBuffer.deallocate() return dict } static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Dictionary?) { result = _unconditionallyBridgeFromObjectiveC(source) } @discardableResult static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Dictionary?) -> Bool { var dict = [Key: Value]() var failedConversion = false if type(of: source) == NSDictionary.self || type(of: source) == NSMutableDictionary.self { source.enumerateKeysAndObjects(options: []) { key, value, stop in guard let key = key as? Key, let value = value as? Value else { failedConversion = true stop.pointee = true return } dict[key] = value } } else if type(of: source) == _NSCFDictionary.self { let cf = source._cfObject let cnt = CFDictionaryGetCount(cf) let keys = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: cnt) let values = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: cnt) CFDictionaryGetKeysAndValues(cf, keys, values) for idx in 0..<cnt { let key = _SwiftValue.fetch(nonOptional: unsafeBitCast(keys.advanced(by: idx).pointee!, to: AnyObject.self)) let value = _SwiftValue.fetch(nonOptional: unsafeBitCast(values.advanced(by: idx).pointee!, to: AnyObject.self)) guard let k = key as? Key, let v = value as? Value else { failedConversion = true break } dict[k] = v } keys.deinitialize(count: cnt) values.deinitialize(count: cnt) keys.deallocate() values.deallocate() } if !failedConversion { result = dict return true } return false } static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Dictionary { if let object = source { var value: Dictionary<Key, Value>? _conditionallyBridgeFromObjectiveC(object, result: &value) return value! } else { return Dictionary<Key, Value>() } } }
apache-2.0
ca219a770b3168ab78cfe053e290076e
36.886598
128
0.598367
5.176056
false
false
false
false
lightsprint09/socket.io-client-swift
Source/SocketIO/Util/SocketTypes.swift
7
2763
// // SocketTypes.swift // Socket.IO-Client-Swift // // Created by Erik Little on 4/8/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// A marking protocol that says a type can be represented in a socket.io packet. /// /// Example: /// /// ```swift /// struct CustomData : SocketData { /// let name: String /// let age: Int /// /// func socketRepresentation() -> SocketData { /// return ["name": name, "age": age] /// } /// } /// /// socket.emit("myEvent", CustomData(name: "Erik", age: 24)) /// ``` public protocol SocketData { // MARK: Methods /// A representation of self that can sent over socket.io. func socketRepresentation() throws -> SocketData } public extension SocketData { /// Default implementation. Only works for native Swift types and a few Foundation types. func socketRepresentation() -> SocketData { return self } } extension Array : SocketData { } extension Bool : SocketData { } extension Dictionary : SocketData { } extension Double : SocketData { } extension Int : SocketData { } extension NSArray : SocketData { } extension Data : SocketData { } extension NSData : SocketData { } extension NSDictionary : SocketData { } extension NSString : SocketData { } extension NSNull : SocketData { } extension String : SocketData { } /// A typealias for an ack callback. public typealias AckCallback = ([Any]) -> () /// A typealias for a normal callback. public typealias NormalCallback = ([Any], SocketAckEmitter) -> () typealias JSON = [String: Any] typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data]) typealias ProbeWaitQueue = [Probe] enum Either<E, V> { case left(E) case right(V) }
apache-2.0
b733d049b298201e37e453e5a0ab0a62
32.289157
93
0.706117
4.205479
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallBeat.swift
9
3186
// // NVActivityIndicatorAnimationBallBeat.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationBallBeat: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - circleSize) / 2 let duration: CFTimeInterval = 0.7 let beginTime = CACurrentMediaTime() let beginTimes = [0.35, 0, 0.35] // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.75, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.5, 1] opacityAnimation.values = [1, 0.2, 1] opacityAnimation.duration = duration // Aniamtion let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } }
apache-2.0
2bfca08957744aac30875a3659d99218
39.846154
133
0.673886
4.924266
false
false
false
false
idikic/ios-viper
Presence-iOS/00_Application/AppDefines.swift
1
463
// // AppDefines.swift // Presence-iOS // // Created by Iki on 05/02/16. // Copyright © 2016 Infinum. All rights reserved. // // MARK: - View Controller Identifier - let LandingViewControllerIdentifier = "LandingViewController" let LoginViewControllerIdentifier = "LoginViewController" let TabbarControllerIdentifier = "TabbarController" let HomeViewControllerIdentifier = "HomeViewController" let SettingsViewControllerIdentifier = "SettingsViewController"
mit
c91f669da5e1cd8c26ab027808b4e37b
32.071429
63
0.796537
4.714286
false
false
false
false
maxvol/RxCloudKit
RxCloudKit/RecordChangeFetcher.swift
1
4183
// // RecordChangeFetcher.swift // RxCloudKit // // Created by Maxim Volgin on 11/08/2017. // Copyright (c) RxSwiftCommunity. All rights reserved. // import RxSwift import CloudKit @available(iOS 10, *) public enum RecordEvent { case changed(CKRecord) case deleted(CKRecord.ID) case token(CKRecordZone.ID, CKServerChangeToken) } @available(iOS 10, *) final class RecordChangeFetcher { typealias Observer = AnyObserver<RecordEvent> private let observer: Observer private let database: CKDatabase private let recordZoneIDs: [CKRecordZone.ID] private var optionsByRecordZoneID: [CKRecordZone.ID : CKFetchRecordZoneChangesOperation.ZoneOptions] init(observer: Observer, database: CKDatabase, recordZoneIDs: [CKRecordZone.ID], optionsByRecordZoneID: [CKRecordZone.ID : CKFetchRecordZoneChangesOperation.ZoneOptions]? = nil) { self.observer = observer self.database = database self.recordZoneIDs = recordZoneIDs self.optionsByRecordZoneID = optionsByRecordZoneID ?? [:] self.fetch() } // MARK:- callbacks private func recordChangedBlock(record: CKRecord) { self.observer.on(.next(.changed(record))) } private func recordWithIDWasDeletedBlock(recordID: CKRecord.ID, undocumented: String) { print("\(recordID)|\(undocumented)") // TEMP undocumented? self.observer.on(.next(.deleted(recordID))) } private func recordZoneChangeTokensUpdatedBlock(zoneID: CKRecordZone.ID, serverChangeToken: CKServerChangeToken?, clientChangeTokenData: Data?) { self.updateToken(zoneID: zoneID, serverChangeToken: serverChangeToken) if let token = serverChangeToken { self.observer.on(.next(.token(zoneID, token))) } // TODO clientChangeTokenData? } private func recordZoneFetchCompletionBlock(zoneID: CKRecordZone.ID, serverChangeToken: CKServerChangeToken?, clientChangeTokenData: Data?, moreComing: Bool, recordZoneError: Error?) { // TODO clientChangeTokenData ? if let error = recordZoneError { // observer.on(.error(error)) // special handling for CKErrorChangeTokenExpired (purge local cache, fetch with token=nil) return } self.updateToken(zoneID: zoneID, serverChangeToken: serverChangeToken) if let token = serverChangeToken { self.observer.on(.next(.token(zoneID, token))) } // if moreComing { // self.fetch() // TODO only for this zone? // return // } else { // if let index = self.recordZoneIDs.index(of: zoneID) { // self.recordZoneIDs.remove(at: index) // } // } } private func fetchRecordZoneChangesCompletionBlock(operationError: Error?) { if let error = operationError { observer.on(.error(error)) return } observer.on(.completed) } // MARK:- custom private func updateToken(zoneID: CKRecordZone.ID, serverChangeToken: CKServerChangeToken?) { // token, limit, fields (nil = all, [] = no user fields) let options = self.optionsByRecordZoneID[zoneID] ?? CKFetchRecordZoneChangesOperation.ZoneOptions() options.previousServerChangeToken = serverChangeToken self.optionsByRecordZoneID[zoneID] = options } private func fetch() { let operation = CKFetchRecordZoneChangesOperation(recordZoneIDs: self.recordZoneIDs, optionsByRecordZoneID: self.optionsByRecordZoneID) operation.fetchAllChanges = true operation.qualityOfService = .userInitiated operation.recordChangedBlock = self.recordChangedBlock operation.recordWithIDWasDeletedBlock = self.recordWithIDWasDeletedBlock operation.recordZoneChangeTokensUpdatedBlock = self.recordZoneChangeTokensUpdatedBlock operation.recordZoneFetchCompletionBlock = self.recordZoneFetchCompletionBlock operation.fetchRecordZoneChangesCompletionBlock = self.fetchRecordZoneChangesCompletionBlock self.database.add(operation) } }
mit
ecedb4a24fabcb470ce1239f790b2ae3
37.027273
188
0.682764
5.335459
false
false
false
false
davidbutz/ChristmasFamDuels
iOS/Boat Aware/DateExtensions.swift
1
910
// // DateExtensions.swift // Christmas Fam Duels // // Created by Dave Butz on 11/5/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import Foundation extension NSDate { convenience init(dateString:String) { let dateStringFormatter = NSDateFormatter() dateStringFormatter.dateFormat = "yyyy-MM-dd" dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let d = dateStringFormatter.dateFromString(dateString)! self.init(timeInterval:0, sinceDate:d) } convenience init(dateStringhms:String) { let dateStringFormatter = NSDateFormatter() dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let d = dateStringFormatter.dateFromString(dateStringhms)! self.init(timeInterval:0, sinceDate:d) } }
mit
78086c12aa459ca24469f7ca2fdde85f
30.37931
78
0.69527
4.412621
false
true
false
false
mzaks/FlatBuffersSwiftPerformanceTest
FBTest/bench_common.swift
1
1671
// // bench_commonDefinitions.swift // FBTest // // Created by Maxim Zaks on 27.09.16. // Copyright © 2016 maxim.zaks. All rights reserved. // import Foundation public enum Enum : Int16 { case Apples, Pears, Bananas } public struct Foo : Scalar { public let id : UInt64 public let count : Int16 public let prefix : Int8 public let length : UInt32 } public func ==(v1:Foo, v2:Foo) -> Bool { return v1.id==v2.id && v1.count==v2.count && v1.prefix==v2.prefix && v1.length==v2.length } public struct Bar : Scalar { public let parent : Foo public let time : Int32 public let ratio : Float32 public let size : UInt16 } public func ==(v1:Bar, v2:Bar) -> Bool { return v1.parent==v2.parent && v1.time==v2.time && v1.ratio==v2.ratio && v1.size==v2.size } public final class FooBar { public var sibling : Bar? = nil public var name : String? = nil public var rating : Float64 = 0 public var postfix : UInt8 = 0 public init(){} public init(sibling: Bar?, name: String?, rating: Float64, postfix: UInt8){ self.sibling = sibling self.name = name self.rating = rating self.postfix = postfix } } public final class FooBarContainer { public var list : ContiguousArray<FooBar?> = [] public var initialized : Bool = false public var fruit : Enum? = Enum.Apples public var location : String? = nil public init(){} public init(list: ContiguousArray<FooBar?>, initialized: Bool, fruit: Enum?, location: String?){ self.list = list self.initialized = initialized self.fruit = fruit self.location = location } }
mit
ee9c304ff672ce4fd951ab32d6529014
26.377049
100
0.634731
3.538136
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/TabManagerStore.swift
1
6305
/* 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 Storage import Shared import XCGLogger private let log = Logger.browserLogger class TabManagerStore { fileprivate var lockedForReading = false fileprivate let imageStore: DiskImageStore? fileprivate var fileManager = FileManager.default fileprivate let serialQueue = DispatchQueue(label: "tab-manager-write-queue") fileprivate var writeOperation = DispatchWorkItem {} // Init this at startup with the tabs on disk, and then on each save, update the in-memory tab state. fileprivate lazy var archivedStartupTabs = { return SiteArchiver.tabsToRestore(tabsStateArchivePath: tabsStateArchivePath()) }() init(imageStore: DiskImageStore?, _ fileManager: FileManager = FileManager.default) { self.fileManager = fileManager self.imageStore = imageStore } var isRestoringTabs: Bool { return lockedForReading } var hasTabsToRestoreAtStartup: Bool { return archivedStartupTabs.0.count > 0 } fileprivate func tabsStateArchivePath() -> String? { let profilePath: String? if AppConstants.IsRunningTest || AppConstants.IsRunningPerfTest { profilePath = (UIApplication.shared.delegate as? TestAppDelegate)?.dirForTestProfile } else { profilePath = fileManager.containerURL( forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier)?.appendingPathComponent("profile.profile").path } guard let path = profilePath else { return nil } return URL(fileURLWithPath: path).appendingPathComponent("tabsState.archive").path } fileprivate func prepareSavedTabs(fromTabs tabs: [Tab], selectedTab: Tab?) -> [SavedTab]? { var savedTabs = [SavedTab]() var savedUUIDs = Set<String>() for tab in tabs { tab.tabUUID = tab.tabUUID.isEmpty ? UUID().uuidString : tab.tabUUID if let savedTab = SavedTab(tab: tab, isSelected: tab == selectedTab) { savedTabs.append(savedTab) if let screenshot = tab.screenshot, let screenshotUUID = tab.screenshotUUID { savedUUIDs.insert(screenshotUUID.uuidString) imageStore?.put(screenshotUUID.uuidString, image: screenshot) } } } // Clean up any screenshots that are no longer associated with a tab. _ = imageStore?.clearExcluding(savedUUIDs) return savedTabs.isEmpty ? nil : savedTabs } // Async write of the tab state. In most cases, code doesn't care about performing an operation // after this completes. Deferred completion is called always, regardless of Data.write return value. // Write failures (i.e. due to read locks) are considered inconsequential, as preserveTabs will be called frequently. @discardableResult func preserveTabs(_ tabs: [Tab], selectedTab: Tab?) -> Success { assert(Thread.isMainThread) print("preserve tabs!, existing tabs: \(tabs.count)") guard let savedTabs = prepareSavedTabs(fromTabs: tabs, selectedTab: selectedTab), let path = tabsStateArchivePath() else { clearArchive() return succeed() } writeOperation.cancel() let tabStateData = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: tabStateData) archiver.encode(savedTabs, forKey: "tabs") archiver.finishEncoding() let simpleTabs = SimpleTab.convertToSimpleTabs(savedTabs) let result = Success() writeOperation = DispatchWorkItem { let written = tabStateData.write(toFile: path, atomically: true) SimpleTab.saveSimpleTab(tabs: simpleTabs) // Ignore write failure (could be restoring). log.debug("PreserveTabs write ok: \(written), bytes: \(tabStateData.length)") result.fill(Maybe(success: ())) } // Delay by 100ms to debounce repeated calls to preserveTabs in quick succession. // Notice above that a repeated 'preserveTabs' call will 'cancel()' a pending write operation. serialQueue.asyncAfter(deadline: .now() + 0.100, execute: writeOperation) return result } func restoreStartupTabs(clearPrivateTabs: Bool, tabManager: TabManager) -> Tab? { let selectedTab = restoreTabs(savedTabs: archivedStartupTabs.0, clearPrivateTabs: clearPrivateTabs, tabManager: tabManager) return selectedTab } func restoreTabs(savedTabs: [SavedTab], clearPrivateTabs: Bool, tabManager: TabManager) -> Tab? { assertIsMainThread("Restoration is a main-only operation") guard !lockedForReading, savedTabs.count > 0 else { return nil } lockedForReading = true defer { lockedForReading = false } var savedTabs = savedTabs // Make sure to wipe the private tabs if the user has the pref turned on if clearPrivateTabs { savedTabs = savedTabs.filter { !$0.isPrivate } } var tabToSelect: Tab? for savedTab in savedTabs { // Provide an empty request to prevent a new tab from loading the home screen var tab = tabManager.addTab(flushToDisk: false, zombie: true, isPrivate: savedTab.isPrivate) tab = savedTab.configureSavedTabUsing(tab, imageStore: imageStore) if savedTab.isSelected { tabToSelect = tab } } if tabToSelect == nil { tabToSelect = tabManager.tabs.first(where: { $0.isPrivate == false }) } return tabToSelect } func clearArchive() { if let path = tabsStateArchivePath() { try? FileManager.default.removeItem(atPath: path) } } } // Functions for testing extension TabManagerStore { func testTabCountOnDisk() -> Int { assert(AppConstants.IsRunningTest) return SiteArchiver.tabsToRestore(tabsStateArchivePath: tabsStateArchivePath()).0.count } }
mpl-2.0
c119acf6a844e3c5c4d5f655292afdbd
39.941558
173
0.657891
5.302775
false
false
false
false
barbosa/clappr-ios
Pod/Classes/Enum/PlayerEvent.swift
1
499
public enum PlayerEvent: String { case Ready = "clappr:playback:ready" case Ended = "clappr:playback:ended" case Play = "clappr:playback:play" case Pause = "clappr:playback:pause" case Error = "clappr:playback:error" case Stop = "clappr:playback:stop" case MediaControlShow = "clappr:core:mediacontrol:show" case MediaControlHide = "clappr:core:mediacontrol:hide" case EnterFullscreen = "player:enterfullscreen" case ExitFullscreen = "player:exitfullscreen" }
bsd-3-clause
676741bc524d5628fcc3f90189721c50
40.666667
59
0.723447
3.80916
false
false
false
false
wess/overlook
Sources/overlook/commands/default.swift
1
1874
// // default.swift // overlook // // Created by Wesley Cope on 9/30/16. // // import Foundation import PathKit import SwiftCLI import Rainbow import config import env import task import watch public class DefaultCommand : Command { public let name = "" public let signature = "[<optional>] ..." public let shortDescription = "" private let taskManager = TaskManager() private var env = Env() private var directories = [String]() private var exec = [String]() private var ignore = [String]() public init() {} public func execute(arguments: CommandArguments) throws { guard let settings = Config() else { throw CLIError.error("Unable to locate .overlook file, please run `overlook init`") } directories = settings.directories.map { String(describing: Path($0).absolute()) } ignore = settings.ignore.map { String(describing: Path($0).absolute()) } exec = settings.execute.components(separatedBy: " ") taskManager.verbose = settings.verbose guard directories.count > 0, exec.count > 0 else { throw CLIError.error("No `directories` or `execute` found in .overlook file. They are required. ") } startup(exec.joined(separator: " "), watching: directories) taskManager.create(exec) {[weak self] (data) in guard let `self` = self, let str = String(data: data, encoding: .utf8) else { return } let output = str.trimmingCharacters(in: .whitespacesAndNewlines) if self.taskManager.verbose && output.characters.count > 0 { print(output) } } taskManager.start() watch() } private func watch() { Watch(directories, exclude:ignore) { self.taskManager.restart() } } private func setupEnv(_ vars:[String:String]) { for(k,v) in vars { env[k] = v } } }
mit
385df6d234e4d171927f7025aab1942d
23.986667
104
0.635539
4.073913
false
false
false
false
ddgold/Cathedral
Cathedral/Theme.swift
1
2850
// // Theme.swift // Cathedral // // Created by Doug Goldstein on 2/23/19. // Copyright © 2019 Doug Goldstein. All rights reserved. // import UIKit /// Theme object. struct Theme: Equatable { //MARK: - Properties /// Current active theme. static private(set) var activeTheme = Theme(Theme.activeName) /// Name of the active theme's name static var activeName: Theme.Name { get { return Theme.Name(rawValue: UserDefaults.standard.string(forKey: "activeTheme") ?? "Black")! } set { activeTheme = Theme(newValue) UserDefaults.standard.set(newValue.rawValue, forKey: "activeTheme") NotificationCenter.default.post(name: .themeChange, object: nil) } } /// Name of the theme let name: Theme.Name /// Color for the tints. let tintColor: UIColor /// Style for all bars, navigator and tab. let barStyle: UIBarStyle /// Color for the background. let backgroundColor: UIColor /// Color for the foreground. let foregroundColor: UIColor /// Color for the text. let textColor: UIColor //MARK: - Initialization /// Initializes a new theme object. /// /// - Parameter name: The theme's name. private init(_ name: Name) { self.name = name switch name { case .black: tintColor = .orange barStyle = .black backgroundColor = UIColor(white: 0.15, alpha: 1) foregroundColor = UIColor(white: 0.1, alpha: 1) textColor = .white case .white: tintColor = .blue barStyle = .default backgroundColor = UIColor(white: 0.95, alpha: 1) foregroundColor = UIColor(white: 1, alpha: 1) textColor = .black } } //MARK: - Functions /// Subscribes an object to theme changes. /// /// - Parameters: /// - subscriber: Object subcribing to theme changes. /// - selector: Method to call when themes change. The method specified by selectot must have one and only one argument (an instance of NSNotification). static func subscribe(_ subscriber: Any, selector: Selector) { NotificationCenter.default.addObserver(subscriber, selector: selector, name: .themeChange, object: nil) } //MARK: - Name Enum /// A theme name. enum Name: String { /// Darkest black theme. case black = "Black" /// Lightest white theme. case white = "White" } } //MARK: - Notification.Name Extention /// Extention of Notification.Name to add themeChange. extension Notification.Name { static let themeChange = Notification.Name("com.ddgold.Cathedral.notifications.themeChange") }
apache-2.0
d19f050719dc834eb28cc18895c1df96
26.394231
160
0.595297
4.50079
false
false
false
false
MyPureCloud/platform-client-sdk-common
resources/sdk/purecloudios/extensions/GenericJSON/JSON.swift
1
2541
import Foundation /// A JSON value representation. This is a bit more useful than the naïve `[String:Any]` type /// for JSON values, since it makes sure only valid JSON values are present & supports `Equatable` /// and `Codable`, so that you can compare values for equality and code and decode them into data /// or strings. public enum JSON: Equatable { case string(String) case number(Float) case object([String:JSON]) case array([JSON]) case bool(Bool) case null } extension JSON: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case let .array(array): try container.encode(array) case let .object(object): try container.encode(object) case let .string(string): try container.encode(string) case let .number(number): try container.encode(number) case let .bool(bool): try container.encode(bool) case .null: try container.encodeNil() } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let object = try? container.decode([String: JSON].self) { self = .object(object) } else if let array = try? container.decode([JSON].self) { self = .array(array) } else if let string = try? container.decode(String.self) { self = .string(string) } else if let bool = try? container.decode(Bool.self) { self = .bool(bool) } else if let number = try? container.decode(Float.self) { self = .number(number) } else if container.decodeNil() { self = .null } else { throw DecodingError.dataCorrupted( .init(codingPath: decoder.codingPath, debugDescription: "Invalid JSON value.") ) } } } extension JSON: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .string(let str): return str.debugDescription case .number(let num): return num.debugDescription case .bool(let bool): return bool.description case .null: return "null" default: let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted] return try! String(data: encoder.encode(self), encoding: .utf8)! } } }
mit
149e69a3410a84a135b8c0d62ad5c49e
30.75
98
0.594094
4.584838
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Live/View/YSLiveHeaderView.swift
1
4130
// // homeLivehead.swift // zhnbilibili // // Created by zhn on 16/11/29. // Copyright © 2016年 zhn. All rights reserved. // import UIKit let kLiveMenuHeight: CGFloat = 100 class YSLiveHeaderView: UICollectionReusableView { // 普通的头部数据 var headModel: YSLiveHeadModel? { didSet { // 1. 设置图标 if let imgStr = headModel?.sub_icon?.src { let imgUrl = URL(string: imgStr) contentView.iconImageView.kf.setImage(with: imgUrl) } // 2. 设置坐标的标题 contentView.iconLabel.text = headModel?.name // 3. 设置标题的文字 let countString = String.creatCountString(count: (headModel?.count)!) let attrStr = String.creatAttributesText(countString: countString, beginStr: "当前", endStr: "个直播,进去看看") contentView.noticeLabel.attributedText = attrStr // 4. 设置arrowimage contentView.arrImageView.image = UIImage(named: "common_rightArrowShadow") contentView.rightIconImageView.isHidden = true // 5. 更改控件位置 normalHead() } } // 带banner的数据 var bannerModelArray: [YSLiveBannerModel]? { didSet{ // 1. 赋值数据 var imageStringArray = [String]() guard let bannerModelArray = bannerModelArray else {return} for model in bannerModelArray{ guard let imgString = model.img else {return} imageStringArray.append(imgString) } carouselView.intnetImageArray = imageStringArray // 2.更改位置 topHead() } } // MARK: - 懒加载控件 lazy var contentView: YSCollectionNormalHeader = { let conteView = YSCollectionNormalHeader() return conteView }() lazy var carouselView: YSCarouselView = { let carouselView = YSCarouselView(viewframe: CGRect(x: 0, y: 0, width: kScreenWidth, height: kCarouseHeight)) carouselView.delegate = self return carouselView }() lazy var menuView: YSLiveHeadMenu = { let menuView = YSLiveHeadMenu() menuView.backgroundColor = kHomeBackColor return menuView }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(contentView) self.addSubview(carouselView) self.addSubview(menuView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 私有方法 extension YSLiveHeaderView { // 普通头部的内部控件的位置 fileprivate func normalHead() { menuView.isHidden = true carouselView.removeFromSuperview() menuView.removeFromSuperview() contentView.snp.remakeConstraints { (make) in make.left.top.bottom.right.equalTo(self) } } // 第一个section的内部控件的位置 fileprivate func topHead() { menuView.isHidden = false self.addSubview(carouselView) self.addSubview(menuView) carouselView.snp.remakeConstraints { (make) in make.left.right.top.equalTo(self) make.height.equalTo(kCarouseHeight) } menuView.snp.remakeConstraints { (make) in make.top.equalTo(carouselView.snp.bottom) make.left.right.equalTo(self) make.height.equalTo(kLiveMenuHeight) } contentView.snp.remakeConstraints { (make) in make.left.bottom.right.equalTo(self) make.top.equalTo(menuView.snp.bottom) } } } extension YSLiveHeaderView: YSCarouselViewDelegate { func carouselViewSelectedIndex(index: Int) { guard let model = bannerModelArray?[index] else {return} guard let link = model.link else {return} YSNotificationHelper.livecarouselClickNotification(link: link) } }
mit
2b7e5608afd9ba36776d6982f106fc7c
28.962121
117
0.598989
4.658422
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClientTests/Model/RepositorySpec.swift
1
4947
/* Copyright 2017 - André Gimenez Faria 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 Quick import Nimble @testable import MiniGitClient class RepositorySpec: QuickSpec { override func spec() { describe("The Repository") { var repo = Repository() beforeEach { repo = Repository() } context("has", closure: { it("a name property") { repo.name = "Name" expect(repo.name) == "Name" } it("a info property") { repo.info = "Description" expect(repo.info) == "Description" } it("a stars count property") { repo.starsCount = 13 expect(repo.starsCount) == 13 } it("a forks count property") { repo.forksCount = 13 expect(repo.forksCount) == 13 } it("an url property") { let url = URL(string: "http://www.pudim.com.br") repo.url = url expect(repo.url) == url } it("an user property") { let user = User() repo.user = user expect(repo.user) == user } }) context("can", closure: { let validJson : DataDict = ["name" : "Name", "description" : "Description", "stargazers_count" : 13, "forks_count" : 13, "url" : "http://www.pudim.com.br", "owner" : [ "name" : "André", "avatar_url" : nil ]] let emptyJson = DataDict() it("be created from a JSON dictionary") { repo = Repository(json: validJson) expect(repo.name) == validJson["name"] as? String expect(repo.info) == validJson["description"] as? String expect(repo.starsCount) == validJson["stargazers_count"] as? Int expect(repo.forksCount) == validJson["forks_count"] as? Int expect(repo.url) == URL(string: validJson["url"] as? String ?? "") expect(repo.user).toNot(beNil()) } it("be created from an invalid JSON dictionary and hold the default values") { repo = Repository(json: emptyJson) expect(repo.name).to(beEmpty()) expect(repo.info).to(beEmpty()) expect(repo.starsCount) == 0 expect(repo.forksCount) == 0 expect(repo.url).to(beNil()) expect(repo.user).to(beNil()) } }) context("is", { it("equatable") { let secondRepo = Repository() expect(repo) == secondRepo } it("printable") { expect(repo.description).notTo(beEmpty()) } it("debug printable") { expect(repo.debugDescription).notTo(beEmpty()) } }) } } }
mit
398847ee68d4fdcb992b0e9f053e0f13
39.867769
461
0.447725
5.865955
false
false
false
false
mattermost/mattermost-mobile
ios/Gekidou/Sources/Gekidou/Storage/Database.swift
1
7638
// // Database.swift // Gekidou // // Created by Miguel Alatzar on 8/20/21. // import Foundation import SQLite3 import SQLite // TODO: This should be exposed to Objective-C in order to handle // any Database throwable methods. enum DatabaseError: Error { case OpenFailure(_ dbPath: String) case MultipleServers case NoResults(_ query: String) case NoDatabase(_ serverUrl: String) case InsertError(_ statement: String) } extension DatabaseError: LocalizedError { var errorDescription: String? { switch self { case .OpenFailure(dbPath: let dbPath): return "Error opening database: \(dbPath)" case .MultipleServers: return "Cannot determine server URL as there are multiple servers" case .NoResults(query: let query): return "No results for query: \(query)" case .NoDatabase(serverUrl: let serverUrl): return "No database for server: \(serverUrl)" case .InsertError(statement: let statement): return "Insert error: \(statement)" } } } public class Database: NSObject { internal let DEFAULT_DB_NAME = "app.db" internal var DEFAULT_DB_PATH: String internal var defaultDB: OpaquePointer? = nil internal var serversTable = Table("Servers") internal var systemTable = Table("System") internal var teamTable = Table("Team") internal var myTeamTable = Table("MyTeam") internal var channelTable = Table("Channel") internal var channelInfoTable = Table("ChannelInfo") internal var channelMembershipTable = Table("ChannelMembership") internal var myChannelTable = Table("MyChannel") internal var myChannelSettingsTable = Table("MyChannelSettings") internal var postTable = Table("Post") internal var postsInChannelTable = Table("PostsInChannel") internal var postsInThreadTable = Table("PostsInThread") internal var postMetadataTable = Table("PostMetadata") internal var reactionTable = Table("Reaction") internal var fileTable = Table("File") internal var emojiTable = Table("CustomEmoji") internal var userTable = Table("User") internal var threadTable = Table("Thread") internal var threadParticipantTable = Table("ThreadParticipant") internal var configTable = Table("Config") @objc public static let `default` = Database() override private init() { let appGroupId = Bundle.main.object(forInfoDictionaryKey: "AppGroupIdentifier") as! String let sharedDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupId)! let databaseUrl = sharedDirectory.appendingPathComponent("databases/\(DEFAULT_DB_NAME)") DEFAULT_DB_PATH = databaseUrl.path } @objc public func getOnlyServerUrlObjc() -> String { do { return try getOnlyServerUrl() } catch { print(error) return "" } } public func generateId() -> String { let alphabet = Array("0123456789abcdefghijklmnopqrstuvwxyz") let alphabetLenght = alphabet.count let idLenght = 16 var id = "" for _ in 1...(idLenght / 2) { let random = floor(Double.random(in: 0..<1) * Double(alphabetLenght) * Double(alphabetLenght)) let firstIndex = Int(floor(random / Double(alphabetLenght))) let lastIndex = Int(random) % alphabetLenght id += String(alphabet[firstIndex]) id += String(alphabet[lastIndex]) } return id } public func getOnlyServerUrl() throws -> String { let db = try Connection(DEFAULT_DB_PATH) let url = Expression<String>("url") let identifier = Expression<String>("identifier") let lastActiveAt = Expression<Int64>("last_active_at") let query = serversTable.select(url).filter(lastActiveAt > 0 && identifier != "") var serverUrl: String? for result in try db.prepare(query) { if (serverUrl != nil) { throw DatabaseError.MultipleServers } serverUrl = try result.get(url) } if (serverUrl != nil) { return serverUrl! } throw DatabaseError.NoResults(query.asSQL()) } public func getServerUrlForServer(_ id: String) throws -> String { let db = try Connection(DEFAULT_DB_PATH) let url = Expression<String>("url") let identifier = Expression<String>("identifier") let query = serversTable.select(url).filter(identifier == id) if let server = try db.pluck(query) { let serverUrl: String? = try server.get(url) if (serverUrl != nil) { return serverUrl! } } throw DatabaseError.NoResults(query.asSQL()) } public func getAllActiveDatabases<T: Codable>() -> [T] { guard let db = try? Connection(DEFAULT_DB_PATH) else {return []} let lastActiveAt = Expression<Int64>("last_active_at") let identifier = Expression<String>("identifier") let query = serversTable.filter(lastActiveAt > 0 && identifier != "").order(lastActiveAt.desc) do { let rows = try db.prepare(query) let servers: [T] = try rows.map { row in return try row.decode() } return servers } catch { return [] } } public func getAllActiveServerUrls() -> [String] { guard let db = try? Connection(DEFAULT_DB_PATH) else {return []} let lastActiveAt = Expression<Int64>("last_active_at") let identifier = Expression<String>("identifier") let url = Expression<String>("url") let query = serversTable.filter(lastActiveAt > 0 && identifier != "").order(lastActiveAt.desc) do { let rows = try db.prepare(query) let servers: [String] = try rows.map { row in return try row.get(url) } return servers } catch { return [] } } public func getCurrentServerDatabase<T: Codable>() -> T? { guard let db = try? Connection(DEFAULT_DB_PATH) else {return nil} do { let lastActiveAt = Expression<Int64>("last_active_at") let identifier = Expression<String>("identifier") let query = serversTable.filter(lastActiveAt > 0 && identifier != "").order(lastActiveAt.desc) if let result = try db.pluck(query) { let server: T = try result.decode() return server } return nil } catch { return nil } } internal func getDatabaseForServer(_ serverUrl: String) throws -> Connection { let db = try Connection(DEFAULT_DB_PATH) let url = Expression<String>("url") let dbPath = Expression<String>("db_path") let query = serversTable.select(dbPath).where(url == serverUrl) if let result = try db.pluck(query) { let path = try result.get(dbPath) return try Connection(path) } throw DatabaseError.NoResults(query.asSQL()) } internal func json(from object:Any?) -> String? { guard let object = object, let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { return nil } return String(data: data, encoding: String.Encoding.utf8) } }
apache-2.0
db41c93a5041ce8021a271966996514a
34.859155
117
0.603954
4.738213
false
false
false
false
readium/r2-streamer-swift
r2-streamer-swift/Toolkit/DataCompression.swift
1
22527
/// /// DataCompression /// /// A libcompression wrapper as an extension for the `Data` type /// (GZIP, ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951, RFC-1952) /// /// Created by Markus Wanke, 2016/12/05 /// /// /// Apache License, Version 2.0 /// /// Copyright 2016, Markus Wanke /// /// 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 Compression public extension Data { /// Compresses the data. /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type /// - returns: compressed data func compress(withAlgorithm algo: CompressionAlgorithm) -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: algo.lowLevelType) return perform(config, source: sourcePtr, sourceSize: count) } } /// Decompresses the data. /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type /// - returns: decompressed data func decompress(withAlgorithm algo: CompressionAlgorithm) -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: algo.lowLevelType) return perform(config, source: sourcePtr, sourceSize: count) } } /// Please consider the [libcompression documentation](https://developer.apple.com/reference/compression/1665429-data_compression) /// for further details. Short info: /// zlib : Aka deflate. Fast with a good compression rate. Proved itself over time and is supported everywhere. /// lzfse : Apples custom Lempel-Ziv style compression algorithm. Claims to compress as good as zlib but 2 to 3 times faster. /// lzma : Horribly slow. Compression as well as decompression. Compresses better than zlib though. /// lz4 : Fast, but compression rate is very bad. Apples lz4 implementation often to not compress at all. enum CompressionAlgorithm { case zlib case lzfse case lzma case lz4 } /// Compresses the data using the zlib deflate algorithm. /// - returns: raw deflated data according to [RFC-1951](https://tools.ietf.org/html/rfc1951). /// - note: Fixed at compression level 5 (best trade off between speed and time) func deflate() -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count) } } /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a raw deflate /// stream according to [RFC-1951](https://tools.ietf.org/html/rfc1951). /// - returns: uncompressed data func inflate() -> Data? { return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count) } } /// Compresses the data using the deflate algorithm and makes it comply to the zlib format. /// - returns: deflated data in zlib format [RFC-1950](https://tools.ietf.org/html/rfc1950) /// - note: Fixed at compression level 5 (best trade off between speed and time) func zip() -> Data? { let header = Data([0x78, 0x5e]) let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count, preload: header) } guard var result = deflated else { return nil } var adler = self.adler32().checksum.bigEndian result.append(Data(bytes: &adler, count: MemoryLayout<UInt32>.size)) return result } /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a zlib deflate /// stream according to [RFC-1950](https://tools.ietf.org/html/rfc1950). /// - returns: uncompressed data func unzip(skipCheckSumValidation: Bool = true) -> Data? { // 2 byte header + 4 byte adler32 checksum let overhead = 6 guard count > overhead else { return nil } let header: UInt16 = withUnsafeBytes { (ptr: UnsafePointer<UInt16>) -> UInt16 in return ptr.pointee.bigEndian } // check for the deflate stream bit guard header >> 8 & 0b1111 == 0b1000 else { return nil } // check the header checksum guard header % 31 == 0 else { return nil } let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data? in let source = ptr.advanced(by: 2) let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: source, sourceSize: count - overhead) } guard let inflated = cresult else { return nil } if skipCheckSumValidation { return inflated } let cksum: UInt32 = withUnsafeBytes { (bytePtr: UnsafePointer<UInt8>) -> UInt32 in let last = bytePtr.advanced(by: count - 4) return last.withMemoryRebound(to: UInt32.self, capacity: 1) { (intPtr) -> UInt32 in return intPtr.pointee.bigEndian } } return cksum == inflated.adler32().checksum ? inflated : nil } /// Compresses the data using the deflate algorithm and makes it comply to the gzip stream format. /// - returns: deflated data in gzip format [RFC-1952](https://tools.ietf.org/html/rfc1952) /// - note: Fixed at compression level 5 (best trade off between speed and time) func gzip() -> Data? { var header = Data([0x1f, 0x8b, 0x08, 0x00]) // magic, magic, deflate, noflags var unixtime = UInt32(Date().timeIntervalSince1970).littleEndian header.append(Data(bytes: &unixtime, count: MemoryLayout<UInt32>.size)) header.append(contentsOf: [0x00, 0x03]) // normal compression level, unix file type let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: sourcePtr, sourceSize: count, preload: header) } guard var result = deflated else { return nil } // append checksum var crc32: UInt32 = self.crc32().checksum.littleEndian result.append(Data(bytes: &crc32, count: MemoryLayout<UInt32>.size)) // append size of original data var isize: UInt32 = UInt32(truncatingIfNeeded: count).littleEndian result.append(Data(bytes: &isize, count: MemoryLayout<UInt32>.size)) return result } /// Decompresses the data using the gzip deflate algorithm. Self is expected to be a gzip deflate /// stream according to [RFC-1952](https://tools.ietf.org/html/rfc1952). /// - returns: uncompressed data func gunzip() -> Data? { // 10 byte header + data + 8 byte footer. See https://tools.ietf.org/html/rfc1952#section-2 let overhead = 10 + 8 guard count >= overhead else { return nil } typealias GZipHeader = (id1: UInt8, id2: UInt8, cm: UInt8, flg: UInt8, xfl: UInt8, os: UInt8) let hdr: GZipHeader = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> GZipHeader in // +---+---+---+---+---+---+---+---+---+---+ // |ID1|ID2|CM |FLG| MTIME |XFL|OS | // +---+---+---+---+---+---+---+---+---+---+ return (id1: ptr[0], id2: ptr[1], cm: ptr[2], flg: ptr[3], xfl: ptr[8], os: ptr[9]) } typealias GZipFooter = (crc32: UInt32, isize: UInt32) let ftr: GZipFooter = withUnsafeBytes { (bptr: UnsafePointer<UInt8>) -> GZipFooter in // +---+---+---+---+---+---+---+---+ // | CRC32 | ISIZE | // +---+---+---+---+---+---+---+---+ return bptr.advanced(by: count - 8).withMemoryRebound(to: UInt32.self, capacity: 2) { ptr in return (ptr[0].littleEndian, ptr[1].littleEndian) } } // Wrong gzip magic or unsupported compression method guard hdr.id1 == 0x1f && hdr.id2 == 0x8b && hdr.cm == 0x08 else { return nil } let has_crc16: Bool = hdr.flg & 0b00010 != 0 let has_extra: Bool = hdr.flg & 0b00100 != 0 let has_fname: Bool = hdr.flg & 0b01000 != 0 let has_cmmnt: Bool = hdr.flg & 0b10000 != 0 let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data? in var pos = 10 ; let limit = count - 8 if has_extra { pos += ptr.advanced(by: pos).withMemoryRebound(to: UInt16.self, capacity: 1) { return Int($0.pointee.littleEndian) + 2 // +2 for xlen } } if has_fname { while pos < limit && ptr[pos] != 0x0 { pos += 1 } pos += 1 // skip null byte as well } if has_cmmnt { while pos < limit && ptr[pos] != 0x0 { pos += 1 } pos += 1 // skip null byte as well } if has_crc16 { pos += 2 // ignoring header crc16 } guard pos < limit else { return nil } let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) return perform(config, source: ptr.advanced(by: pos), sourceSize: limit - pos) } guard let inflated = cresult else { return nil } guard ftr.isize == UInt32(truncatingIfNeeded: inflated.count) else { return nil } guard ftr.crc32 == inflated.crc32().checksum else { return nil } return inflated } /// Calculate the Adler32 checksum of the data. /// - returns: Adler32 checksum type. Can still be further advanced. func adler32() -> Adler32 { var res = Adler32() res.advance(withChunk: self) return res } /// Calculate the Crc32 checksum of the data. /// - returns: Crc32 checksum type. Can still be further advanced. func crc32() -> Crc32 { var res = Crc32() res.advance(withChunk: self) return res } } /// Struct based type representing a Crc32 checksum. public struct Crc32: CustomStringConvertible { private static let zLibCrc32: ZLibCrc32FuncPtr? = loadCrc32fromZLib() public init() {} // C convention function pointer type matching the signature of `libz::crc32` private typealias ZLibCrc32FuncPtr = @convention(c) ( _ cks: UInt32, _ buf: UnsafePointer<UInt8>, _ len: UInt32 ) -> UInt32 /// Raw checksum. Updated after a every call to `advance(withChunk:)` public var checksum: UInt32 = 0 /// Advance the current checksum with a chunk of data. Designed t be called multiple times. /// - parameter chunk: data to advance the checksum public mutating func advance(withChunk chunk: Data) { if let fastCrc32 = Crc32.zLibCrc32 { checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer<UInt8>) -> UInt32 in return fastCrc32(checksum, ptr, UInt32(chunk.count)) }) } else { checksum = slowCrc32(start: checksum, data: chunk) } } /// Formatted checksum. public var description: String { return String(format: "%08x", checksum) } /// Load `crc32()` from '/usr/lib/libz.dylib' if libz is installed. /// - returns: A function pointer to crc32() of zlib or nil if zlib can't be found private static func loadCrc32fromZLib() -> ZLibCrc32FuncPtr? { guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW) else { return nil } guard let fptr = dlsym(libz, "crc32") else { return nil } return unsafeBitCast(fptr, to: ZLibCrc32FuncPtr.self) } /// Rudimentary fallback implementation of the crc32 checksum. This is only a backup used /// when zlib can't be found under '/usr/lib/libz.dylib'. /// - returns: crc32 checksum (4 byte) private func slowCrc32(start: UInt32, data: Data) -> UInt32 { return ~data.reduce(~start) { (crc: UInt32, next: UInt8) -> UInt32 in let tableOffset = (crc ^ UInt32(next)) & 0xff return lookUpTable[Int(tableOffset)] ^ crc >> 8 } } /// Lookup table for faster crc32 calculation. /// table source: http://web.mit.edu/freebsd/head/sys/libkern/crc32.c private let lookUpTable: [UInt32] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, ] } /// Struct based type representing a Adler32 checksum. public struct Adler32: CustomStringConvertible { private static let zLibAdler32: ZLibAdler32FuncPtr? = loadAdler32fromZLib() public init() {} // C convention function pointer type matching the signature of `libz::adler32` private typealias ZLibAdler32FuncPtr = @convention(c) ( _ cks: UInt32, _ buf: UnsafePointer<UInt8>, _ len: UInt32 ) -> UInt32 /// Raw checksum. Updated after a every call to `advance(withChunk:)` public var checksum: UInt32 = 1 /// Advance the current checksum with a chunk of data. Designed t be called multiple times. /// - parameter chunk: data to advance the checksum public mutating func advance(withChunk chunk: Data) { if let fastAdler32 = Adler32.zLibAdler32 { checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer<UInt8>) -> UInt32 in return fastAdler32(checksum, ptr, UInt32(chunk.count)) }) } else { checksum = slowAdler32(start: checksum, data: chunk) } } /// Formatted checksum. public var description: String { return String(format: "%08x", checksum) } /// Load `adler32()` from '/usr/lib/libz.dylib' if libz is installed. /// - returns: A function pointer to adler32() of zlib or nil if zlib can't be found private static func loadAdler32fromZLib() -> ZLibAdler32FuncPtr? { guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW) else { return nil } guard let fptr = dlsym(libz, "adler32") else { return nil } return unsafeBitCast(fptr, to: ZLibAdler32FuncPtr.self) } /// Rudimentary fallback implementation of the adler32 checksum. This is only a backup used /// when zlib can't be found under '/usr/lib/libz.dylib'. /// - returns: adler32 checksum (4 byte) private func slowAdler32(start: UInt32, data: Data) -> UInt32 { var s1: UInt32 = start & 0xffff var s2: UInt32 = (start >> 16) & 0xffff let prime: UInt32 = 65521 for byte in data { s1 += UInt32(byte) if s1 >= prime { s1 = s1 % prime } s2 += s1 if s2 >= prime { s2 = s2 % prime } } return (s2 << 16) | s1 } } fileprivate extension Data { func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try self.withUnsafeBytes({ (rawBufferPointer: UnsafeRawBufferPointer) -> ResultType in return try body(rawBufferPointer.bindMemory(to: ContentType.self).baseAddress!) }) } } fileprivate extension Data.CompressionAlgorithm { var lowLevelType: compression_algorithm { switch self { case .zlib : return COMPRESSION_ZLIB case .lzfse : return COMPRESSION_LZFSE case .lz4 : return COMPRESSION_LZ4 case .lzma : return COMPRESSION_LZMA } } } fileprivate typealias Config = (operation: compression_stream_operation, algorithm: compression_algorithm) fileprivate func perform(_ config: Config, source: UnsafePointer<UInt8>, sourceSize: Int, preload: Data = Data()) -> Data? { guard config.operation == COMPRESSION_STREAM_ENCODE || sourceSize > 0 else { return nil } let streamBase = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1) defer { streamBase.deallocate() } var stream = streamBase.pointee let status = compression_stream_init(&stream, config.operation, config.algorithm) guard status != COMPRESSION_STATUS_ERROR else { return nil } defer { compression_stream_destroy(&stream) } var result = preload var flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) let blockLimit = 64 * 1024 var bufferSize = Swift.max(sourceSize, 64) if sourceSize > blockLimit { bufferSize = blockLimit if config.algorithm == COMPRESSION_LZFSE && config.operation != COMPRESSION_STREAM_ENCODE { // This fixes a bug in Apples lzfse decompressor. it will sometimes fail randomly when the input gets // splitted into multiple chunks and the flag is not 0. Even though it should always work with FINALIZE... flags = 0 } } let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) defer { buffer.deallocate() } stream.dst_ptr = buffer stream.dst_size = bufferSize stream.src_ptr = source stream.src_size = sourceSize while true { switch compression_stream_process(&stream, flags) { case COMPRESSION_STATUS_OK: guard stream.dst_size == 0 else { return nil } result.append(buffer, count: stream.dst_ptr - buffer) stream.dst_ptr = buffer stream.dst_size = bufferSize if flags == 0 && stream.src_size == 0 { // part of the lzfse bugfix above flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) } case COMPRESSION_STATUS_END: result.append(buffer, count: stream.dst_ptr - buffer) return result default: return nil } } }
bsd-3-clause
58b83ca7d2185b5f1172769dce8fa929
42.656977
134
0.631065
3.511613
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/OpenTelemetrySdk/Trace/SpanLimits.swift
1
2550
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetryApi /// Struct that holds global trace parameters. public struct SpanLimits: Equatable { // These values are the default values for all the global parameters. // TODO: decide which default sampler to use /// The global default max number of attributes perSpan. public private(set) var attributeCountLimit: Int = 128 /// the global default max number of Events per Span. public private(set) var eventCountLimit: Int = 128 /// the global default max number of Link entries per Span. public private(set) var linkCountLimit: Int = 128 /// the global default max number of attributes per Event. public private(set) var attributePerEventCountLimit: Int = 128 /// the global default max number of attributes per Link. public private(set) var attributePerLinkCountLimit: Int = 128 /// Returns the defaultSpanLimits. public init() {} @discardableResult public func settingAttributeCountLimit(_ number: UInt) -> Self { var spanLimits = self spanLimits.attributeCountLimit = number > 0 ? Int(number) : 0 return spanLimits } @discardableResult public func settingEventCountLimit(_ number: UInt) -> Self { var spanLimits = self spanLimits.eventCountLimit = number > 0 ? Int(number) : 0 return spanLimits } @discardableResult public func settingLinkCountLimit(_ number: UInt) -> Self { var spanLimits = self spanLimits.linkCountLimit = number > 0 ? Int(number) : 0 return spanLimits } @discardableResult public func settingAttributePerEventCountLimit(_ number: UInt) -> Self { var spanLimits = self spanLimits.attributePerEventCountLimit = number > 0 ? Int(number) : 0 return spanLimits } @discardableResult public func settingAttributePerLinkCountLimit(_ number: UInt) -> Self { var spanLimits = self spanLimits.attributePerLinkCountLimit = number > 0 ? Int(number) : 0 return spanLimits } public static func == (lhs: SpanLimits, rhs: SpanLimits) -> Bool { return lhs.attributeCountLimit == rhs.attributeCountLimit && lhs.eventCountLimit == rhs.eventCountLimit && lhs.linkCountLimit == rhs.linkCountLimit && lhs.attributePerEventCountLimit == rhs.attributePerEventCountLimit && lhs.attributePerLinkCountLimit == rhs.attributePerLinkCountLimit } }
apache-2.0
a1b29a4dc84ce807e2d70a9779b77e8a
38.84375
95
0.69098
5.059524
false
false
false
false
hollance/swift-algorithm-club
Octree/Octree.playground/Contents.swift
3
986
//: Playground - noun: a place where people can play import UIKit import simd let boxMin = vector_double3(0, 2, 6) let boxMax = vector_double3(5, 10, 9) let box = Box(boxMin: boxMin, boxMax: boxMax) var octree = Octree<Int>(boundingBox: box, minimumCellSize: 5.0) var five = octree.add(5, at: vector_double3(3,4,8)) octree.add(8, at: vector_double3(3,4,8.2)) octree.add(10, at: vector_double3(3,4,8.2)) octree.add(7, at: vector_double3(2,5,8)) octree.add(2, at: vector_double3(1,6,7)) var cont = octree.elements(at: vector_double3(3,4,8.2)) octree.remove(8) octree.elements(at: vector_double3(3,4,8)) let boxMin2 = vector_double3(1,3,7) let boxMax2 = vector_double3(4,9,8) let box2 = Box(boxMin: boxMin2, boxMax: boxMax2) box.isContained(in: box2) box.intersects(box2) let boxMin3 = vector_double3(3,8,8) let boxMax3 = vector_double3(10,12,20) let box3 = Box(boxMin: boxMin3, boxMax: boxMax3) box3.intersects(box3) octree.elements(in: box) octree.elements(in: box2) print(octree)
mit
efc406848a38a22cfbfa60c7ae5ee735
28.878788
64
0.721095
2.471178
false
false
false
false
jseanj/SwiftMapping
Demo/SwiftMappingDemo/SwiftMappingDemo/SwiftMapping/ModelSerializer.swift
1
2565
// // ModelSerializer.swift // SwiftMappingDemo // // Created by jin.shang on 14-10-31. // Copyright (c) 2014年 BlackWater. All rights reserved. // import Foundation class ModelSerializer { var className: NSObject.Type var path: String init(modelClass className: NSObject.Type, path modelsPath: String) { self.className = className self.path = modelsPath } func serialize(jsonDictionary: NSDictionary) -> AnyObject? { var response: NSMutableDictionary = CFPropertyListCreateDeepCopy(kCFAllocatorDefault, self.removeNullValues(jsonDictionary), 1) as NSMutableDictionary var values: AnyObject! if self.path == "" { values = jsonDictionary } else { values = jsonDictionary.valueForKeyPath(self.path) } if values is Array<NSDictionary> { var models: Array<BaseModel> = Array<BaseModel>() for value in values as [NSDictionary] { var model = self.className() as BaseModel model.setAttributes(value as [String: AnyObject]) models.append(model) } response.setValue(models, forKeyPath: self.path) } else if values is Dictionary<String, AnyObject> { var model = self.className() as BaseModel model.setAttributes(values as [String: AnyObject]) response.setValue(model, forKeyPath: self.path) } return response } func removeNullValues(JSONObject: AnyObject) -> AnyObject { if JSONObject.isKindOfClass(NSArray.self) { let mutableArray = NSMutableArray(capacity: (JSONObject as NSArray).count) for value in (JSONObject as NSArray) { mutableArray.addObject(self.removeNullValues(value)) } return mutableArray.copy() as NSArray } else if JSONObject.isKindOfClass(NSDictionary.self) { let mutableDictionary = (JSONObject as NSDictionary).mutableCopy() as NSMutableDictionary for (key, value) in (JSONObject as NSDictionary) { if value.isKindOfClass(NSNull.self) { mutableDictionary.removeObjectForKey(key) } else if value.isKindOfClass(NSArray.self) || value.isKindOfClass(NSDictionary.self) { mutableDictionary.setObject(self.removeNullValues(value), forKey: (key as String)) } } return mutableDictionary.copy() as NSDictionary } return JSONObject } }
mit
7500d10ecf91ec59e56ff528b26605ce
39.0625
158
0.626609
5.105578
false
false
false
false
gcrabtree/react-native-socketio
ios/RNSwiftSocketIO/SocketIOClient/SocketEngine.swift
1
18586
// // SocketEngine.swift // Socket.IO-Client-Swift // // Created by Erik Little on 3/3/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket { public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL) public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL) public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL) public var connectParams: [String: AnyObject]? { didSet { (urlPolling, urlWebSocket) = createURLs() } } public var postWait = [String]() public var waitingForPoll = false public var waitingForPost = false public private(set) var closed = false public private(set) var connected = false public private(set) var cookies: [NSHTTPCookie]? public private(set) var doubleEncodeUTF8 = true public private(set) var extraHeaders: [String: String]? public private(set) var fastUpgrade = false public private(set) var forcePolling = false public private(set) var forceWebsockets = false public private(set) var invalidated = false public private(set) var polling = true public private(set) var probing = false public private(set) var session: NSURLSession? public private(set) var sid = "" public private(set) var socketPath = "/engine.io/" public private(set) var urlPolling = NSURL() public private(set) var urlWebSocket = NSURL() public private(set) var websocket = false public private(set) var ws: WebSocket? public weak var client: SocketEngineClient? private weak var sessionDelegate: NSURLSessionDelegate? private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData]) private typealias ProbeWaitQueue = [Probe] private let logType = "SocketEngine" private let url: NSURL private var pingInterval: Double? private var pingTimeout = 0.0 { didSet { pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25)) } } private var pongsMissed = 0 private var pongsMissedMax = 0 private var probeWait = ProbeWaitQueue() private var secure = false private var selfSigned = false private var voipEnabled = false public init(client: SocketEngineClient, url: NSURL, options: Set<SocketIOClientOption>) { self.client = client self.url = url for option in options { switch option { case let .ConnectParams(params): connectParams = params case let .Cookies(cookies): self.cookies = cookies case let .DoubleEncodeUTF8(encode): doubleEncodeUTF8 = encode case let .ExtraHeaders(headers): extraHeaders = headers case let .SessionDelegate(delegate): sessionDelegate = delegate case let .ForcePolling(force): forcePolling = force case let .ForceWebsockets(force): forceWebsockets = force case let .Path(path): socketPath = path case let .VoipEnabled(enable): voipEnabled = enable case let .Secure(secure): self.secure = secure case let .SelfSigned(selfSigned): self.selfSigned = selfSigned default: continue } } super.init() (urlPolling, urlWebSocket) = createURLs() } public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) { self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? []) } deinit { DefaultSocketLogger.Logger.log("Engine is being released", type: logType) closed = true stopPolling() } private func checkAndHandleEngineError(msg: String) { guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return } do { if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? NSDictionary { guard let error = dict["message"] as? String else { return } /* 0: Unknown transport 1: Unknown sid 2: Bad handshake request 3: Bad request */ didError(error) } } catch { didError("Got unknown error from server \(msg)") } } private func checkIfMessageIsBase64Binary(message: String) -> Bool { if message.hasPrefix("b4") { // binary in base64 string let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex] if let data = NSData(base64EncodedString: noPrefix, options: .IgnoreUnknownCharacters) { client?.parseEngineBinaryData(data) } return true } else { return false } } /// Starts the connection to the server public func connect() { if connected { DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType) disconnect("reconnect") } DefaultSocketLogger.Logger.log("Starting engine", type: logType) DefaultSocketLogger.Logger.log("Handshaking", type: logType) resetEngine() if forceWebsockets { polling = false websocket = true createWebsocketAndConnect() return } let reqPolling = NSMutableURLRequest(URL: urlPolling) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) reqPolling.allHTTPHeaderFields = headers } if let extraHeaders = extraHeaders { for (headerName, value) in extraHeaders { reqPolling.setValue(value, forHTTPHeaderField: headerName) } } dispatch_async(emitQueue) { self.doLongPoll(reqPolling) } } private func createURLs() -> (NSURL, NSURL) { if client == nil { return (NSURL(), NSURL()) } let urlPolling = NSURLComponents(string: url.absoluteString)! let urlWebSocket = NSURLComponents(string: url.absoluteString)! var queryString = "" urlWebSocket.path = socketPath urlPolling.path = socketPath if secure { urlPolling.scheme = "https" urlWebSocket.scheme = "wss" } else { urlPolling.scheme = "http" urlWebSocket.scheme = "ws" } if connectParams != nil { for (key, value) in connectParams! { let keyEsc = key.urlEncode()! let valueEsc = "\(value)".urlEncode()! queryString += "&\(keyEsc)=\(valueEsc)" } } urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString return (urlPolling.URL!, urlWebSocket.URL!) } private func createWebsocketAndConnect() { ws = WebSocket(url: urlWebSocketWithSid) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) for (key, value) in headers { ws?.headers[key] = value } } if extraHeaders != nil { for (headerName, value) in extraHeaders! { ws?.headers[headerName] = value } } ws?.queue = handleQueue ws?.voipEnabled = voipEnabled ws?.delegate = self ws?.selfSignedSSL = selfSigned ws?.connect() } public func didError(error: String) { DefaultSocketLogger.Logger.error(error, type: logType) client?.engineDidError(error) disconnect(error) } public func disconnect(reason: String) { func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) { sid = "" closed = true invalidated = true connected = false ws?.disconnect() stopPolling() client?.engineDidClose(reason) } DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType) if closed { client?.engineDidClose(reason) return } if websocket { sendWebSocketMessage("", withType: .Close, withData: []) postSendClose(nil, nil, nil) } else { // We need to take special care when we're polling that we send it ASAP // Also make sure we're on the emitQueue since we're touching postWait dispatch_sync(emitQueue) { self.postWait.append(String(SocketEnginePacketType.Close.rawValue)) let req = self.createRequestForPostWithPostWait() self.doRequest(req, withCallback: postSendClose) } } } public func doFastUpgrade() { if waitingForPoll { DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," + "we'll probably disconnect soon. You should report this.", type: logType) } sendWebSocketMessage("", withType: .Upgrade, withData: []) websocket = true polling = false fastUpgrade = false probing = false flushProbeWait() } private func flushProbeWait() { DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType) dispatch_async(emitQueue) { for waiter in self.probeWait { self.write(waiter.msg, withType: waiter.type, withData: waiter.data) } self.probeWait.removeAll(keepCapacity: false) if self.postWait.count != 0 { self.flushWaitingForPostToWebSocket() } } } // We had packets waiting for send when we upgraded // Send them raw public func flushWaitingForPostToWebSocket() { guard let ws = self.ws else { return } for msg in postWait { ws.writeString(fixDoubleUTF8(msg)) } postWait.removeAll(keepCapacity: true) } private func handleClose(reason: String) { client?.engineDidClose(reason) } private func handleMessage(message: String) { client?.parseEngineMessage(message) } private func handleNOOP() { doPoll() } private func handleOpen(openData: String) { let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! do { let json = try NSJSONSerialization.JSONObjectWithData(mesData, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary if let sid = json?["sid"] as? String { let upgradeWs: Bool self.sid = sid connected = true if let upgrades = json?["upgrades"] as? [String] { upgradeWs = upgrades.contains("websocket") } else { upgradeWs = false } if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double { self.pingInterval = pingInterval / 1000.0 self.pingTimeout = pingTimeout / 1000.0 } if !forcePolling && !forceWebsockets && upgradeWs { createWebsocketAndConnect() } sendPing() if !forceWebsockets { doPoll() } client?.engineDidOpen?("Connect") } } catch { didError("Error parsing open packet") } } private func handlePong(pongMessage: String) { pongsMissed = 0 // We should upgrade if pongMessage == "3probe" { upgradeTransport() } } public func parseEngineData(data: NSData) { DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data) client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1))) } public func parseEngineMessage(message: String, fromPolling: Bool) { DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message) let reader = SocketStringReader(message: message) let fixedString: String guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else { if !checkIfMessageIsBase64Binary(message) { checkAndHandleEngineError(message) } return } if fromPolling && type != .Noop && doubleEncodeUTF8 { fixedString = fixDoubleUTF8(message) } else { fixedString = message } switch type { case .Message: handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex]) case .Noop: handleNOOP() case .Pong: handlePong(fixedString) case .Open: handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex]) case .Close: handleClose(fixedString) default: DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType) } } // Puts the engine back in its default state private func resetEngine() { closed = false connected = false fastUpgrade = false polling = true probing = false invalidated = false session = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: sessionDelegate, delegateQueue: NSOperationQueue()) sid = "" waitingForPoll = false waitingForPost = false websocket = false } private func sendPing() { if !connected { return } //Server is not responding if pongsMissed > pongsMissedMax { client?.engineDidClose("Ping timeout") return } if let pingInterval = pingInterval { pongsMissed += 1 write("", withType: .Ping, withData: []) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(pingInterval * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()) {[weak self] in self?.sendPing() } } } // Moves from long-polling to websockets private func upgradeTransport() { if ws?.isConnected ?? false { DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType) fastUpgrade = true sendPollMessage("", withType: .Noop, withData: []) // After this point, we should not send anymore polling messages } } /// Write a message, independent of transport. public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) { dispatch_async(emitQueue) { guard self.connected else { return } if self.websocket { DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendWebSocketMessage(msg, withType: type, withData: data) } else if !self.probing { DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendPollMessage(msg, withType: type, withData: data) } else { self.probeWait.append((msg, type, data)) } } } // Delegate methods public func websocketDidConnect(socket: WebSocket) { if !forceWebsockets { probing = true probeWebSocket() } else { connected = true probing = false polling = false } } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { probing = false if closed { client?.engineDidClose("Disconnect") return } if websocket { connected = false websocket = false let reason = error?.localizedDescription ?? "Socket Disconnected" if error != nil { didError(reason) } client?.engineDidClose(reason) } else { flushProbeWait() } } }
mit
c1dcd40f8b9d27c6dd94b0cf0d5716ba
32.731397
130
0.576133
5.365473
false
false
false
false
christophhagen/Signal-iOS
Signal/src/ViewControllers/Utils/MessageRecipientStatusUtils.swift
1
9557
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit import SignalMessaging @objc enum MessageRecipientStatus: Int { case uploading case sending case sent case delivered case read case failed } // Our per-recipient status messages are "biased towards success" // and reflect the most successful known state for that recipient. // // Our per-message status messages are "biased towards failure" // and reflect the least successful known state for that message. // // Why? // // When showing the per-recipient status, we want to show the message // as "read" even if delivery failed to another recipient of the same // message. // // When showing the per-message status, we want to show the message // as "failed" if delivery failed to any recipient, even if another // receipient has read the message. // // Note also that for legacy reasons we have redundant and possibly // conflicting state. Examples: // // * We could have an entry in the recipientReadMap for a message // that has no entries in its recipientDeliveryMap. // * We could have an entry in the recipientReadMap or recipientDeliveryMap // for a message whose status is "attempting out" or "unsent". // * We could have a message whose wasDelivered property is false but // which has entries in its recipientDeliveryMap or recipientReadMap. // * Etc. // // To resolve this ambiguity, we apply a "bias" towards success or // failure. class MessageRecipientStatusUtils: NSObject { // MARK: Initializers @available(*, unavailable, message:"do not instantiate this class.") private override init() { } // This method is per-recipient and "biased towards success". // See comments above. public class func recipientStatus(outgoingMessage: TSOutgoingMessage, recipientId: String, referenceView: UIView) -> MessageRecipientStatus { let (messageRecipientStatus, _) = recipientStatusAndStatusMessage(outgoingMessage: outgoingMessage, recipientId: recipientId, referenceView: referenceView) return messageRecipientStatus } // This method is per-recipient and "biased towards success". // See comments above. public class func statusMessage(outgoingMessage: TSOutgoingMessage, recipientId: String, referenceView: UIView) -> String { let (_, statusMessage) = recipientStatusAndStatusMessage(outgoingMessage: outgoingMessage, recipientId: recipientId, referenceView: referenceView) return statusMessage } // This method is per-recipient and "biased towards success". // See comments above. public class func recipientStatusAndStatusMessage(outgoingMessage: TSOutgoingMessage, recipientId: String, referenceView: UIView) -> (MessageRecipientStatus, String) { // Legacy messages don't have "recipient read" state or "per-recipient delivery" state, // so we fall back to `TSOutgoingMessageState` which is not per-recipient and therefore // might be misleading. let recipientReadMap = outgoingMessage.recipientReadMap if let readTimestamp = recipientReadMap[recipientId] { assert(outgoingMessage.messageState == .sentToService) let statusMessage = NSLocalizedString("MESSAGE_STATUS_READ", comment:"message footer for read messages").rtlSafeAppend(" ", referenceView:referenceView) .rtlSafeAppend( DateUtil.formatPastTimestampRelativeToNow(readTimestamp.uint64Value), referenceView:referenceView) return (.read, statusMessage) } let recipientDeliveryMap = outgoingMessage.recipientDeliveryMap if let deliveryTimestamp = recipientDeliveryMap[recipientId] { assert(outgoingMessage.messageState == .sentToService) let statusMessage = NSLocalizedString("MESSAGE_STATUS_DELIVERED", comment:"message status for message delivered to their recipient.").rtlSafeAppend(" ", referenceView:referenceView) .rtlSafeAppend( DateUtil.formatPastTimestampRelativeToNow(deliveryTimestamp.uint64Value), referenceView:referenceView) return (.delivered, statusMessage) } if outgoingMessage.wasDelivered { let statusMessage = NSLocalizedString("MESSAGE_STATUS_DELIVERED", comment:"message status for message delivered to their recipient.") return (.delivered, statusMessage) } if outgoingMessage.messageState == .unsent { let statusMessage = NSLocalizedString("MESSAGE_STATUS_FAILED", comment:"message footer for failed messages") return (.failed, statusMessage) } else if outgoingMessage.messageState == .sentToService || outgoingMessage.wasSent(toRecipient:recipientId) { let statusMessage = NSLocalizedString("MESSAGE_STATUS_SENT", comment:"message footer for sent messages") return (.sent, statusMessage) } else if outgoingMessage.hasAttachments() { assert(outgoingMessage.messageState == .attemptingOut) let statusMessage = NSLocalizedString("MESSAGE_STATUS_UPLOADING", comment:"message footer while attachment is uploading") return (.uploading, statusMessage) } else { assert(outgoingMessage.messageState == .attemptingOut) let statusMessage = NSLocalizedString("MESSAGE_STATUS_SENDING", comment:"message status while message is sending.") return (.sending, statusMessage) } } // This method is per-message and "biased towards failure". // See comments above. public class func statusMessage(outgoingMessage: TSOutgoingMessage, referenceView: UIView) -> String { switch outgoingMessage.messageState { case .unsent: return NSLocalizedString("MESSAGE_STATUS_FAILED", comment:"message footer for failed messages") case .attemptingOut: if outgoingMessage.hasAttachments() { return NSLocalizedString("MESSAGE_STATUS_UPLOADING", comment:"message footer while attachment is uploading") } else { return NSLocalizedString("MESSAGE_STATUS_SENDING", comment:"message status while message is sending.") } case .sentToService: let recipientReadMap = outgoingMessage.recipientReadMap if recipientReadMap.count > 0 { return NSLocalizedString("MESSAGE_STATUS_READ", comment:"message footer for read messages") } let recipientDeliveryMap = outgoingMessage.recipientDeliveryMap if recipientDeliveryMap.count > 0 { return NSLocalizedString("MESSAGE_STATUS_DELIVERED", comment:"message status for message delivered to their recipient.") } if outgoingMessage.wasDelivered { return NSLocalizedString("MESSAGE_STATUS_DELIVERED", comment:"message status for message delivered to their recipient.") } return NSLocalizedString("MESSAGE_STATUS_SENT", comment:"message footer for sent messages") default: owsFail("Message has unexpected status: \(outgoingMessage.messageState).") return NSLocalizedString("MESSAGE_STATUS_SENT", comment:"message footer for sent messages") } } // This method is per-message and "biased towards failure". // See comments above. public class func recipientStatus(outgoingMessage: TSOutgoingMessage) -> MessageRecipientStatus { switch outgoingMessage.messageState { case .unsent: return .failed case .attemptingOut: if outgoingMessage.hasAttachments() { return .uploading } else { return .sending } case .sentToService: let recipientReadMap = outgoingMessage.recipientReadMap if recipientReadMap.count > 0 { return .read } let recipientDeliveryMap = outgoingMessage.recipientDeliveryMap if recipientDeliveryMap.count > 0 { return .delivered } if outgoingMessage.wasDelivered { return .delivered } return .sent default: owsFail("Message has unexpected status: \(outgoingMessage.messageState).") return .sent } } }
gpl-3.0
c243fe8da62e2e6158ae96b07222999c
44.509524
165
0.604478
6.36285
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Services/APIs/Models/ScanResult.swift
2
1404
// // Scan.swift // SmartReceipts // // Created by Bogdan Evsenev on 19/11/2018. // Copyright © 2017 Will Baumann. All rights reserved. // import UIKit class ScanResult { private(set) var recognition: Recognition? private(set) var filepath: URL! init(recognition: Recognition? = nil, image: UIImage) { self.recognition = recognition self.filepath = cache(image: image) } init(recognition: Recognition? = nil, filepath: URL) { self.recognition = recognition self.filepath = filepath } private func cache(image: UIImage) -> URL { let imgData = image.jpegData(compressionQuality: kImageCompression)! try? imgData.write(to: ReceiptDocument.imgTempURL) return ReceiptDocument.imgTempURL } } extension ScanResult: Equatable { static func ==(lhs: ScanResult, rhs: ScanResult) -> Bool { if lhs === rhs { return true } return lhs.filepath == rhs.filepath && lhs.recognition?.createdAt == rhs.recognition?.createdAt && lhs.recognition?.id == rhs.recognition?.id && lhs.recognition?.s3path == rhs.recognition?.s3path && lhs.recognition?.status == rhs.recognition?.status && lhs.recognition?.result.amount == rhs.recognition?.result.amount && lhs.recognition?.result.tax == rhs.recognition?.result.tax } }
agpl-3.0
0e351ce4ce9e29946537c9207cecb13f
29.5
79
0.63578
4.316923
false
false
false
false
tapglue/elements-ios
Pod/Classes/views/LikeEventCell.swift
1
1886
// // LikeEventCell.swift // Tapglue Elements // // Created by John Nilsen on 14/03/16. // Copyright (c) 2015 Tapglue (https://www.tapglue.com/). All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Tapglue class LikeEventCell: UITableViewCell { @IBOutlet weak var likeEventImage: UIImageView! @IBOutlet weak var likeEventLabel: UILabel! var event: TGEvent? { didSet { if let event = event { let userNameAttributes = [NSFontAttributeName : UIFont.boldSystemFontOfSize(16)] let likeEventText = NSMutableAttributedString(string:event.user.firstName + " " + event.user.lastName, attributes:userNameAttributes) likeEventText.appendAttributedString(NSMutableAttributedString(string: " liked ")) let authorName = event.post.user.firstName + " " + event.post.user.lastName likeEventText.appendAttributedString(NSMutableAttributedString(string:authorName, attributes:userNameAttributes)) likeEventText.appendAttributedString(NSMutableAttributedString(string: "'s post")) likeEventLabel.attributedText = likeEventText user = event.user likeEventImage.setUserPicture(event.post.user) } } } private var user: TGUser? }
mit
8b60962c6f6d9671db18b6eeca2c5523
40.911111
149
0.687169
4.715
false
false
false
false
codeOfRobin/eSubziiOS
eSubzi/OrderViewController.swift
1
2593
// // OrderViewController.swift // eSubzi // // Created by Robin Malhotra on 04/04/16. // Copyright © 2016 Robin Malhotra. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class OrderViewController: UIViewController { @IBOutlet weak var totalPrice: UILabel! @IBOutlet weak var currentStatusLabel: UILabel! @IBOutlet weak var tableView: UITableView! var products = [] override func viewDidLoad() { super.viewDidLoad() let defaults = NSUserDefaults.standardUserDefaults() let token = defaults.valueForKey("token") as! String let headers = [ "x-access-token": token, "Content-Type": "application/x-www-form-urlencoded" ] Alamofire.request(.POST, API().fetchOrdersURL, headers:headers,parameters:["usertype":"Customer"] ).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) sharedCurrentOrder.currentOrderState = orderState.OrderReceived // self.currentStatusLabel.text = "Current Status : \(json["Orders"][0]["currentState"].string!)" } case .Failure(let error): print(error) } } // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { // products = Array(sharedCurrentOrder.orders.keys) } // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return 1 // } // func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return products.count // } // // func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCellWithIdentifier("cell") // // // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
f70400d221741f7e4ccf8b7b26cb2e00
32.230769
145
0.621528
4.956023
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleCell.swift
5
15003
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import UIKit; /** Bubble types */ enum BubbleType { // Outcome text bubble case TextOut // Income text bubble case TextIn // Outcome media bubble case MediaOut // Income media bubble case MediaIn // Service bubbl case Service } /** Root class for bubble layouter. Used for preprocessing bubble layout in background. */ protocol AABubbleLayouter { func isSuitable(message: ACMessage) -> Bool func buildLayout(peer: ACPeer, message: ACMessage) -> CellLayout func cellClass() -> AnyClass } // Extension for automatically building reuse ids extension AABubbleLayouter { var reuseId: String { get { return "\(self.dynamicType)" } } } /** Root class for bubble cells */ class AABubbleCell: UICollectionViewCell { // MARK: - // MARK: Private static vars static let bubbleContentTop: CGFloat = 6 static let bubbleContentBottom: CGFloat = 6 static let bubbleTop: CGFloat = 3 static let bubbleTopCompact: CGFloat = 1 static let bubbleBottom: CGFloat = 3 static let bubbleBottomCompact: CGFloat = 1 static let avatarPadding: CGFloat = 39 static let dateSize: CGFloat = 30 static let newMessageSize: CGFloat = 30 // Cached bubble images private static var cachedOutTextBg:UIImage = UIImage(named: "BubbleOutgoingFull")!.tintImage(MainAppTheme.bubbles.textBgOut) private static var cachedOutTextBgBorder:UIImage = UIImage(named: "BubbleOutgoingFullBorder")!.tintImage(MainAppTheme.bubbles.textBgOutBorder) private static var cachedInTextBg:UIImage = UIImage(named: "BubbleIncomingFull")!.tintImage(MainAppTheme.bubbles.textBgIn) private static var cachedInTextBgBorder:UIImage = UIImage(named: "BubbleIncomingFullBorder")!.tintImage(MainAppTheme.bubbles.textBgInBorder) private static var cachedOutTextCompactBg:UIImage = UIImage(named: "BubbleOutgoingPartial")!.tintImage(MainAppTheme.bubbles.textBgOut) private static var cachedOutTextCompactBgBorder:UIImage = UIImage(named: "BubbleOutgoingPartialBorder")!.tintImage(MainAppTheme.bubbles.textBgOutBorder) private static var cachedInTextCompactBg:UIImage = UIImage(named: "BubbleIncomingPartial")!.tintImage(MainAppTheme.bubbles.textBgIn) private static var cachedInTextCompactBgBorder:UIImage = UIImage(named: "BubbleIncomingPartialBorder")!.tintImage(MainAppTheme.bubbles.textBgInBorder) private static let cachedOutMediaBg:UIImage = UIImage(named: "BubbleOutgoingPartial")!.tintImage(MainAppTheme.bubbles.mediaBgOut) private static var cachedOutMediaBgBorder:UIImage = UIImage(named: "BubbleIncomingPartialBorder")!.tintImage(MainAppTheme.bubbles.mediaBgInBorder) private static var cachedInMediaBg:UIImage? = nil; private static var cachedInMediaBgBorder:UIImage? = nil; private static var cachedServiceBg:UIImage = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) private static var dateBgImage = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) // MARK: - // MARK: Public vars // Views let mainView = UIView() let avatarView = AvatarView(frameSize: 39) var avatarAdded: Bool = false let bubble = UIImageView() let bubbleBorder = UIImageView() private let dateText = UILabel() private let dateBg = UIImageView() private let newMessage = UILabel() // Layout var contentInsets : UIEdgeInsets = UIEdgeInsets() var bubbleInsets : UIEdgeInsets = UIEdgeInsets() var fullContentInsets : UIEdgeInsets { get { return UIEdgeInsets( top: contentInsets.top + bubbleInsets.top + (isShowDate ? AABubbleCell.dateSize : 0) + (isShowNewMessages ? AABubbleCell.newMessageSize : 0), left: contentInsets.left + bubbleInsets.left + (isGroup && !isOut ? AABubbleCell.avatarPadding : 0), bottom: contentInsets.bottom + bubbleInsets.bottom, right: contentInsets.right + bubbleInsets.right) } } var needLayout: Bool = true let groupContentInsetY = 20.0 let groupContentInsetX = 40.0 var bubbleVerticalSpacing: CGFloat = 6.0 let bubblePadding: CGFloat = 6; let bubbleMediaPadding: CGFloat = 10; // Binded data var peer: ACPeer! var controller: ConversationBaseViewController! var isGroup: Bool = false var isFullSize: Bool! var bindedSetting: CellSetting? var bindedMessage: ACMessage? = nil var bubbleType:BubbleType? = nil var isOut: Bool = false var isShowDate: Bool = false var isShowNewMessages: Bool = false // MARK: - // MARK: Constructors init(frame: CGRect, isFullSize: Bool) { super.init(frame: frame) self.isFullSize = isFullSize dateBg.image = AABubbleCell.dateBgImage dateText.font = UIFont.mediumSystemFontOfSize(12) dateText.textColor = UIColor.whiteColor() dateText.contentMode = UIViewContentMode.Center dateText.textAlignment = NSTextAlignment.Center newMessage.font = UIFont.mediumSystemFontOfSize(14) newMessage.textColor = UIColor.whiteColor() newMessage.contentMode = UIViewContentMode.Center newMessage.textAlignment = NSTextAlignment.Center newMessage.backgroundColor = UIColor.alphaBlack(0.3) newMessage.text = "New Messages" // bubble.userInteractionEnabled = true mainView.transform = CGAffineTransformMake(1, 0, 0, -1, 0, 0) mainView.addSubview(bubble) mainView.addSubview(bubbleBorder) mainView.addSubview(newMessage) mainView.addSubview(dateBg) mainView.addSubview(dateText) contentView.addSubview(mainView) avatarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "avatarDidTap")) avatarView.userInteractionEnabled = true backgroundColor = UIColor.clearColor() // Speed up animations self.layer.speed = 1.5 self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setConfig(peer: ACPeer, controller: ConversationBaseViewController) { self.peer = peer self.controller = controller if (peer.getPeerType().ordinal() == jint(ACPeerType.GROUP.rawValue) && !isFullSize) { self.isGroup = true } } override func canBecomeFirstResponder() -> Bool { return false } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "delete:" { return true } return false } override func delete(sender: AnyObject?) { let rids = IOSLongArray(length: 1) rids.replaceLongAtIndex(0, withLong: bindedMessage!.rid) Actor.deleteMessagesWithPeer(self.peer, withRids: rids) } func avatarDidTap() { if bindedMessage != nil { controller.onBubbleAvatarTap(self.avatarView, uid: bindedMessage!.senderId) } } func performBind(message: ACMessage, setting: CellSetting, isShowNewMessages: Bool, layout: CellLayout) { self.clipsToBounds = false self.contentView.clipsToBounds = false var reuse = false if (bindedMessage != nil && bindedMessage?.rid == message.rid) { reuse = true } isOut = message.senderId == Actor.myUid(); bindedMessage = message self.isShowNewMessages = isShowNewMessages if (!reuse) { if (!isFullSize) { if (!isOut && isGroup) { if let user = Actor.getUserWithUid(message.senderId) { let avatar: ACAvatar? = user.getAvatarModel().get() let name = user.getNameModel().get() avatarView.bind(name, id: user.getId(), avatar: avatar) } if !avatarAdded { mainView.addSubview(avatarView) avatarAdded = true } } else { if avatarAdded { avatarView.removeFromSuperview() avatarAdded = false } } } } self.isShowDate = setting.showDate if (isShowDate) { self.dateText.text = Actor.getFormatter().formatDate(message.date) } self.bindedSetting = setting bind(message, reuse: reuse, cellLayout: layout, setting: setting) if (!reuse) { needLayout = true super.setNeedsLayout() } } func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) { fatalError("bind(message:) has not been implemented") } func bindBubbleType(type: BubbleType, isCompact: Bool) { self.bubbleType = type // Update Bubble background images switch(type) { case BubbleType.TextIn: if (isCompact) { bubble.image = AABubbleCell.cachedInTextCompactBg bubbleBorder.image = AABubbleCell.cachedInTextCompactBgBorder } else { bubble.image = AABubbleCell.cachedInTextBg bubbleBorder.image = AABubbleCell.cachedInTextBgBorder } break case BubbleType.TextOut: if (isCompact) { bubble.image = AABubbleCell.cachedOutTextCompactBg bubbleBorder.image = AABubbleCell.cachedOutTextCompactBgBorder } else { bubble.image = AABubbleCell.cachedOutTextBg bubbleBorder.image = AABubbleCell.cachedOutTextBgBorder } break case BubbleType.MediaIn: bubble.image = AABubbleCell.cachedOutMediaBg bubbleBorder.image = AABubbleCell.cachedOutMediaBgBorder break case BubbleType.MediaOut: bubble.image = AABubbleCell.cachedOutMediaBg bubbleBorder.image = AABubbleCell.cachedOutMediaBgBorder break case BubbleType.Service: bubble.image = AABubbleCell.cachedServiceBg bubbleBorder.image = nil break } } // MARK: - // MARK: Layout override func layoutSubviews() { super.layoutSubviews() mainView.frame = CGRectMake(0, 0, contentView.bounds.width, contentView.bounds.height) // if (!needLayout) { // return // } // needLayout = false UIView.performWithoutAnimation { () -> Void in let endPadding: CGFloat = 32 let startPadding: CGFloat = (!self.isOut && self.isGroup) ? AABubbleCell.avatarPadding : 0 let cellMaxWidth = self.contentView.frame.size.width - endPadding - startPadding self.layoutContent(cellMaxWidth, offsetX: startPadding) self.layoutAnchor() if (!self.isOut && self.isGroup && !self.isFullSize) { self.layoutAvatar() } } } func layoutAnchor() { if (isShowDate) { dateText.frame = CGRectMake(0, 0, 1000, 1000) dateText.sizeToFit() dateText.frame = CGRectMake( (self.contentView.frame.size.width-dateText.frame.width)/2, 8, dateText.frame.width, 18) dateBg.frame = CGRectMake(dateText.frame.minX - 8, dateText.frame.minY, dateText.frame.width + 16, 18) dateText.hidden = false dateBg.hidden = false } else { dateText.hidden = true dateBg.hidden = true } if (isShowNewMessages) { var top = CGFloat(0) if (isShowDate) { top += AABubbleCell.dateSize } newMessage.hidden = false newMessage.frame = CGRectMake(0, top + CGFloat(2), self.contentView.frame.width, AABubbleCell.newMessageSize - CGFloat(4)) } else { newMessage.hidden = true } } func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { } func layoutAvatar() { let avatarSize = CGFloat(self.avatarView.frameSize) avatarView.frame = CGRect(x: 5 + (isIPad ? 16 : 0), y: self.contentView.frame.size.height - avatarSize - 2 - bubbleInsets.bottom, width: avatarSize, height: avatarSize) } // Need to be called in child cells func layoutBubble(contentWidth: CGFloat, contentHeight: CGFloat) { let fullWidth = contentView.bounds.width let bubbleW = contentWidth + contentInsets.left + contentInsets.right let bubbleH = contentHeight + contentInsets.top + contentInsets.bottom var topOffset = CGFloat(0) if (isShowDate) { topOffset += AABubbleCell.dateSize } if (isShowNewMessages) { topOffset += AABubbleCell.newMessageSize } var bubbleFrame : CGRect! if (!isFullSize) { if (isOut) { bubbleFrame = CGRect( x: fullWidth - contentWidth - contentInsets.left - contentInsets.right - bubbleInsets.right, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } else { let padding : CGFloat = isGroup ? AABubbleCell.avatarPadding : 0 bubbleFrame = CGRect( x: bubbleInsets.left + padding, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } } else { bubbleFrame = CGRect( x: (fullWidth - contentWidth - contentInsets.left - contentInsets.right)/2, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } bubble.frame = bubbleFrame bubbleBorder.frame = bubbleFrame } func layoutBubble(frame: CGRect) { bubble.frame = frame bubbleBorder.frame = frame } override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { return layoutAttributes } }
mit
ccd2ddeb10f4ee329657ad389689850d
35.417476
176
0.612677
5.350571
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Geometry/Buffer list/BufferListViewController.swift
1
12060
// Copyright 2020 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class BufferListViewController: UIViewController { // MARK: Storyboard views /// The undo button. @IBOutlet weak var undoBarButtonItem: UIBarButtonItem! /// The clear button. @IBOutlet weak var clearBarButtonItem: UIBarButtonItem! /// A label to display status message. @IBOutlet weak var statusLabel: UILabel! /// A switch to enable "union" for buffer operation. @IBOutlet weak var isUnionSwitch: UISwitch! /// The map view managed by the view controller. @IBOutlet weak var mapView: AGSMapView! { didSet { mapView.map = makeMap(imageLayer: mapImageLayer) // Create and add graphics overlays. // An overlay to display the boundary. let boundaryGraphicsOverlay = makeBoundaryGraphicsOverlay(boundaryGeometry: boundaryPolygon) bufferGraphicsOverlay = makeBufferGraphicsOverlay() tappedLocationsGraphicsOverlay = makeTappedLocationsGraphicsOverlay() mapView.graphicsOverlays.addObjects(from: [boundaryGraphicsOverlay, bufferGraphicsOverlay!, tappedLocationsGraphicsOverlay!]) mapView.touchDelegate = self } } // MARK: Instance properties /// An image layer as the base layer of the map. let mapImageLayer = AGSArcGISMapImageLayer(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer")!) /// A polygon that represents the valid area of use for the spatial reference. let boundaryPolygon: AGSPolygon = { let boundaryPoints = [ AGSPoint(x: -103.070, y: 31.720, spatialReference: .wgs84()), AGSPoint(x: -103.070, y: 34.580, spatialReference: .wgs84()), AGSPoint(x: -94.000, y: 34.580, spatialReference: .wgs84()), AGSPoint(x: -94.00, y: 31.720, spatialReference: .wgs84()) ] let polygon = AGSPolygon(points: boundaryPoints) let statePlaneNorthCentralTexas = AGSSpatialReference(wkid: 32038)! return AGSGeometryEngine.projectGeometry(polygon, to: statePlaneNorthCentralTexas) as! AGSPolygon }() /// An overlay to display buffers graphics. var bufferGraphicsOverlay: AGSGraphicsOverlay! /// An overlay to display tapped locations with red circle symbols. var tappedLocationsGraphicsOverlay: AGSGraphicsOverlay! /// An array of tapped points and buffer radii (in US feet) tuple. var tappedPointsAndRadii = [(point: AGSPoint, radius: Double)]() { didSet { let newValueIsEmpty = tappedPointsAndRadii.isEmpty if newValueIsEmpty != oldValue.isEmpty { // Only set button states when the emptiness of the array has changed. undoBarButtonItem.isEnabled = !newValueIsEmpty clearBarButtonItem.isEnabled = !newValueIsEmpty } // Redraw the buffers. drawBuffers() } } /// A formatter for the output distance string. let distanceFormatter: MeasurementFormatter = { let formatter = MeasurementFormatter() formatter.numberFormatter.maximumFractionDigits = 0 return formatter }() // MARK: Instance methods /// Creates a map with an image base layer. /// /// - Parameter imageLayer: An `AGSArcGISMapImageLayer` object as the base layer of the map. /// - Returns: A new `AGSMap` object. func makeMap(imageLayer: AGSArcGISMapImageLayer) -> AGSMap { // The spatial reference for this sample. let statePlaneNorthCentralTexas = AGSSpatialReference(wkid: 32038)! let map = AGSMap(spatialReference: statePlaneNorthCentralTexas) map.basemap.baseLayers.add(imageLayer) return map } /// Creates a graphics overlay for the boundary polygon graphics. /// /// - Parameter boundaryGeometry: The geometry of bounday graphics. /// - Returns: A new `AGSGraphicsOverlay` object. func makeBoundaryGraphicsOverlay(boundaryGeometry: AGSGeometry) -> AGSGraphicsOverlay { let overlay = AGSGraphicsOverlay() let lineSymbol = AGSSimpleLineSymbol(style: .dash, color: .red, width: 5) let boundaryGraphic = AGSGraphic(geometry: boundaryGeometry, symbol: lineSymbol) overlay.graphics.add(boundaryGraphic) return overlay } /// Creates a graphics overlay for the buffer graphics. func makeBufferGraphicsOverlay() -> AGSGraphicsOverlay { let overlay = AGSGraphicsOverlay() let bufferPolygonOutlineSymbol = AGSSimpleLineSymbol(style: .solid, color: .systemGreen, width: 3) let bufferPolygonFillSymbol = AGSSimpleFillSymbol(style: .solid, color: UIColor.yellow.withAlphaComponent(0.6), outline: bufferPolygonOutlineSymbol) overlay.renderer = AGSSimpleRenderer(symbol: bufferPolygonFillSymbol) return overlay } /// Creates a graphics overlay for the tapped location graphics. func makeTappedLocationsGraphicsOverlay() -> AGSGraphicsOverlay { let overlay = AGSGraphicsOverlay() let circleSymbol = AGSSimpleMarkerSymbol(style: .circle, color: .red, size: 10) overlay.renderer = AGSSimpleRenderer(symbol: circleSymbol) return overlay } // MARK: Actions @IBAction func undoButtonTapped(_ sender: UIBarButtonItem) { // Remove the last pair of tapped point and radius. tappedPointsAndRadii.removeLast() } @IBAction func isUnionSwitchValueChanged(_ sender: UISwitch) { // Redraw buffers when the union switch's value is changed. drawBuffers() } @IBAction func clearButtonTapped(_ sender: UIBarButtonItem) { bufferGraphicsOverlay.graphics.removeAllObjects() tappedLocationsGraphicsOverlay.graphics.removeAllObjects() tappedPointsAndRadii.removeAll() } // MARK: UI func setStatus(message: String) { statusLabel.text = message } func drawBuffers() { // Clear existing buffers graphics before drawing. bufferGraphicsOverlay.graphics.removeAllObjects() tappedLocationsGraphicsOverlay.graphics.removeAllObjects() guard !tappedPointsAndRadii.isEmpty else { setStatus(message: "Tap on the map to add buffers.") return } // Reduce the tuples into points and radii arrays. let (points, radii) = tappedPointsAndRadii.reduce(into: ([AGSPoint](), [NSNumber]())) { (result, pointAndRadius) in result.0.append(pointAndRadius.point) result.1.append(pointAndRadius.radius as NSNumber) } // Create the buffers. // Notice: the radius distances has the same unit of the map's spatial reference's unit. // In this case, the statePlaneNorthCentralTexas spatial reference uses US feet. if let bufferPolygon = AGSGeometryEngine.bufferGeometries(points, distances: radii, unionResults: isUnionSwitch.isOn) { // Add graphics symbolizing the tap point. tappedLocationsGraphicsOverlay.graphics.addObjects(from: points.map { AGSGraphic(geometry: $0, symbol: nil) }) // Add graphics of the buffer polygons. bufferGraphicsOverlay.graphics.addObjects(from: bufferPolygon.map { AGSGraphic(geometry: $0, symbol: nil) }) setStatus(message: "Buffers created.") } } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["BufferListViewController"] // Load the map image layer. mapImageLayer.load { [weak self] (error) in guard let self = self else { return } if let error = error { self.presentAlert(error: error) self.setStatus(message: "Failed to load basemap.") } else { self.mapView.setViewpoint(AGSViewpoint(targetExtent: self.boundaryPolygon.extent), completion: nil) self.setStatus(message: "Tap on the map to add buffers.") } } } } // MARK: - AGSGeoViewTouchDelegate extension BufferListViewController: AGSGeoViewTouchDelegate { func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { // Only proceed when the tapped point is within the boundary. guard AGSGeometryEngine.geometry(boundaryPolygon, contains: mapPoint) else { setStatus(message: "Tap within the boundary to add buffer.") return } // Use an alert to get radius input from user. let alert = UIAlertController(title: "Provide a buffer radius between 0 and 300 \(distanceFormatter.string(from: UnitLength.miles)).", message: nil, preferredStyle: .alert) // Create an object to observe changes from the textfield. var textFieldObserver: NSObjectProtocol! // Add a textfield to get user input. alert.addTextField { textField in textField.keyboardType = .numberPad textField.placeholder = "100" } let doneAction = UIAlertAction(title: "Done", style: .default) { [weak self, unowned alert, mapPoint = mapPoint] _ in // Remove the observer after editing is complete. NotificationCenter.default.removeObserver(textFieldObserver!) guard let self = self, let text = alert.textFields?.first?.text, let radius = self.distanceFormatter.numberFormatter.number(from: text) else { return } // Update the buffer radius with the text value. let radiusInMiles = Measurement(value: radius.doubleValue, unit: UnitLength.miles) // The spatial reference in this sample uses US feet as its unit. let radiusInFeet = radiusInMiles.converted(to: .feet).value // Keep track of tapped points and their radii. self.tappedPointsAndRadii.append((point: mapPoint, radius: radiusInFeet)) } // Add an observer to ensure the user input is valid. textFieldObserver = NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nil, queue: .main, using: { [weak self, weak alert, unowned doneAction] _ in // Ensure the buffer radius input is valid, and is within the range. if let text = alert?.textFields?.first?.text, !text.isEmpty, let radius = self?.distanceFormatter.numberFormatter.number(from: text), radius.doubleValue > 0, radius.doubleValue < 300 { doneAction.isEnabled = true } else { doneAction.isEnabled = false } }) // Disable done button by default. doneAction.isEnabled = false alert.addAction(doneAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in // Remove the observer when canceled. NotificationCenter.default.removeObserver(textFieldObserver!) } alert.addAction(cancelAction) alert.preferredAction = doneAction present(alert, animated: true) } }
apache-2.0
54a424547f29f855ac71ff5f35dfe67a
45.030534
199
0.660697
5.232104
false
false
false
false
codefellows/sea-d34-iOS
Sample Code/Week 2/ImageFilters/PhotoViewController.swift
1
8812
// // PhotoViewController.swift // ImageFilters // // Created by Bradley Johnson on 4/6/15. // Copyright (c) 2015 BPJ. All rights reserved. // import UIKit import Social class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, ImageSelectedDelegate { let alertController = UIAlertController(title: "Options", message: "Choose One", preferredStyle: UIAlertControllerStyle.ActionSheet) let imageToUploadSize = CGSize(width: 400, height: 400) //MARK: CollectionView Constraints @IBOutlet weak var collectionViewBottomConstraint: NSLayoutConstraint! //MARK: ImageView Constraints @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint! var originalImageViewTopLeadingTrailingConstaint : CGFloat = 0.0 var originalImageViewBottomConstant : CGFloat = 0.0 let constraintBuffer : CGFloat = 50 let constraintAnimationDuration = 0.3 let collectionViewHeight : CGFloat = 75 let collectionViewFilterModeBottomConstant : CGFloat = 8 let thumbnailSize = CGSize(width: 75, height: 75) var filters : [(UIImage, CIContext)->(UIImage)]! var context : CIContext! //var filters = Array<(UIImage,CIContext) -> (UIImage)>() var originalThumbnail : UIImage! var currentImage : UIImage! { didSet { self.primaryImageView.image = self.currentImage self.originalThumbnail = ImageResizer.resizeImage(self.currentImage, size: self.thumbnailSize) self.collectionView.reloadData() //self.currentImage = oldValue } } //MARK: Interface Outlets @IBOutlet weak var primaryImageView: UIImageView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var photoButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.title = "Upload" if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) { self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "sharePressed") } let options = [kCIContextWorkingColorSpace : NSNull()] let eaglContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2) self.context = CIContext(EAGLContext: eaglContext, options: options) self.filters = [FilterService.sepia,FilterService.colorInvert, FilterService.instant, FilterService.chrome, FilterService.noir] self.collectionView.dataSource = self self.collectionViewBottomConstraint.constant = -self.tabBarController!.tabBar.frame.height - self.collectionView.frame.height self.originalImageViewTopLeadingTrailingConstaint = self.imageViewTopConstraint.constant self.originalImageViewBottomConstant = self.imageViewBottomConstraint.constant if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { (action) -> Void in let imagePickerController = UIImagePickerController() imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePickerController.allowsEditing = true self.presentViewController(imagePickerController, animated: true, completion: nil) imagePickerController.delegate = self //imagePickerController.mediaTypes = [UIImagePickerControllerMediaType] } self.alertController.addAction(cameraAction) } let filtersAction = UIAlertAction(title: "Filters", style: UIAlertActionStyle.Default) { [weak self] (action) -> Void in if self != nil { self!.enterFilterMode() } } self.alertController.addAction(filtersAction) let uploadAction = UIAlertAction(title: "Upload", style: UIAlertActionStyle.Default) { (action) -> Void in ParseService.uploadImage(self.primaryImageView.image!, size: self.imageToUploadSize, completionHandler: { (errorDescription) -> Void in }) } self.alertController.addAction(uploadAction) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (action) -> Void in } self.alertController.addAction(cancelAction) let galleryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default) { (action) -> Void in self.performSegueWithIdentifier("ShowGallery", sender: self) } self.alertController.addAction(galleryAction) self.currentImage = UIImage(named: "photo.jpg") // Do any additional setup after loading the view. } func enterFilterMode() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "leaveFilterMode") self.photoButton.enabled = false self.imageViewTopConstraint.constant = self.imageViewTopConstraint.constant + self.constraintBuffer self.imageViewBottomConstraint.constant = self.imageViewBottomConstraint.constant + self.constraintBuffer self.imageViewLeadingConstraint.constant = self.imageViewLeadingConstraint.constant + self.constraintBuffer self.imageViewTrailingConstraint.constant += self.constraintBuffer self.collectionViewBottomConstraint.constant = self.collectionViewFilterModeBottomConstant UIView.animateWithDuration(self.constraintAnimationDuration, animations: { () -> Void in self.view.layoutIfNeeded() }) } func leaveFilterMode() { self.navigationItem.rightBarButtonItem = nil self.photoButton.enabled = true self.imageViewTopConstraint.constant = self.originalImageViewTopLeadingTrailingConstaint self.imageViewBottomConstraint.constant = self.originalImageViewBottomConstant self.imageViewTrailingConstraint.constant = self.originalImageViewTopLeadingTrailingConstaint self.imageViewLeadingConstraint.constant = self.originalImageViewTopLeadingTrailingConstaint self.collectionViewBottomConstraint.constant = -self.tabBarController!.tabBar.frame.height - self.collectionView.frame.height UIView.animateWithDuration(self.constraintAnimationDuration, animations: { () -> Void in self.view.layoutIfNeeded() }) } @IBAction func photoButtonPressed(sender: AnyObject) { if let popoverController = self.alertController.popoverPresentationController { if let button = sender as? UIButton { popoverController.sourceView = button popoverController.sourceRect = button.bounds } } self.presentViewController(alertController, animated: true) { () -> Void in } } //MARK: //MARK: UIImagePickerControllerDelegate func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { self.currentImage = editedImage } picker.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { } //MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.filters.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! ImageCell let filter = self.filters[indexPath.row] cell.imageView.image = filter(self.originalThumbnail,self.context) return cell } //MARK: ImageSelectedDelegate func controllerDidSelectImage(image: UIImage) { self.currentImage = image } //MARK: PrepareForSegue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowGallery" { let galleryVC = segue.destinationViewController as GalleryViewController galleryVC.primaryImageViewSize = self.primaryImageView.frame.size galleryVC.delegate = self } } func sharePressed() { let composeVC = SLComposeViewController(forServiceType: SLServiceTypeTwitter) composeVC.addImage(self.currentImage) self.presentViewController(composeVC, animated: true, completion: nil) } }
mit
bbf57dc4c4120b9129927268d0278cbb
39.054545
161
0.742397
5.573688
false
false
false
false
Agarunov/FetchKit
Sources/GetDistinct.swift
1
5173
// // GetDistinct.swift // FetchKit // // Created by Anton Agarunov on 15.11.2017. // // import CoreData import Foundation open class GetDistinct<ModelType: NSManagedObject>: FetchRequest<ModelType> { public typealias Aggregation = (property: String, function: String, name: String) // MARK: - Properties /// Properties that will be used to group result open internal(set) var propertiesToGroupBy: [String]? /// Aggregation data which will be used to form aggregation expressions open internal(set) var aggregations: [Aggregation] = [] /// Predicate that will be used to filter result open internal(set) var havingPredicate: NSPredicate? // MARK: - Methods /// Sets property that will be used to group result /// /// - parameter keyPath: Property keyPath /// /// - returns: Updated `GetDistinct` instance open func group(by keyPath: String) -> Self { propertiesToGroupBy = [keyPath] return self } /// Sets properties that will be used to group result /// /// - parameter keyPaths: Property keyPaths /// /// - returns: Updated `GetDistinct` instance open func group(by keyPaths: [String]) -> Self { propertiesToGroupBy = keyPaths return self } /// Sets property that will be used to group result /// /// - parameter keyPath: Property keyPath /// /// - returns: Updated `GetDistinct` instance open func group(by keyPath: PartialKeyPath<ModelType>) -> Self { propertiesToGroupBy = [keyPath._kvcKeyPathString!] return self } /// Sets properties that will be used to group result /// /// - parameter keyPaths: Property keyPaths /// /// - returns: Updated `GetDistinct` instance open func group(by keyPaths: [PartialKeyPath<ModelType>]) -> Self { propertiesToGroupBy = keyPaths.compactMap { $0._kvcKeyPathString } return self } /// Add aggregation function and property to fetch request /// /// - parameter property: Aggregation property /// - parameter function: Aggregation function /// - parameter name: Key name which will be used in result dictionary /// /// - returns: Updated `GetDistinct` instance open func aggregate(property: String, function: String, saveAs name: String) -> Self { aggregations.append((property: property, function: function, name: name)) return self } /// Add aggregation function and keyPath to fetch request /// /// - parameter keyPath: Aggregation keyPath /// - parameter function: Aggregation function /// - parameter name: Key name which will be used in result dictionary /// /// - returns: Updated `GetDistinct` instance open func aggregate(keyPath: PartialKeyPath<ModelType>, function: String, saveAs name: String) -> Self { aggregations.append((property: keyPath._kvcKeyPathString!, function: function, name: name)) return self } /// Sets predicate that will be used to filter result /// /// - parameter predicate: Filter preficate /// /// - returns: Updated `GetDistinct` instance open func having(_ predicate: NSPredicate) -> Self { havingPredicate = predicate return self } /// Executes fetch request with selected options on given managed object context. /// Returns fetched properties and aggregation results /// /// - parameter context: Managed object context instance /// /// - returns: Fetched properties and aggregation results /// /// - throws: Core Data error if fetch fails open func execute(in context: NSManagedObjectContext) throws -> [[String: Any]] { let request: NSFetchRequest<NSDictionary> = buildFetchRequest() request.resultType = .dictionaryResultType request.returnsDistinctResults = true request.havingPredicate = havingPredicate request.propertiesToGroupBy = propertiesToGroupBy let entityDescription = NSEntityDescription.entity(forEntityName: entityName, in: context) let expressions = aggregations.compactMap { aggregation -> NSExpressionDescription? in guard let attributeDescription = entityDescription?.attributeDescription(for: aggregation.property) else { return nil } let expression = NSExpression(forFunction: aggregation.function, arguments: [NSExpression(forKeyPath: aggregation.property)]) let expressionDescription = NSExpressionDescription() expressionDescription.name = aggregation.name expressionDescription.expression = expression expressionDescription.expressionResultType = attributeDescription.attributeType return expressionDescription } if let propertiesToFetch = request.propertiesToFetch { request.propertiesToFetch = propertiesToFetch + expressions } else { request.propertiesToFetch = expressions } let result = try context.fetch(request) return result as? [[String: Any]] ?? [] } }
bsd-2-clause
08cc6a919fe34205ca39df43ca69b8b7
35.174825
118
0.662478
5.456751
false
false
false
false
saqibmk/SKStackedCardViewController
SKStackedCollectionView/ViewController.swift
1
1635
// // ViewController.swift // SKStackedCollectionView // // Created by Personal Work on 4/10/15. // Copyright (c) 2015 Saqib. All rights reserved. // import UIKit let reuseIdentifier = "cell" @IBDesignable class ViewController: SKStackedCollectionViewController { func getRandomColor() -> UIColor{ var randomRed:CGFloat = CGFloat(drand48()) var randomGreen:CGFloat = CGFloat(drand48()) var randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return 3 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SKCollectionViewCell // Configure the cell cell.layer.cornerRadius = 15; cell.label?.text = "HELLO" cell.backgroundColor = getRandomColor() return cell } }
mit
d680ee77a4b7225d849550c88cac7fdf
28.727273
139
0.668502
5.468227
false
false
false
false
mansoor92/MaksabComponents
MaksabComponents/Classes/Help/CreateIssueTemplateViewController.swift
1
3676
// // CreateIssueTemplateViewController.swift // Pods // // Created by Incubasys on 19/09/2017. // // import UIKit import StylingBoilerPlate import KMPlaceholderTextView public protocol CreateIssueDelegate{ func selectRide() func selectIssue() func seekHelp() } open class CreateIssueTemplateViewController: UIViewController, NibLoadableView, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak public var textView: KMPlaceholderTextView! @IBOutlet weak public var btnSeekHelp: UIButton! public var delegate: CreateIssueDelegate? public var showSelectRide: Bool = true @IBOutlet weak var tableViewHeight: NSLayoutConstraint! let bundle = Bundle(for: CreateIssueTemplateViewController.classForCoder()) open override func loadView() { let name = CreateIssueTemplateViewController.nibName let bundle = Bundle(for: CreateIssueTemplateViewController.classForCoder()) guard let view = bundle.loadNibNamed(name, owner: self, options: nil)?.first as? UIView else { fatalError("Nib not found.") } self.view = view } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. configView() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let index = tableView.indexPathForSelectedRow{ tableView.deselectRow(at: index, animated: false) } } func configView() { self.view.backgroundColor = UIColor.appColor(color: .Light) tableView.dataSource = self tableView.delegate = self tableView.register(SimpleTextTableViewCell.self, bundle: Bundle(for: SimpleTextTableViewCell.classForCoder())) if !showSelectRide{ tableViewHeight.constant = 50 } textView.layer.cornerRadius = 5 textView.placeholder = Bundle.localizedStringFor(key: "help-details") textView.layer.borderWidth = 1 textView.layer.borderColor = UIColor.appColor(color: .Dark).cgColor textView.textColor = UIColor.appColor(color: .DarkText) btnSeekHelp.setTitle(Bundle.localizedStringFor(key: "help-btn-seek-help"), for: .normal) } //MARK:- tableView public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if showSelectRide{ return 2 }else { return 1 } } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeCell(indexPath: indexPath) as SimpleTextTableViewCell cell.isLight = true cell.selectionStyle = .default if indexPath.row == 0 && showSelectRide{ cell.config(title: Bundle.localizedStringFor(key: "help-cell-select-ride")) }else{ cell.config(title: Bundle.localizedStringFor(key: "help-cell-select-issue")) } cell.addAccessoryView(img: UIImage.localizedImage(named: "arrow-right")) return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if showSelectRide && indexPath.row == 0{ delegate?.selectRide() }else{ delegate?.selectIssue() } } //MARK:- Seek Help @IBAction func actSeekHelp(){ delegate?.seekHelp() } }
mit
4ba220de81ad5d73456ab7f419f793a0
33.35514
125
0.662949
5.042524
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0030.xcplaygroundpage/Contents.swift
2
34458
/*: # Property Behaviors * Proposal: [SE-0030](0030-property-behavior-decls.md) * Author: [Joe Groff](https://github.com/jckarter) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Deferred** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-February/000047.html) ## Introduction There are property implementation patterns that come up repeatedly. Rather than hardcode a fixed set of patterns into the compiler, we should provide a general "property behavior" mechanism to allow these patterns to be defined as libraries. [Swift Evolution Discussion](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/003148.html)<br/> [Review](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160208/009603.html) ## Motivation We've tried to accommodate several important patterns for properties with targeted language support, but this support has been narrow in scope and utility. For instance, Swift 1 and 2 provide `lazy` properties as a primitive language feature, since lazy initialization is common and is often necessary to avoid having properties be exposed as `Optional`. Without this language support, it takes a lot of boilerplate to get the same effect: ```swift class Foo { // lazy var foo = 1738 private var _foo: Int? var foo: Int { get { if let value = _foo { return value } let initialValue = 1738 _foo = initialValue return initialValue } set { _foo = newValue } } } ``` Building `lazy` into the language has several disadvantages. It makes the language and compiler more complex and less orthogonal. It's also inflexible; there are many variations on lazy initialization that make sense, but we wouldn't want to hardcode language support for all of them. For instance, some applications may want the lazy initialization to be synchronized, but `lazy` only provides single-threaded initialization. The standard implementation of `lazy` is also problematic for value types. A `lazy` getter must be `mutating`, which means it can't be accessed from an immutable value. Inline storage is also suboptimal for many memoization tasks, since the cache cannot be reused across copies of the value. A value-oriented memoized property implementation might look very different, using a class instance to store the cached value out-of-line in order to avoid mutation of the value itself. There are important property patterns outside of lazy initialization. It often makes sense to have "delayed", once-assignable-then-immutable properties to support multi-phase initialization: ```swift class Foo { let immediatelyInitialized = "foo" var _initializedLater: String? // We want initializedLater to present like a non-optional 'let' to user code; // it can only be assigned once, and can't be accessed before being assigned. var initializedLater: String { get { return _initializedLater! } set { assert(_initializedLater == nil) _initializedLater = newValue } } } ``` Implicitly-unwrapped optionals allow this in a pinch, but give up a lot of safety compared to a non-optional 'let'. Using IUO for multi-phase initialization gives up both immutability and nil-safety. We also have other application-specific property features like `didSet`/`willSet` that add language complexity for limited functionality. Beyond what we've baked into the language already, there's a seemingly endless set of common property behaviors, including synchronized access, copying, and various kinds of proxying, all begging for language attention to eliminate their boilerplate. ## Proposed solution I suggest we allow for **property behaviors** to be implemented within the language. A `var` declaration can specify its **behaviors** in square brackets after the keyword: ```swift var [lazy] foo = 1738 ``` which implements the property `foo` in a way described by the **property behavior declaration** for `lazy`: ```swift var behavior lazy<Value>: Value { var value: Value? = nil initialValue mutating get { if let value = value { return value } let initial = initialValue value = initial return initial } set { value = newValue } } ``` Property behaviors can control the storage, initialization, and access of affected properties, obviating the need for special language support for `lazy`, observers, and other special-case property features. ## Examples Before describing the detailed design, I'll run through some examples of potential applications for behaviors. ### Lazy The current `lazy` property feature can be reimplemented as a property behavior. ```swift // Property behaviors are declared using the `var behavior` keyword cluster. public var behavior lazy<Value>: Value { // Behaviors can declare storage that backs the property. private var value: Value? // Behaviors can bind the property's initializer expression with an // `initialValue` property declaration. initialValue // Behaviors can declare initialization logic for the storage. // (Stored properties can also be initialized in-line.) init() { value = nil } // Inline initializers are also supported, so `var value: Value? = nil` // would work equivalently. // Behaviors can declare accessors that implement the property. mutating get { if let value = value { return value } let initial = initialValue value = initial return initial } set { value = newValue } } ``` Properties declared with the `lazy` behavior are backed by the `Optional`-typed storage and accessors from the behavior: ```swift var [lazy] x = 1738 // Allocates an Int? behind the scenes, inited to nil print(x) // Invokes the `lazy` getter, initializing the property x = 679 // Invokes the `lazy` setter ``` ### Delayed Initialization A property behavior can model "delayed" initialization behavior, where the DI rules for properties are enforced dynamically rather than at compile time. This can avoid the need for implicitly-unwrapped optionals in multi-phase initialization. We can implement both a mutable variant, which allows for reassignment like a `var`: ```swift public var behavior delayedMutable<Value>: Value { private var value: Value? = nil get { guard let value = value else { fatalError("property accessed before being initialized") } return value } set { value = newValue } } ``` and an immutable variant, which only allows a single initialization like a `let`: ```swift public var behavior delayedImmutable<Value>: Value { private var value: Value? = nil get { guard let value = value else { fatalError("property accessed before being initialized") } return value } // Perform an initialization, trapping if the // value is already initialized. set { if let _ = value { fatalError("property initialized twice") } value = initialValue } } ``` This enables multi-phase initialization, like this: ```swift class Foo { var [delayedImmutable] x: Int init() { // We don't know "x" yet, and we don't have to set it } func initializeX(x: Int) { self.x = x // Will crash if 'self.x' is already initialized } func getX() -> Int { return x // Will crash if 'self.x' wasn't initialized } } ``` ### Property Observers A property behavior can also approximate the built-in behavior of `didSet`/`willSet` observers, by declaring support for custom accessors: ```swift public var behavior observed<Value>: Value { initialValue var value = initialValue // A behavior can declare accessor requirements, the implementations of // which must be provided by property declarations using the behavior. // The behavior may provide a default implementation of the accessors, in // order to make them optional. // The willSet accessor, invoked before the property is updated. The // default does nothing. mutating accessor willSet(newValue: Value) { } // The didSet accessor, invoked before the property is updated. The // default does nothing. mutating accessor didSet(oldValue: Value) { } get { return value } set { willSet(newValue) let oldValue = value value = newValue didSet(oldValue) } } ``` A common complaint with `didSet`/`willSet` is that the observers fire on *every* write, not only ones that cause a real change. A behavior that supports a `didChange` accessor, which only gets invoked if the property value really changed to a value not equal to the old value, can be implemented as a new behavior: ```swift public var behavior changeObserved<Value: Equatable>: Value { initialValue var value = initialValue mutating accessor didChange(oldValue: Value) { } get { return value } set { let oldValue = value value = newValue if oldValue != newValue { didChange(oldValue) } } } ``` For example: ```swift var [changeObserved] x: Int = 1 { didChange { print("\(oldValue) => \(x)") } } x = 1 // Prints nothing x = 2 // Prints 1 => 2 ``` (Note that, like `didSet`/`willSet` today, neither behavior implementation will observe changes through class references that mutate a referenced class instance without changing the reference itself. Also, as currently proposed, behaviors would force the property to be initialized in-line, which is not acceptable for instance properties. That's a limitation that can be lifted by future extensions.) ### Synchronized Property Access Objective-C supports `atomic` properties, which take a lock on `get` and `set` to synchronize accesses to a property. This is occasionally useful, and it can be brought to Swift as a behavior. The real implementation of `atomic` properties in ObjC uses a global bank of locks, but for illustrative purposes (and to demonstrate referring to `self`) I'll use a per-object lock instead: ```swift // A class that owns a mutex that can be used to synchronize access to its // properties. public protocol Synchronizable: class { func withLock<R>(@noescape body: () -> R) -> R } // Behaviors can refer to a property's containing type using // the implicit `Self` generic parameter. Constraints can be // applied using a 'where' clause, like in an extension. public var behavior synchronized<Value where Self: Synchronizable>: Value { initialValue var value: Value = initialValue get { return self.withLock { return value } } set { self.withLock { value = newValue } } } ``` ### `NSCopying` Many Cocoa classes implement value-like objects that require explicit copying. Swift currently provides an `@NSCopying` attribute for properties to give them behavior like Objective-C's `@property(copy)`, invoking the `copy` method on new objects when the property is set. We can turn this into a behavior: ```swift public var behavior copying<Value: NSCopying>: Value { initialValue // Copy the value on initialization. var value: Value = initialValue.copy() get { return value } set { // Copy the value on reassignment. value = newValue.copy() } } ``` This is a small sampling of the possibilities of behaviors. Let's look at the proposed design in detail: ## Detailed design ### Property behavior declarations A **property behavior declaration** is introduced by the `var behavior` contextual keyword cluster. The declaration is designed to resemble the syntax of a property using the behavior: ```text property-behavior-decl ::= attribute* decl-modifier* 'var' 'behavior' identifier // behavior name generic-signature? ':' type '{' property-behavior-member-decl* '}' ``` Inside the behavior declaration, standard initializer, property, method, and nested type declarations are allowed, as are **core accessor** declarations —`get` and `set`. **Accessor requirement declarations** and **initial value requirement declarations** are also recognized contextually within the declaration: ```text property-behavior-member-decl ::= decl property-behavior-member-decl ::= accessor-decl // get, set property-behavior-member-decl ::= accessor-requirement-decl property-behavior-member-decl ::= initial-value-requirement-decl ``` ### Bindings within Behavior Declarations Inside a behavior declaration, `self` is implicitly bound to the value that contains the property instantiated using this behavior. For a freestanding property at global or local scope, this will be the empty tuple `()`, and for a static or class property, this will be the metatype. Within the behavior declaration, the type of `self` is abstract and represented by the implicit generic type parameter `Self`. Constraints can be placed on `Self` in the generic signature of the behavior, to make protocol members available on `self`: ```swift protocol Fungible { typealias Fungus func funge() -> Fungus } var behavior runcible<Value where Self: Fungible, Self.Fungus == Value>: Value { get { return self.funge() } } ``` Lookup within `self` is *not* implicit within behaviors and must always be explicit, since unqualified lookup refers to the behavior's own members. `self` is immutable except in `mutating` methods, where it is considered an `inout` parameter unless the `Self` type has a class constraint. `self` cannot be accessed within inline initializers of the behavior's storage or in `init` declarations, since these may run during the container's own initialization phase. Definitions within behaviors can refer to other members of the behavior by unqualified lookup, or if disambiguation is necessary, by qualified lookup on the behavior's name (since `self` is already taken to mean the containing value): ```swift var behavior foo<Value>: Value { var x: Int init() { x = 1738 } mutating func update(x: Int) { foo.x = x // Disambiguate reference to behavior storage } } ``` If the behavior includes *accessor requirement declarations*, then the declared accessor names are bound as functions with labeled arguments: ```swift var behavior fakeComputed<Value>: Value { accessor get() -> Value mutating accessor set(newValue: Value) get { return get() } set { set(newValue: newValue) } } ``` Note that the behavior's own *core accessor* implementations `get { ... }` and `set { ... }` are *not* referenceable this way. If the behavior includes an *initial value requirement declaration*, then the identifier `initialValue` is bound as a get-only computed property that evaluates the initial value expression for the property ### Properties and Methods in Behaviors Behaviors may include property and method declarations. Any storage produced by behavior properties is expanded into the containing scope of a property using the behavior. ```swift var behavior runcible<Value>: Value { var x: Int = 0 let y: String = "" ... } var [runcible] a: Int // expands to: var `a.[runcible].x`: Int let `a.[runcible].y`: String var a: Int { ... } ``` For public behaviors, this is inherently *fragile*, so adding or removing storage is a breaking change. Resilience can be achieved by using a resilient type as storage. The instantiated properties must also be of types that are visible to potential users of the behavior, meaning that public behaviors must use storage with types that are either public or internal-with-availability, similar to the restrictions on inlineable functions. Method and computed property implementations have only immutable access to `self` and their storage by default, unless they are `mutating`. (As with computed properties, setters are `mutating` by default unless explicitly marked `nonmutating`). ### `init` in Behaviors The storage of a behavior must be initialized, either by inline initialization, or by an `init` declaration within the initializer: ```swift var behavior inlineInitialized<Value>: Value { var x: Int = 0 // initialized inline ... } var behavior initInitialized<Value>: Value { var x: Int init() { x = 0 } } ``` Behaviors can contain at most one `init` declaration, which must take no parameters. This `init` declaration cannot take a visibility modifier; it is always as visible as the behavior itself. Neither inline initializers nor `init` declaration bodies may reference `self`, since they will be executed during the initialization of a property's containing value. ### Initial Value Requirement Declaration An *initial value requirement declaration* specifies that a behavior requires any property declared using the behavior to be declared with an initial value expression. ```swift initial-value-requirement-decl ::= 'initialValue' ``` The initial value expression from the property declaration is coerced to the property's type and bound to the `initialValue` identifier in the scope of the behavior. Loading from `initialValue` behaves like a get-only computed property, evaluating the expression every time it is loaded: ```swift var behavior evalTwice<Value>: Value { initialValue get { // Evaluate the initial value twice, for whatever reason. _ = initialValue return initialValue } } var [evalTwice] test: () = print("test") // Prints "test" twice _ = evalTwice ``` A property declared with a behavior must have an initial value expression if and only if the behavior has an initial value requirement. ### Accessor Requirement Declarations An *accessor requirement declaration* specifies that a behavior requires any property declared using the behavior to provide an accessor implementation. An accessor requirement declaration is introduced by the contextual `accessor` keyword: ```swift accessor-requirement-decl ::= attribute* decl-modifier* 'accessor' identifier function-signature function-body? ``` An accessor requirement declaration looks like, and serves a similar role to, a function requirement declaration in a protocol. A property using the behavior must supply an implementation for each of its accessor requirements that don't have a default implementation. The accessor names (with labeled arguments) are bound as functions within the behavior declaration: ```swift // Reinvent computed properties var behavior foobar<Value>: Value { accessor foo() -> Value mutating accessor bar(bas: Value) get { return foo() } set { bar(bas: newValue) } } var [foobar] foo: Int { foo { return 0 } bar { // Parameter gets the name 'bas' from the accessor requirement // by default, as with built-in accessors today. print(bas) } } var [foobar] bar: Int { foo { return 0 } bar(myNewValue) { // Parameter name can be overridden as well print(myNewValue) } } ``` Accessor requirements can be made optional by specifying a default implementation: ```swift // Reinvent property observers var behavior observed<Value>: Value { // Requirements initialValue mutating accessor willSet(newValue: Value) { // do nothing by default } mutating accessor didSet(oldValue: Value) { // do nothing by default } // Implementation init() { value = initialValue } get { return value } set { willSet(newValue: newValue) let oldValue = value value = newValue didSet(oldValue: oldValue) } } ``` Accessor requirements cannot take visibility modifiers; they are always as visible as the behavior itself. Like methods, accessors are not allowed to mutate the storage of the behavior or `self` unless declared `mutating`. Mutating accessors can only be invoked by the behavior from other `mutating` contexts. ### Core Accessor Declarations The behavior implements the property by defining its *core accessors*, `get` and optionally `set`. If a behavior only provides a getter, it produces read-only properties; if it provides both a getter and setter, it produces mutable properties (though properties that instantiate the behavior may still control the visibility of their setters). It is an error if a behavior declaration does not provide at least a getter. ### Using Behaviors in Property Declarations Property declarations gain the ability to instantiate behavior, with arbitrary accessors: ```text property-decl ::= attribute* decl-modifier* core-property-decl core-property-decl ::= ('var' | 'let') behavior? pattern-binding ((',' pattern-binding)+ | accessors)? behavior ::= '[' visibility? decl-ref ']' pattern-binding ::= var-pattern (':' type)? inline-initializer? inline-initializer ::= '=' expr accessors ::= '{' accessor+ '}' | brace-stmt // see notes about disambiguation accessor ::= decl-modifier* decl-ref accessor-args? brace-stmt accessor-args ::= '(' identifier (',' identifier)* ')' ``` For example: ```swift public var [behavior] prop: Int { accessor1 { body() } behavior.accessor2(arg) { body() } } ``` If multiple properties are declared in the same declaration, the behavior apply to every declared property. `let` properties cannot yet use behaviors. If the behavior requires accessors, the implementations for those accessors are taken from the property's accessor declarations, matching by name. To support future composition of behaviors, the accessor definitions can use qualified names `behavior.accessor`. If an accessor requirement takes parameters, but the definition in for the property does not explicitly name parameters, the parameter labels from the behavior's accessor requirement declaration are implicitly bound by default. ```swift var behavior foo<Value>: Value { accessor bar(arg: Int) ... } var [foo] x: Int { bar { print(arg) } // `arg` implicitly bound } var [foo] x: Int { bar(myArg) { print(myArg) } // `arg` explicitly bound to `myArg` } ``` If any accessor definition in the property does not match up to a behavior requirement, it is an error. The shorthand for get-only computed properties is only allowed for computed properties that use no behaviors. Any property that uses behaviors with accessors must name all those accessors explicitly. If a property with behaviors declares an inline initializer, the initializer expression is captured as the implementation of a computed, get-only property which is bound to the behavior's initializer requirement. If the behavior does not have a behavior requirement, then it is an error to use an inline initializer expression. Conversely, it is an error not to provide an initializer expression to a behavior that requires one. Properties cannot be declared using behaviors inside protocols. Under this proposal, even if a property with a behavior has an initial value expression, the type is always required to be explicitly declared. Behaviors also do not allow for out-of-line initialization of properties. Both of these restrictions can be lifted by future extensions; see the **Future directions** section below. ## Impact on existing code By itself, this is an additive feature that doesn't impact existing code. However, with some of the future directions suggested, it can potentially obsolete `lazy`, `willSet`/`didSet`, and `@NSCopying` as hardcoded language features. We could grandfather these in, but my preference would be to phase them out by migrating them to library-based property behavior implementations. (Removing them should be its own separate proposal, though.) ## Alternatives considered ### Using a protocol (formal or not) instead of a new declaration A previous iteration of this proposal used an informal instantiation protocol for property behaviors, desugaring a behavior into function calls, so that: ```swift var [lazy] foo = 1738 ``` would act as sugar for something like this: ```swift var `foo.[lazy]` = lazy(var: Int.self, initializer: { 1738 }) var foo: Int { get { return `foo.[lazy]`[varIn: self, initializer: { 1738 }] } set { `foo.[lazy]`[varIn: self, initializer: { 1738 }] = newValue } } ``` There are a few disadvantages to this approach: - Behaviors would pollute the namespace, potentially with multiple global functions and/or types. - In practice, it would require every behavior to be implemented using a new (usually generic) type, which introduces runtime overhead for the type's metadata structures. - The property behavior logic ends up less clear, being encoded in unspecialized language constructs. - Determining the capabilities of a behavior relied on function overload resolution, which can be fiddly, and would require a lot of special case diagnostic work to get good, property-oriented error messages out of. - Without severely complicating the informal protocol, it would be difficult to support eager vs. deferred initializers, or allow mutating access to `self` concurrently with the property's own storage without violating `inout` aliasing rules. The code generation for standalone behavior decls can hide this complexity. Making property behaviors a distinct declaration undeniably increases the language size, but the demand for something like behaviors is clearly there. In return for a new declaration, we get better namespacing, more efficient code generation, clearer, more descriptive code for their implementation, and more expressive power with better diagnostics. I argue that the complexity can pay for itself, today by eliminating several special-case language features, and potentially in the future by generalizing to other kinds of behaviors (or being subsumed by an all-encompassing macro system). For instance, a future `func behavior` could conceivably provide Python decorator-like behavior for transforming function bodies. ### "Template"-style behavior declaration syntax John McCall proposed a "template"-like syntax for property behaviors, used in a previous revision of this proposal: ```swift behavior var [lazy] name: Value = initialValue { ... } ``` It's appealing from a declaration-follows-use standpoint, and provides convenient places to slot in name, type, and initial value bindings. However, this kind of syntax is unprecedented in Swift, and in initial review, was not popular. ### Declaration syntax for properties using behaviors Alternatives to the proposed `var [behavior] propertyName` syntax include: - A different set of brackets, `var (behavior) propertyName` or `var {behavior} propertyName`. Parens have the problem of being ambiguous with a tuple `var` declaration, requiring lookahead to resolve. Square brackets also work better with other declarations behaviors could be extended to apply to in the future, such as subscripts or functions - An attribute, such as `@behavior(lazy)` or `behavior(lazy) var`. This is the most conservative answer, but is clunky. - Use the behavior function name directly as an attribute, so that e.g. `@lazy` works. - Use a new keyword, as in `var x: T by behavior`. - Something on the right side of the colon, such as `var x: lazy(T)`. To me this reads like `lazy(T)` is a type of some kind, which it really isn't. ## Future directions The functionality proposed here is quite broad, so to attempt to minimize the review burden of the initial proposal, I've factored out several aspects for separate consideration: ### Behaviors for immutable `let` properties Since we don't have an effects system (yet?), `let` behavior implementations have the potential to invalidate the immutability assumptions expected of `let` properties, and it would be the programmer's responsibility to maintain them. We don't support computed `let`s for the same reason, so I suggest leaving `let`s out of property behaviors for now. `let behavior`s could be added in the future when we have a comprehensive design for immutable computed properties and/or functions. ### Type inference of properties with behaviors There are subtle issues with inferring the type of a property using a behavior when the behavior introduces constraints on the property type. If you have something like this: ```swift var behavior uint16only: UInt16 { ... } var [uint16only] x = 1738 ``` there are two, and possibly more, ways to define what happens: - We type-check the initializer expression in isolation *before* resolving behaviors. In this case, `1738` would type-check by defaulting to `Int`, and then we'd raise an error instantiating the `uint16only` behavior, which requires a property to have type `UInt16`. - We apply the behaviors *before* type-checking the initializer expression, introducing generic constraints on the contextual type of the initializer. In this case, applying the `uint16only` behavior would constrain the contextual type of the initializer to `UInt16`, and we'd successfully type-check the literal as a `UInt16`. There are merits and downsides to both approaches. To allow these issues to be given proper consideration, I'm subsetting them out by proposing to first require that properties with behaviors always declare an explicit type. ### Composing behaviors It is useful to be able to compose behaviors, for instance, to have a lazy property with observers that's also synchronized. Relatedly, it is useful for subclasses to be able to `override` their inherited properties by applying behaviors over the base class implementation, as can be done with `didSet` and `willSet` today. Linear composition can be supported by allowing behaviors to stack, each referring to the underlying property beneath it by `super` or some other magic binding. However, this form of composition can be treacherous, since it allows for "incorrect" compositions of behaviors. One of `lazy • synchronized` or `synchronized • lazy` is going to do the wrong thing. This possibility can be handled somewhat by allowing certain compositions to be open-coded; John McCall has suggested that every composition ought to be directly implemented as an entirely distinct behavior. That of course has an obvious exponential explosion problem; it's infeasible to anticipate and hand-code every useful combination of behaviors. These issues deserve careful separate consideration, so I'm leaving behavior composition out of this initial proposal. ### Deferred evaluation of initialization expressions This proposal does not suggest changing the allowed operations inside initialization expressions; in particular, an initialization of an instance property may not refer to `self` or other instance properties or methods, due to the potential for the expression to execute before the value is fully initialized: ```swift struct Foo { var a = 1 var b = a // Not allowed var c = foo() // Not allowed func foo() { } } ``` This is inconvenient for behaviors like `lazy` that only ever evaluate the initial value expression after the true initialization phase has completed, and where it's desirable to reference `self` to lazily initialize. Behaviors could be extended to annotate the initializer as "deferred", which would allow the initializer expression to refer to `self`, while preventing the initializer expression from being evaluated at initialization time. (If we consider behaviors to be essentially always fragile, this could be inferred from the behavior implementation.) ### Out-of-line initialization with behaviors This proposal also does not allow for behaviors that support out-of-line initialization, as in: ```swift func foo() { // Out-of-line local variable initialization var [behavior] x: Int x = 1 } struct Foo { var [behavior] y: Int init() { // Out-of-line instance property initialization y = 1 } } ``` This is a fairly serious limitation for instance properties. There are a few potential approaches we can take. One is to allow a behavior's `init` logic to take an out-of-line initialization as a parameter, either directly or by having a different constraint on the initializer requirement that *only* allows it to be referred to from `init` (the opposite of "deferred"). It can also be supported indirectly by linear behavior composition, if the default root `super` behavior for a stack of properties defaults to a plain old stored property, which can then follow normal initialization rules. This is similar to how `didSet`/`willSet` behave today. However, this would not allow behaviors to change the initialization behavior in any way. ### Binding the name of a property using the behavior There are a number of clever things you can do with the name of a property if it can be referenced as a string, such as using it to look up a value in a map, to log, or to serialize. We could conceivably support a `name` requirement declaration: ```swift var behavior echo<Value: StringLiteralConvertible>: Value { name: String get { return name } } var [echo] echo: String print(echo) // => echo ``` ### Overloading behaviors It may be useful for behaviors to be overloadable, for instance to give a different implementation to computed and stored variants of a concept: ```swift // A behavior for stored properties... var behavior foo<Value>: Value { initialValue var value: Value = initialValue get { ... } set { ... } } // Same behavior for computed properties... var behavior foo<Value>: Value { initialValue accessor get() -> Value accessor set(newValue: Value) get { ... } set { ... } } ``` We could resolve overloads by accessors, type constraints on `Value`, and/or initializer requirements. However, determining what this overload signature should be, and also the exciting interactions with type inference from initializer expressions, should be a separate discussion. ### Accessing "out-of-band" behavior members It is useful to add out-of-band operations to a property that aren't normal members of its formal type, for instance, to `clear` a lazy property to be recomputed later, or to reset a property to an implementation-defined default value. This is useful, but it complicates the design of the feature. Aside from the obvious surface-level concerns of syntax for accessing these members, this also exposes behaviors as interface rather than purely an implementation detail, meaning their interaction with resilience, protocols, class inheritance, and other abstractions needs to be designed. It's also a fair question whether out-of- band members should be tied to behaviors at all--it could be useful to design out-of-band members as an independent feature independent with behaviors. ---------- [Previous](@previous) | [Next](@next) */
mit
22a4cd45adb5001af05ba6dca93c0411
31.28866
117
0.752496
4.394388
false
false
false
false
NemProject/NEMiOSApp
NEMWallet/Models/TransactionMetaDataModel.swift
1
1202
// // TransactionMetaDataModel.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import Foundation import SwiftyJSON /** Represents a transaction meta data object on the NEM blockchain. Visit the [documentation](http://bob.nem.ninja/docs/#transactionMetaData) for more information. */ public struct TransactionMetaData: SwiftyJSONMappable { // MARK: - Model Properties /// The id of the transaction. public var id: Int? /// The hash of the transaction. public var hash: String? /// The height of the block in which the transaction was included. public var height: Int? /// The transaction hash of the multisig transaction. public var data: String? // MARK: - Model Lifecycle public init?(jsonData: JSON) { id = jsonData["id"].int height = jsonData["height"].int data = jsonData["data"].string if jsonData["innerHash"]["data"].string == nil { hash = jsonData["hash"]["data"].stringValue } else { hash = jsonData["innerHash"]["data"].stringValue } } }
mit
b8aea641a891186168c3bde412f78daa
25.130435
77
0.617304
4.587786
false
false
false
false
stephentyrone/swift
test/IDE/complete_function_builder.swift
8
3413
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_TOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_NONTOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT struct Tagged<Tag, Entity> { let tag: Tag let entity: Entity static func fo } protocol Taggable { } extension Taggable { func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> { return Tagged(tag: tag, entity: self) } } extension Int: Taggable { } extension String: Taggable { } @_functionBuilder struct TaggedBuilder<Tag> { static func buildBlock() -> () { } static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> { return t1 } static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) { return (t1, t2) } static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t2: Tagged<Tag, T3>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) { return (t1, t2, t3) } } enum Color { case red, green, blue } func acceptColorTagged<Result>(@TaggedBuilder<Color> body: (Color) -> Result) { print(body(.blue)) } var globalIntVal: Int = 1 let globalStringVal: String = "" func testAcceptColorTagged(paramIntVal: Int, paramStringVal: String) { let taggedValue = paramIntVal.tag(Color.red) acceptColorTagged { color in #^IN_CLOSURE_TOP^# // IN_CLOSURE_TOP_CONTEXT: Begin completions // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local{{.*}}: taggedValue[#Tagged<Color, Int>#]; name=taggedValue // IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalIntVal[#Int#]; name=globalIntVal // IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalStringVal[#String#]; name=globalStringVal // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: color{{.*}}; name=color // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal // IN_CLOSURE_TOP: End completions } acceptColorTagged { color in paramIntVal.tag(.red) #^IN_CLOSURE_NONTOP^# // Same as IN_CLOSURE_TOP. } acceptColorTagged { color in paramIntVal.tag(#^IN_CLOSURE_COLOR_CONTEXT^#) // IN_CLOSURE_COLOR_CONTEXT: Begin completions // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: color; name=color // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: taggedValue[#Tagged<Color, Int>#]; name=taggedValue // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal // IN_CLOSURE_COLOR_CONTEXT: End completions } } enum MyEnum { case east, west case north, south } @_functionBuilder struct EnumToVoidBuilder { static func buildBlock() {} static func buildBlock(_ :MyEnum) {} static func buildBlock(_ :MyEnum, _: MyEnum) {} static func buildBlock(_ :MyEnum, _: MyEnum, _: MyEnum) {} } func acceptBuilder(@EnumToVoidBuilder body: () -> Void) {}
apache-2.0
a658c98a96e177edf3694fa0e75192f9
34.926316
170
0.675945
3.416416
false
false
false
false
CocoaheadsSaar/Treffen
Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/MainStackButtonsViewController.swift
1
1867
// // MainStackButtonsViewController.swift // AutolayoutTests // // Created by Markus Schmitt on 13.01.16. // Copyright © 2016 Insecom - Markus Schmitt. All rights reserved. // import UIKit import Foundation class MainStackButtonsViewController: UIViewController { var mainStackView: MainStackButtonsView { return view as! MainStackButtonsView } override func viewDidLoad() { super.viewDidLoad() for newButton in mainStackView.buttonArray { newButton.addTarget(self, action: Selector("evaluateButton:"), forControlEvents: .TouchDown) } mainStackView.switchButton.addTarget(self, action: Selector("switchButtonAlignment:"), forControlEvents: .TouchDown) } override func loadView() { let contentView = MainStackButtonsView(frame: .zero) view = contentView } override func viewWillLayoutSubviews() { let topLayoutGuide = self.topLayoutGuide let bottomLayoutGuide = self.bottomLayoutGuide let views = ["topLayoutGuide": topLayoutGuide, "buttonStackView" : mainStackView.buttonStackView, "bottomLayoutGuide" : bottomLayoutGuide, "switchButton" : mainStackView.switchButton] as [String:AnyObject] NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[buttonStackView]-[switchButton(40)]-[bottomLayoutGuide]", options: [], metrics: nil, views: views)) } func evaluateButton(sender: UIButton) { print("Button : \(sender.tag)") } func switchButtonAlignment(sender: UIButton) { let newOrientation: UILayoutConstraintAxis = (mainStackView.buttonStackView.axis == .Horizontal) ? .Vertical : .Horizontal mainStackView.buttonStackView.axis = newOrientation } }
gpl-2.0
8cfd412861949b9f6d82d4f9e9788618
32.321429
214
0.689711
5.795031
false
false
false
false
hooman/swift
test/IRGen/objc_structs.swift
13
3886
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[GIZMO:%TSo5GizmoC]] = type opaque // CHECK: [[NSRECT:%TSo6NSRectV]] = type <{ [[NSPOINT:%TSo7NSPointV]], [[NSSIZE:%TSo6NSSizeV]] }> // CHECK: [[NSPOINT]] = type <{ [[DOUBLE:%TSd]], [[DOUBLE]] }> // CHECK: [[DOUBLE]] = type <{ double }> // CHECK: [[NSSIZE]] = type <{ [[DOUBLE]], [[DOUBLE]] }> // CHECK: [[NSSTRING:%TSo8NSStringC]] = type opaque // CHECK: [[NSVIEW:%TSo6NSViewC]] = type opaque // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs8getFrame{{[_0-9a-zA-Z]*}}F"([[GIZMO]]* %0) {{.*}} { func getFrame(_ g: Gizmo) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(frame)" // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*)*)([[NSRECT]]* noalias nocapture sret({{.*}}) {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}) return g.frame() } // CHECK: } // CHECK: define hidden swiftcc void @"$s12objc_structs8setFrame{{[_0-9a-zA-Z]*}}F"(%TSo5GizmoC* %0, double %1, double %2, double %3, double %4) {{.*}} { func setFrame(_ g: Gizmo, frame: NSRect) { // CHECK: load i8*, i8** @"\01L_selector(setFrame:)" // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval({{.*}}) align 8 {{.*}}) g.setFrame(frame) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs8makeRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3) func makeRect(_ a: Double, b: Double, c: Double, d: Double) -> NSRect { // CHECK: call void @NSMakeRect(%struct.NSRect* noalias nocapture sret({{.*}}) {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}) return NSMakeRect(a,b,c,d) } // CHECK: } // CHECK: define hidden swiftcc [[stringLayout:[^@]*]] @"$s12objc_structs14stringFromRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3) {{.*}} { func stringFromRect(_ r: NSRect) -> String { // CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect(%struct.NSRect* byval({{.*}}) align 8 {{.*}}) return NSStringFromRect(r) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs9insetRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3, double %4, double %5) func insetRect(_ r: NSRect, x: Double, y: Double) -> NSRect { // CHECK: call void @NSInsetRect(%struct.NSRect* noalias nocapture sret({{.*}}) {{.*}}, %struct.NSRect* byval({{.*}}) align 8 {{.*}}, double {{.*}}, double {{.*}}) return NSInsetRect(r, x, y) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @"$s12objc_structs19convertRectFromBase{{[_0-9a-zA-Z]*}}F"([[NSVIEW]]* %0, double %1, double %2, double %3, double %4) func convertRectFromBase(_ v: NSView, r: NSRect) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret({{.*}}) {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval({{.*}}) align 8 {{.*}}) return v.convertRect(fromBase: r) } // CHECK: } // CHECK: define hidden swiftcc { {{.*}}*, {{.*}}*, {{.*}}*, {{.*}}* } @"$s12objc_structs20useStructOfNSStringsySo0deF0VADF"({{.*}}* %0, {{.*}}* %1, {{.*}}* %2, {{.*}}* %3) // CHECK: call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret({{.*}}) {{%.*}}, %struct.StructOfNSStrings* byval({{.*}}) align 8 {{%.*}}) func useStructOfNSStrings(_ s: StructOfNSStrings) -> StructOfNSStrings { return useStructOfNSStringsInObjC(s) }
apache-2.0
4e997e8fc9618bf67eb4381ab5bebfce
56.147059
247
0.59753
3.466548
false
false
false
false
Ajunboys/actor-platform
actor-apps/app-ios/Actor/Resources/AppTheme.swift
24
14026
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation var MainAppTheme = AppTheme() class AppTheme { var navigation: AppNavigationBar { get { return AppNavigationBar() } } var tab: AppTabBar { get { return AppTabBar() } } var search: AppSearchBar { get { return AppSearchBar() } } var list: AppList { get { return AppList() } } var bubbles: ChatBubbles { get { return ChatBubbles() } } var text: AppText { get { return AppText() } } var chat: AppChat { get { return AppChat() } } var common: AppCommon { get { return AppCommon() } } func applyAppearance(application: UIApplication) { navigation.applyAppearance(application) tab.applyAppearance(application) search.applyAppearance(application) list.applyAppearance(application) } } class AppText { var textPrimary: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } } class AppChat { var chatField: UIColor { get { return UIColor.whiteColor() } } var attachColor: UIColor { get { return UIColor.RGB(0x5085CB) } } var sendEnabled: UIColor { get { return UIColor.RGB(0x50A1D6) } } var sendDisabled: UIColor { get { return UIColor.alphaBlack(0.56) } } var profileBgTint: UIColor { get { return UIColor.RGB(0x5085CB) } } var autocompleteHighlight: UIColor { get { return UIColor.RGB(0x5085CB) } } } class AppCommon { var isDarkKeyboard: Bool { get { return false } } var tokenFieldText: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldTextSelected: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldBg: UIColor { get { return UIColor.RGB(0x5085CB) } } } class ChatBubbles { // Basic colors var text : UIColor { get { return UIColor.RGB(0x141617) } } var textUnsupported : UIColor { get { return UIColor.RGB(0x50b1ae) } } var bgOut: UIColor { get { return UIColor.RGB(0xD2FEFD) } } var bgOutBorder: UIColor { get { return UIColor.RGB(0x99E4E3) } } var bgIn : UIColor { get { return UIColor.whiteColor() } } var bgInBorder:UIColor { get { return UIColor.RGB(0xCCCCCC) } } var statusActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDanger : UIColor { get { return UIColor.redColor() } } var statusMediaActive : UIColor { get { return UIColor.RGB(0x1ed2f9) } } var statusMediaPassive : UIColor { get { return UIColor.whiteColor() } } // TODO: Fix var statusMediaDanger : UIColor { get { return UIColor.redColor() } } var statusDialogActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusDialogPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDialogDanger : UIColor { get { return UIColor.redColor() } } // Dialog-based colors var statusDialogSending : UIColor { get { return statusDialogPassive } } var statusDialogSent : UIColor { get { return statusDialogPassive } } var statusDialogReceived : UIColor { get { return statusDialogPassive } } var statusDialogRead : UIColor { get { return statusDialogActive } } var statusDialogError : UIColor { get { return statusDialogDanger } } // Text-based bubble colors var statusSending : UIColor { get { return statusPassive } } var statusSent : UIColor { get { return statusPassive } } var statusReceived : UIColor { get { return statusPassive } } var statusRead : UIColor { get { return statusActive } } var statusError : UIColor { get { return statusDanger } } var textBgOut: UIColor { get { return bgOut } } var textBgOutBorder : UIColor { get { return bgOutBorder } } var textBgIn : UIColor { get { return bgIn } } var textBgInBorder : UIColor { get { return bgInBorder } } var textDateOut : UIColor { get { return UIColor.alphaBlack(0.27) } } var textDateIn : UIColor { get { return UIColor.RGB(0x979797) } } var textOut : UIColor { get { return text } } var textIn : UIColor { get { return text } } var textUnsupportedOut : UIColor { get { return textUnsupported } } var textUnsupportedIn : UIColor { get { return textUnsupported } } // Media-based bubble colors var statusMediaSending : UIColor { get { return statusMediaPassive } } var statusMediaSent : UIColor { get { return statusMediaPassive } } var statusMediaReceived : UIColor { get { return statusMediaPassive } } var statusMediaRead : UIColor { get { return statusMediaActive } } var statusMediaError : UIColor { get { return statusMediaDanger } } var mediaBgOut: UIColor { get { return UIColor.whiteColor() } } var mediaBgOutBorder: UIColor { get { return UIColor.RGB(0xCCCCCC) } } var mediaBgIn: UIColor { get { return mediaBgOut } } var mediaBgInBorder: UIColor { get { return mediaBgOutBorder } } var mediaDateBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.54) } } var mediaDate: UIColor { get { return UIColor.whiteColor() } } // Service-based bubble colors var serviceBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.56) } } var chatBgTint: UIColor { get { return UIColor.RGB(0xe7e0c4) } } } class AppList { var actionColor : UIColor { get { return UIColor.RGB(0x5085CB) } } var bgColor: UIColor { get { return UIColor.whiteColor() } } var bgSelectedColor : UIColor { get { return UIColor.RGB(0xd9d9d9) } } var backyardColor : UIColor { get { return UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) } } var separatorColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x1e/255.0) } } var textColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var hintColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } var sectionColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } // var arrowColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogText: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var dialogDate: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var unreadText: UIColor { get { return UIColor.whiteColor() } } var unreadBg: UIColor { get { return UIColor.RGB(0x50A1D6) } } var contactsTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var contactsShortTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } func applyAppearance(application: UIApplication) { UITableViewHeaderFooterView.appearance().tintColor = sectionColor } } class AppSearchBar { var statusBarLightContent : Bool { get { return false } } var backgroundColor : UIColor { get { return UIColor.RGB(0xf1f1f1) } } var cancelColor : UIColor { get { return UIColor.RGB(0x8E8E93) } } var fieldBackgroundColor: UIColor { get { return UIColor.whiteColor() } } var fieldTextColor: UIColor { get { return UIColor.blackColor().alpha(0.56) } } func applyAppearance(application: UIApplication) { // SearchBar Text Color var textField = UITextField.my_appearanceWhenContainedIn(UISearchBar.self) // textField.tintColor = UIColor.redColor() var font = UIFont(name: "HelveticaNeue", size: 14.0) textField.defaultTextAttributes = [NSFontAttributeName: font!, NSForegroundColorAttributeName : fieldTextColor] } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func styleSearchBar(searchBar: UISearchBar) { // SearchBar Minimal Style searchBar.searchBarStyle = UISearchBarStyle.Default // SearchBar Transculent searchBar.translucent = false // SearchBar placeholder animation fix searchBar.placeholder = ""; // SearchBar background color searchBar.barTintColor = backgroundColor.forTransparentBar() searchBar.setBackgroundImage(Imaging.imageWithColor(backgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) searchBar.backgroundColor = backgroundColor // SearchBar field color var fieldBg = Imaging.imageWithColor(fieldBackgroundColor, size: CGSize(width: 14,height: 28)) .roundCorners(14, h: 28, roundSize: 4) searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal) // SearchBar cancel color searchBar.tintColor = cancelColor } } class AppTabBar { private let mainColor = UIColor.RGB(0x5085CB) var backgroundColor : UIColor { get { return UIColor.whiteColor() } } var showText : Bool { get { return true } } var selectedIconColor: UIColor { get { return mainColor } } var selectedTextColor : UIColor { get { return mainColor } } var unselectedIconColor:UIColor { get { return mainColor.alpha(0.56) } } var unselectedTextColor : UIColor { get { return mainColor.alpha(0.56) } } var barShadow : String? { get { return "CardTop2" } } func createSelectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(selectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func createUnselectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(unselectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func applyAppearance(application: UIApplication) { var tabBar = UITabBar.appearance() // TabBar Background color tabBar.barTintColor = backgroundColor; // TabBar Shadow if (barShadow != nil) { tabBar.shadowImage = UIImage(named: barShadow!); } else { tabBar.shadowImage = nil } var tabBarItem = UITabBarItem.appearance() // TabBar Unselected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: unselectedTextColor], forState: UIControlState.Normal) // TabBar Selected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor], forState: UIControlState.Selected) } } class AppNavigationBar { var statusBarLightContent : Bool { get { return true } } var barColor:UIColor { get { return /*UIColor.RGB(0x5085CB)*/ UIColor.RGB(0x3576cc) } } var barSolidColor:UIColor { get { return UIColor.RGB(0x5085CB) } } var titleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleActiveColor: UIColor { get { return UIColor.whiteColor() } } var shadowImage : String? { get { return nil } } var progressPrimary: UIColor { get { return UIColor.RGB(0x1484ee) } } var progressSecondary: UIColor { get { return UIColor.RGB(0xaccceb) } } func applyAppearance(application: UIApplication) { // StatusBar style if (statusBarLightContent) { application.statusBarStyle = UIStatusBarStyle.LightContent } else { application.statusBarStyle = UIStatusBarStyle.Default } var navAppearance = UINavigationBar.appearance(); // NavigationBar Icon navAppearance.tintColor = titleColor; // NavigationBar Text navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: titleColor]; // NavigationBar Background navAppearance.barTintColor = barColor; // navAppearance.setBackgroundImage(Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 1)), forBarMetrics: UIBarMetrics.Default) // navAppearance.shadowImage = Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 2)) // Small hack for correct background color UISearchBar.appearance().backgroundColor = barColor // NavigationBar Shadow // navAppearance.shadowImage = nil // if (shadowImage == nil) { // navAppearance.shadowImage = UIImage() // navAppearance.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) // } else { // navAppearance.shadowImage = UIImage(named: shadowImage!) // } } func applyAuthStatusBar() { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func applyStatusBarFast() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false) } } }
mit
618972df17617410e4b33a1ec36b6645
41.896024
181
0.662484
4.462615
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Views/ConversationAvatarView.swift
1
10185
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import WireSyncEngine /// Source of random values. protocol RandomGenerator { func rand<ContentType>() -> ContentType } /// Generates the pseudorandom values from the data given. /// @param data the source of random values. final class RandomGeneratorFromData: RandomGenerator { public let source: Data private var step: Int = 0 init(data: Data) { source = data } public func rand<ContentType>() -> ContentType { let currentStep = self.step let result = source.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> ContentType in return pointer.baseAddress!.assumingMemoryBound(to: ContentType.self).advanced(by: currentStep % (source.count - MemoryLayout<ContentType>.size)).pointee } step += MemoryLayout<ContentType>.size return result } } extension RandomGeneratorFromData { /// Use UUID as plain data to generate random value. convenience init(uuid: UUID) { self.init(data: (uuid as NSUUID).data()!) } } extension Array { func shuffled(with generator: RandomGenerator) -> Array { var workingCopyIndices = [Int](indices) var resultIndices = [Int]() forEach { _ in let rand: UInt = generator.rand() % (UInt)(workingCopyIndices.count) resultIndices.append(workingCopyIndices[Int(rand)]) workingCopyIndices.remove(at: Int(rand)) } return resultIndices.map { self[$0] } } } extension ZMConversation: StableRandomParticipantsProvider { /// Stable random list of the participants in the conversation. The list would be consistent between platforms /// because the conversation UUID is used as the random indexes source. var stableRandomParticipants: [UserType] { let allUsers = sortedActiveParticipants guard let remoteIdentifier = self.remoteIdentifier else { return allUsers } let rand = RandomGeneratorFromData(uuid: remoteIdentifier) return allUsers.shuffled(with: rand) } } enum Mode: Equatable { /// 0 participants in conversation: /// / \ /// \ / case none /// 1-2 participants in conversation: /// / AA \ /// \ AA / case one(serviceUser: Bool) /// 2+ participants in conversation: /// / AB \ /// \ CD / case four } extension Mode { /// create a Mode for different cases /// /// - Parameters: /// - conversationType: when conversationType is nil, it is a incoming connection request /// - users: number of users involved in the conversation fileprivate init(conversationType: ZMConversationType? = nil, users: [UserType]) { switch (users.count, conversationType) { case (0, _): self = .none case (1, .group?): let isServiceUser = users[0].isServiceUser self = isServiceUser ? .one(serviceUser: isServiceUser) : .four case (1, _): self = .one(serviceUser: users[0].isServiceUser) default: self = .four } } var showInitials: Bool { if case .one = self { return true } else { return false } } var shape: AvatarImageView.Shape { switch self { case .one(serviceUser: true): return .relative default: return .rectangle } } } typealias ConversationAvatarViewConversation = ConversationLike & StableRandomParticipantsProvider final class ConversationAvatarView: UIView { enum Context { // one or more users requesting connection to self user case connect(users: [UserType]) // an established conversation or self user has a pending request to other users case conversation(conversation: ConversationAvatarViewConversation) } func configure(context: Context) { switch context { case .connect(let users): self.users = users mode = Mode(users: users) case .conversation(let conversation): self.conversation = conversation mode = Mode(conversationType: conversation.conversationType, users: users) } } private var users: [UserType] = [] private var conversation: ConversationAvatarViewConversation? = .none { didSet { guard let conversation = conversation else { self.clippingView.subviews.forEach { $0.isHidden = true } return } accessibilityLabel = "Avatar for \(conversation.displayName)" let usersOnAvatar: [UserType] let stableRandomParticipants = conversation.stableRandomParticipants.filter { !$0.isSelfUser } if stableRandomParticipants.isEmpty, let connectedUser = conversation.connectedUserType { usersOnAvatar = [connectedUser] } else { usersOnAvatar = stableRandomParticipants } users = usersOnAvatar } } private(set) var mode: Mode = .one(serviceUser: false) { didSet { self.clippingView.subviews.forEach { $0.isHidden = true } self.userImages().forEach { $0.isHidden = false } if case .one = mode { layer.borderWidth = 0 backgroundColor = .clear } else { layer.borderWidth = .hairline layer.borderColor = UIColor(white: 1, alpha: 0.24).cgColor backgroundColor = UIColor(white: 0, alpha: 0.16) } var index: Int = 0 self.userImages().forEach { $0.userSession = ZMUserSession.shared() $0.shouldDesaturate = false $0.size = mode == .four ? .tiny : .small if index < users.count { $0.user = users[index] } else { $0.user = nil $0.container.isOpaque = false $0.container.backgroundColor = UIColor(white: 0, alpha: 0.24) $0.avatar = .none } $0.allowsInitials = mode.showInitials $0.shape = mode.shape index += 1 } setNeedsLayout() } } private var userImageViews: [UserImageView] { return [imageViewLeftTop, imageViewRightTop, imageViewLeftBottom, imageViewRightBottom] } func userImages() -> [UserImageView] { switch mode { case .none: return [] case .one: return [imageViewLeftTop] case .four: return userImageViews } } override var intrinsicContentSize: CGSize { return CGSize(width: CGFloat.ConversationAvatarView.iconSize, height: CGFloat.ConversationAvatarView.iconSize) } let clippingView = UIView() let imageViewLeftTop: UserImageView = { let userImageView = BadgeUserImageView() userImageView.initialsFont = .mediumSemiboldFont return userImageView }() lazy var imageViewRightTop: UserImageView = { return UserImageView() }() lazy var imageViewLeftBottom: UserImageView = { return UserImageView() }() lazy var imageViewRightBottom: UserImageView = { return UserImageView() }() init() { super.init(frame: .zero) userImageViews.forEach(self.clippingView.addSubview) updateCornerRadius() autoresizesSubviews = false layer.masksToBounds = true clippingView.clipsToBounds = true self.addSubview(clippingView) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let interAvatarInset: CGFloat = 2 var containerSize: CGSize { return self.clippingView.bounds.size } override func layoutSubviews() { super.layoutSubviews() guard self.bounds != .zero else { return } clippingView.frame = self.bounds.insetBy(dx: 2, dy: 2) switch mode { case .none: break case .one: self.userImages().forEach { $0.frame = clippingView.bounds } case .four: layoutMultipleAvatars(with: CGSize(width: (containerSize.width - interAvatarInset) / 2.0, height: (containerSize.height - interAvatarInset) / 2.0)) } updateCornerRadius() } private func layoutMultipleAvatars(with size: CGSize) { var xPosition: CGFloat = 0 var yPosition: CGFloat = 0 self.userImages().forEach { $0.frame = CGRect(x: xPosition, y: yPosition, width: size.width, height: size.height) if xPosition + size.width >= containerSize.width { xPosition = 0 yPosition += size.height + interAvatarInset } else { xPosition += size.width + interAvatarInset } } } private func updateCornerRadius() { switch mode { case .one(serviceUser: let serviceUser): layer.cornerRadius = serviceUser ? 0 : layer.bounds.width / 2.0 clippingView.layer.cornerRadius = serviceUser ? 0 : clippingView.layer.bounds.width / 2.0 default: layer.cornerRadius = 6 clippingView.layer.cornerRadius = 4 } } }
gpl-3.0
157bea1128ec9cc8285e9fb02dc94a6a
29.957447
165
0.603731
4.970717
false
false
false
false
ZekeSnider/Jared
Pods/Telegraph/Sources/Clients/WebSocketClient.swift
1
9945
// // WebSocketClient.swift // Telegraph // // Created by Yvo van Beek on 2/9/17. // Copyright © 2017 Building42. All rights reserved. // import Foundation public protocol WebSocketClientDelegate: class { func webSocketClient(_ client: WebSocketClient, didConnectToHost host: String) func webSocketClient(_ client: WebSocketClient, didDisconnectWithError error: Error?) func webSocketClient(_ client: WebSocketClient, didReceiveData data: Data) func webSocketClient(_ client: WebSocketClient, didReceiveText text: String) } open class WebSocketClient: WebSocket { public let url: URL public var headers: HTTPHeaders public var config = WebSocketConfig.clientDefault public var tlsPolicy: TLSPolicy? public weak var delegate: WebSocketClientDelegate? private let workQueue = DispatchQueue(label: "Telegraph.WebSocketClient.work") private let delegateQueue = DispatchQueue(label: "Telegraph.WebSocketClient.delegate") private let endpoint: Endpoint private var socket: TCPSocket? private var httpConnection: HTTPConnection? private var webSocketConnection: WebSocketConnection? /// Initializes a new WebSocketClient with an url public init(url: URL, headers: HTTPHeaders = .empty) throws { guard url.hasWebSocketScheme else { throw WebSocketClientError.invalidScheme } guard let endpoint = Endpoint(url: url) else { throw WebSocketClientError.invalidHost } // Store the connection information self.url = url self.endpoint = endpoint self.headers = headers // Only mask unsecure connections config.maskMessages = !url.isSchemeSecure } /// Performs the handshake with the host, forming the websocket connection. public func connect(timeout: TimeInterval = 10) { workQueue.async { [weak self] in guard let self = self else { return } // Release the old connections self.httpConnection = nil self.webSocketConnection = nil // Create and connect the socket self.socket = TCPSocket(endpoint: self.endpoint, tlsPolicy: self.tlsPolicy) self.socket!.setDelegate(self, queue: self.workQueue) self.socket!.connect(timeout: timeout) } } /// Disconnects the client. Same as calling close with immediately: false. public func disconnect() { close(immediately: false) } /// Disconnects the client. public func close(immediately: Bool) { workQueue.async { [weak self] in self?.socket?.close(when: .immediately) self?.httpConnection?.close(immediately: true) self?.webSocketConnection?.close(immediately: immediately) } } /// Sends a raw websocket message. public func send(message: WebSocketMessage) { workQueue.async { [weak self] in self?.webSocketConnection?.send(message: message) } } /// Performs a handshake to initiate the websocket connection. private func performHandshake(socket: TCPSocket) { // Create the handshake request let requestURI = URI(path: url.path, query: url.query) let handshakeRequest = HTTPRequest(uri: requestURI, headers: headers) handshakeRequest.webSocketHandshake(host: endpoint.host, port: endpoint.port) // Create the HTTP connection (retains the socket) self.httpConnection = HTTPConnection(socket: socket, config: HTTPConfig.clientDefault) self.httpConnection!.delegate = self self.httpConnection!.open() // Send the handshake request self.httpConnection!.send(request: handshakeRequest) } /// Processes the handshake response. private func handleHandshakeResponse(_ response: HTTPResponse) { // Validate the handshake response guard response.isWebSocketHandshake else { let handShakeError = WebSocketClientError.handshakeFailed(response: response) handleHandshakeError(handShakeError) return } // Extract the information from the HTTP connection guard let (socket, webSocketData) = httpConnection?.upgrade() else { return } // Release the HTTP connection httpConnection = nil // Create a WebSocket connection (retains the socket) webSocketConnection = WebSocketConnection(socket: socket, config: config) webSocketConnection!.delegate = self webSocketConnection!.open(data: webSocketData) // Inform the delegate that we are connected delegateQueue.async { [weak self] in guard let self = self else { return } self.delegate?.webSocketClient(self, didConnectToHost: self.endpoint.host) } } /// Handles a bad response on the websocket handshake. private func handleHandshakeError(_ error: Error?) { // Prevent any connection delegate calls, we want to provide our own error httpConnection?.delegate = nil webSocketConnection?.delegate = nil // Manually close and report the error close(immediately: true) handleConnectionClose(error: error) } /// Handles a connection close. private func handleConnectionClose(error: Error?) { httpConnection = nil webSocketConnection = nil delegateQueue.async { [weak self] in guard let self = self else { return } self.delegate?.webSocketClient(self, didDisconnectWithError: error) } } } // MARK: WebSocket conformance public extension WebSocketClient { /// The local endpoint information, only available when connected. var localEndpoint: Endpoint? { return socket?.localEndpoint } /// The remote endpoint information, only available when connected. var remoteEndpoint: Endpoint? { return socket?.remoteEndpoint } } // MARK: Convenience initializers public extension WebSocketClient { /// Creates a new WebSocketClient with an url in string form. convenience init(_ string: String) throws { guard let url = URL(string: string) else { throw WebSocketClientError.invalidURL } try self.init(url: url) } /// Creates a new WebSocketClient with an url in string form and certificates to trust. convenience init(_ string: String, certificates: [Certificate]) throws { try self.init(string) self.tlsPolicy = TLSPolicy(certificates: certificates) } /// Creates a new WebSocketClient with an url and certificates to trust. convenience init(url: URL, certificates: [Certificate]) throws { try self.init(url: url) self.tlsPolicy = TLSPolicy(certificates: certificates) } } // MARK: TCPSocketDelegate implementation extension WebSocketClient: TCPSocketDelegate { /// Raised when the socket has connected. public func socketDidOpen(_ socket: TCPSocket) { guard socket == self.socket else { return } // Stop retaining the socket self.socket = nil // Start TLS for secure hosts if url.isSchemeSecure { socket.startTLS() } // Send the handshake request performHandshake(socket: socket) } /// Raised when the socket disconnected. public func socketDidClose(_ socket: TCPSocket, error: Error?) { guard socket == self.socket else { return } handleConnectionClose(error: error) } /// Raised when the socket reads (ignore, the connections will handle this). public func socketDidRead(_ socket: TCPSocket, data: Data, tag: Int) {} /// Raised when the socket writes (ignore). public func socketDidWrite(_ socket: TCPSocket, tag: Int) {} } // MARK: TCPSocketDelegate implementation extension WebSocketClient: HTTPConnectionDelegate { /// Raised when the HTTPConnecion was closed. public func connection(_ httpConnection: HTTPConnection, didCloseWithError error: Error?) { guard httpConnection == self.httpConnection else { return } handleConnectionClose(error: error) } /// Raised when the HTTPConnecion received a response. public func connection(_ httpConnection: HTTPConnection, handleIncomingResponse response: HTTPResponse, error: Error?) { guard httpConnection == self.httpConnection else { return } if let error = error { handleHandshakeError(error) } else { handleHandshakeResponse(response) } } /// Raised when the HTTPConnecion received a request (client doesn't support requests -> close). public func connection(_ httpConnection: HTTPConnection, handleIncomingRequest request: HTTPRequest, error: Error?) { guard httpConnection == self.httpConnection else { return } httpConnection.close(immediately: true) } /// Raised when the HTTPConnecion received a request (client doesn't support request upgrades -> close). public func connection(_ httpConnection: HTTPConnection, handleUpgradeByRequest request: HTTPRequest) { guard httpConnection == self.httpConnection else { return } httpConnection.close(immediately: true) } } // MARK: WebSocketConnectionDelegate implementation extension WebSocketClient: WebSocketConnectionDelegate { /// Raised when the WebSocketConnection disconnected. public func connection(_ webSocketConnection: WebSocketConnection, didCloseWithError error: Error?) { guard webSocketConnection == self.webSocketConnection else { return } handleConnectionClose(error: error) } /// Raised when the WebSocketConnection receives a message. public func connection(_ webSocketConnection: WebSocketConnection, didReceiveMessage message: WebSocketMessage) { guard webSocketConnection == self.webSocketConnection else { return } // We are only interested in binary and text messages guard message.opcode == .binaryFrame || message.opcode == .textFrame else { return } // Inform the delegate delegateQueue.async { [weak self] in guard let self = self else { return } switch message.payload { case let .binary(data): self.delegate?.webSocketClient(self, didReceiveData: data) case let .text(text): self.delegate?.webSocketClient(self, didReceiveText: text) default: break } } } /// Raised when the WebSocketConnection sent a message (ignore). public func connection(_ webSocketConnection: WebSocketConnection, didSendMessage message: WebSocketMessage) {} }
apache-2.0
9c982665927ee5dc587ced7ff5831f2f
34.262411
122
0.732502
4.886486
false
false
false
false
hoobaa/nkbd
Keyboard/cKeyboardLayout.swift
6
45040
// // KeyboardLayout.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/25/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // TODO: need to rename, consolidate, and define terms class LayoutConstants: NSObject { class var landscapeRatio: CGFloat { get { return 2 }} // side edges increase on 6 in portrait class var sideEdgesPortraitArray: [CGFloat] { get { return [3, 4] }} class var sideEdgesPortraitWidthThreshholds: [CGFloat] { get { return [400] }} class var sideEdgesLandscape: CGFloat { get { return 3 }} // top edges decrease on various devices in portrait class var topEdgePortraitArray: [CGFloat] { get { return [12, 10, 8] }} class var topEdgePortraitWidthThreshholds: [CGFloat] { get { return [350, 400] }} class var topEdgeLandscape: CGFloat { get { return 6 }} // keyboard area shrinks in size in landscape on 6 and 6+ class var keyboardShrunkSizeArray: [CGFloat] { get { return [522, 524] }} class var keyboardShrunkSizeWidthThreshholds: [CGFloat] { get { return [700] }} class var keyboardShrunkSizeBaseWidthThreshhold: CGFloat { get { return 600 }} // row gaps are weird on 6 in portrait class var rowGapPortraitArray: [CGFloat] { get { return [15, 11, 10] }} class var rowGapPortraitThreshholds: [CGFloat] { get { return [350, 400] }} class var rowGapPortraitLastRow: CGFloat { get { return 9 }} class var rowGapPortraitLastRowIndex: Int { get { return 1 }} class var rowGapLandscape: CGFloat { get { return 7 }} // key gaps have weird and inconsistent rules class var keyGapPortraitNormal: CGFloat { get { return 6 }} class var keyGapPortraitSmall: CGFloat { get { return 5 }} class var keyGapPortraitNormalThreshhold: CGFloat { get { return 350 }} class var keyGapPortraitUncompressThreshhold: CGFloat { get { return 350 }} class var keyGapLandscapeNormal: CGFloat { get { return 6 }} class var keyGapLandscapeSmall: CGFloat { get { return 5 }} // TODO: 5.5 row gap on 5L // TODO: wider row gap on 6L class var keyCompressedThreshhold: Int { get { return 11 }} // rows with two special keys on the side and characters in the middle (usually 3rd row) // TODO: these are not pixel-perfect, but should be correct within a few pixels // TODO: are there any "hidden constants" that would allow us to get rid of the multiplier? see: popup dimensions class var flexibleEndRowTotalWidthToKeyWidthMPortrait: CGFloat { get { return 1 }} class var flexibleEndRowTotalWidthToKeyWidthCPortrait: CGFloat { get { return -14 }} class var flexibleEndRowTotalWidthToKeyWidthMLandscape: CGFloat { get { return 0.9231 }} class var flexibleEndRowTotalWidthToKeyWidthCLandscape: CGFloat { get { return -9.4615 }} class var flexibleEndRowMinimumStandardCharacterWidth: CGFloat { get { return 7 }} class var lastRowKeyGapPortrait: CGFloat { get { return 6 }} class var lastRowKeyGapLandscapeArray: [CGFloat] { get { return [8, 7, 5] }} class var lastRowKeyGapLandscapeWidthThreshholds: [CGFloat] { get { return [500, 700] }} // TODO: approxmiate, but close enough class var lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var micButtonPortraitWidthRatioToOtherSpecialButtons: CGFloat { get { return 0.765 }} // TODO: not exactly precise class var popupGap: CGFloat { get { return 8 }} class var popupWidthIncrement: CGFloat { get { return 26 }} class var popupTotalHeightArray: [CGFloat] { get { return [102, 108] }} class var popupTotalHeightDeviceWidthThreshholds: [CGFloat] { get { return [350] }} class func sideEdgesPortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.sideEdgesPortraitArray, threshholds: self.sideEdgesPortraitWidthThreshholds, measurement: width) } class func topEdgePortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.topEdgePortraitArray, threshholds: self.topEdgePortraitWidthThreshholds, measurement: width) } class func rowGapPortrait(width: CGFloat) -> CGFloat { return self.findThreshhold(self.rowGapPortraitArray, threshholds: self.rowGapPortraitThreshholds, measurement: width) } class func rowGapPortraitLastRow(width: CGFloat) -> CGFloat { let index = self.findThreshholdIndex(self.rowGapPortraitThreshholds, measurement: width) if index == self.rowGapPortraitLastRowIndex { return self.rowGapPortraitLastRow } else { return self.rowGapPortraitArray[index] } } class func keyGapPortrait(width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) if compressed { if width >= self.keyGapPortraitUncompressThreshhold { return self.keyGapPortraitNormal } else { return self.keyGapPortraitSmall } } else { return self.keyGapPortraitNormal } } class func keyGapLandscape(width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) let shrunk = self.keyboardIsShrunk(width) if compressed || shrunk { return self.keyGapLandscapeSmall } else { return self.keyGapLandscapeNormal } } class func lastRowKeyGapLandscape(width: CGFloat) -> CGFloat { return self.findThreshhold(self.lastRowKeyGapLandscapeArray, threshholds: self.lastRowKeyGapLandscapeWidthThreshholds, measurement: width) } class func keyboardIsShrunk(width: CGFloat) -> Bool { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad return (isPad ? false : width >= self.keyboardShrunkSizeBaseWidthThreshhold) } class func keyboardShrunkSize(width: CGFloat) -> CGFloat { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad if isPad { return width } if width >= self.keyboardShrunkSizeBaseWidthThreshhold { return self.findThreshhold(self.keyboardShrunkSizeArray, threshholds: self.keyboardShrunkSizeWidthThreshholds, measurement: width) } else { return width } } class func popupTotalHeight(deviceWidth: CGFloat) -> CGFloat { return self.findThreshhold(self.popupTotalHeightArray, threshholds: self.popupTotalHeightDeviceWidthThreshholds, measurement: deviceWidth) } class func findThreshhold(elements: [CGFloat], threshholds: [CGFloat], measurement: CGFloat) -> CGFloat { assert(elements.count == threshholds.count + 1, "elements and threshholds do not match") return elements[self.findThreshholdIndex(threshholds, measurement: measurement)] } class func findThreshholdIndex(threshholds: [CGFloat], measurement: CGFloat) -> Int { for (i, threshhold) in enumerate(reverse(threshholds)) { if measurement >= threshhold { let actualIndex = threshholds.count - i return actualIndex } } return 0 } } class GlobalColors: NSObject { class var lightModeRegularKey: UIColor { get { return UIColor.whiteColor() }} class var darkModeRegularKey: UIColor { get { return UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorRegularKey: UIColor { get { return UIColor(red: CGFloat(83)/CGFloat(255), green: CGFloat(83)/CGFloat(255), blue: CGFloat(83)/CGFloat(255), alpha: 1) }} class var lightModeSpecialKey: UIColor { get { return GlobalColors.lightModeSolidColorSpecialKey }} class var lightModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(177)/CGFloat(255), green: CGFloat(177)/CGFloat(255), blue: CGFloat(177)/CGFloat(255), alpha: 1) }} class var darkModeSpecialKey: UIColor { get { return UIColor.grayColor().colorWithAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(45)/CGFloat(255), green: CGFloat(45)/CGFloat(255), blue: CGFloat(45)/CGFloat(255), alpha: 1) }} class var darkModeShiftKeyDown: UIColor { get { return UIColor(red: CGFloat(214)/CGFloat(255), green: CGFloat(220)/CGFloat(255), blue: CGFloat(208)/CGFloat(255), alpha: 1) }} class var lightModePopup: UIColor { get { return GlobalColors.lightModeRegularKey }} class var darkModePopup: UIColor { get { return UIColor.grayColor() }} class var darkModeSolidColorPopup: UIColor { get { return GlobalColors.darkModeSolidColorRegularKey }} class var lightModeUnderColor: UIColor { get { return UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1) }} class var darkModeUnderColor: UIColor { get { return UIColor(red: CGFloat(38.6)/CGFloat(255), green: CGFloat(18)/CGFloat(255), blue: CGFloat(39.3)/CGFloat(255), alpha: 0.4) }} class var lightModeTextColor: UIColor { get { return UIColor.blackColor() }} class var darkModeTextColor: UIColor { get { return UIColor.whiteColor() }} class var lightModeBorderColor: UIColor { get { return UIColor(hue: (214/360.0), saturation: 0.04, brightness: 0.65, alpha: 1.0) }} class var darkModeBorderColor: UIColor { get { return UIColor.clearColor() }} class func regularKey(darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorRegularKey } else { return self.darkModeRegularKey } } else { return self.lightModeRegularKey } } class func popup(darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorPopup } else { return self.darkModePopup } } else { return self.lightModePopup } } class func specialKey(darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorSpecialKey } else { return self.darkModeSpecialKey } } else { if solidColorMode { return self.lightModeSolidColorSpecialKey } else { return self.lightModeSpecialKey } } } } //"darkShadowColor": UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1), //"blueColor": UIColor(hue: (211/360.0), saturation: 1.0, brightness: 1.0, alpha: 1), //"blueShadowColor": UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.43, alpha: 1), extension CGRect: Hashable { public var hashValue: Int { get { return (origin.x.hashValue ^ origin.y.hashValue ^ size.width.hashValue ^ size.height.hashValue) } } } extension CGSize: Hashable { public var hashValue: Int { get { return (width.hashValue ^ height.hashValue) } } } // handles the layout for the keyboard, including key spacing and arrangement class KeyboardLayout: NSObject, KeyboardKeyProtocol { class var shouldPoolKeys: Bool { get { return true }} var layoutConstants: LayoutConstants.Type var globalColors: GlobalColors.Type unowned var model: Keyboard unowned var superview: UIView var modelToView: [Key:KeyboardKey] = [:] var viewToModel: [KeyboardKey:Key] = [:] var keyPool: [KeyboardKey] = [] var nonPooledMap: [String:KeyboardKey] = [:] var sizeToKeyMap: [CGSize:[KeyboardKey]] = [:] var shapePool: [String:Shape] = [:] var darkMode: Bool var solidColorMode: Bool var initialized: Bool required init(model: Keyboard, superview: UIView, layoutConstants: LayoutConstants.Type, globalColors: GlobalColors.Type, darkMode: Bool, solidColorMode: Bool) { self.layoutConstants = layoutConstants self.globalColors = globalColors self.initialized = false self.model = model self.superview = superview self.darkMode = darkMode self.solidColorMode = solidColorMode } // TODO: remove this method func initialize() { assert(!self.initialized, "already initialized") self.initialized = true } func viewForKey(model: Key) -> KeyboardKey? { return self.modelToView[model] } func keyForView(key: KeyboardKey) -> Key? { return self.viewToModel[key] } ////////////////////////////////////////////// // CALL THESE FOR LAYOUT/APPEARANCE CHANGES // ////////////////////////////////////////////// func layoutKeys(pageNum: Int, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { CATransaction.begin() CATransaction.setDisableActions(true) // pre-allocate all keys if no cache if !self.dynamicType.shouldPoolKeys { if self.keyPool.isEmpty { for p in 0..<self.model.pages.count { self.positionKeys(p) } self.updateKeyAppearance() self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } } self.positionKeys(pageNum) // reset state for (p, page) in enumerate(self.model.pages) { for (_, row) in enumerate(page.rows) { for (_, key) in enumerate(row) { if let keyView = self.modelToView[key] { keyView.hidePopup() keyView.highlighted = false keyView.hidden = (p != pageNum) } } } } if self.dynamicType.shouldPoolKeys { self.updateKeyAppearance() self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } CATransaction.commit() } func positionKeys(pageNum: Int) { CATransaction.begin() CATransaction.setDisableActions(true) let setupKey = { (view: KeyboardKey, model: Key, frame: CGRect) -> Void in view.frame = frame self.modelToView[model] = view self.viewToModel[view] = model } if var keyMap = self.generateKeyFrames(self.model, bounds: self.superview.bounds, page: pageNum) { if self.dynamicType.shouldPoolKeys { self.modelToView.removeAll(keepCapacity: true) self.viewToModel.removeAll(keepCapacity: true) self.resetKeyPool() var foundCachedKeys = [Key]() // pass 1: reuse any keys that match the required size for (key, frame) in keyMap { if var keyView = self.pooledKey(key: key, model: self.model, frame: frame) { foundCachedKeys.append(key) setupKey(keyView, key, frame) } } foundCachedKeys.map { keyMap.removeValueForKey($0) } // pass 2: fill in the blanks for (key, frame) in keyMap { var keyView = self.generateKey() setupKey(keyView, key, frame) } } else { for (key, frame) in keyMap { if var keyView = self.pooledKey(key: key, model: self.model, frame: frame) { setupKey(keyView, key, frame) } } } } CATransaction.commit() } func updateKeyAppearance() { CATransaction.begin() CATransaction.setDisableActions(true) for (key, view) in self.modelToView { self.setAppearanceForKey(view, model: key, darkMode: self.darkMode, solidColorMode: self.solidColorMode) } CATransaction.commit() } // on fullReset, we update the keys with shapes, images, etc. as if from scratch; otherwise, just update the text // WARNING: if key cache is disabled, DO NOT CALL WITH fullReset MORE THAN ONCE func updateKeyCaps(fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { CATransaction.begin() CATransaction.setDisableActions(true) if fullReset { for (_, key) in self.modelToView { key.shape = nil if let imageKey = key as? ImageKey { // TODO: imageKey.image = nil } } } for (model, key) in self.modelToView { self.updateKeyCap(key, model: model, fullReset: fullReset, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } CATransaction.commit() } func updateKeyCap(key: KeyboardKey, model: Key, fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { if fullReset { // font size switch model.type { case Key.KeyType.ModeChange, Key.KeyType.Space, Key.KeyType.Return: key.label.adjustsFontSizeToFitWidth = true key.label.font = key.label.font.fontWithSize(16) default: key.label.font = key.label.font.fontWithSize(22) } // label inset switch model.type { case Key.KeyType.ModeChange: key.labelInset = 3 default: key.labelInset = 0 } // shapes switch model.type { case Key.KeyType.Shift: if key.shape == nil { let shiftShape = self.getShape(ShiftShape) key.shape = shiftShape } case Key.KeyType.Backspace: if key.shape == nil { let backspaceShape = self.getShape(BackspaceShape) key.shape = backspaceShape } case Key.KeyType.KeyboardChange: if key.shape == nil { let globeShape = self.getShape(GlobeShape) key.shape = globeShape } default: break } // images if model.type == Key.KeyType.Settings { if let imageKey = key as? ImageKey { if imageKey.image == nil { var gearImage = UIImage(named: "gear") var settingsImageView = UIImageView(image: gearImage) imageKey.image = settingsImageView } } } } if model.type == Key.KeyType.Shift { if key.shape == nil { let shiftShape = self.getShape(ShiftShape) key.shape = shiftShape } switch shiftState { case .Disabled: key.highlighted = false case .Enabled: key.highlighted = true case .Locked: key.highlighted = true } (key.shape as? ShiftShape)?.withLock = (shiftState == .Locked) } self.updateKeyCapText(key, model: model, uppercase: uppercase, characterUppercase: characterUppercase) } func updateKeyCapText(key: KeyboardKey, model: Key, uppercase: Bool, characterUppercase: Bool) { if model.type == .Character { key.text = model.keyCapForCase(characterUppercase) } else { key.text = model.keyCapForCase(uppercase) } } /////////////// // END CALLS // /////////////// func setAppearanceForKey(key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) { if model.type == Key.KeyType.Other { self.setAppearanceForOtherKey(key, model: model, darkMode: darkMode, solidColorMode: solidColorMode) } switch model.type { case Key.KeyType.Character, Key.KeyType.SpecialCharacter, Key.KeyType.Period: key.color = self.self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) } else { key.downColor = nil } key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.Space: key.color = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.Shift: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.downColor = (darkMode ? self.globalColors.darkModeShiftKeyDown : self.globalColors.lightModeRegularKey) key.textColor = self.globalColors.darkModeTextColor key.downTextColor = self.globalColors.lightModeTextColor case Key.KeyType.Backspace: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) // TODO: actually a bit different key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.textColor = self.globalColors.darkModeTextColor key.downTextColor = (darkMode ? nil : self.globalColors.lightModeTextColor) case Key.KeyType.ModeChange: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.downColor = nil key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.Return, Key.KeyType.KeyboardChange, Key.KeyType.Settings: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) // TODO: actually a bit different key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil default: break } key.popupColor = self.globalColors.popup(darkMode, solidColorMode: solidColorMode) key.underColor = (self.darkMode ? self.globalColors.darkModeUnderColor : self.globalColors.lightModeUnderColor) key.borderColor = (self.darkMode ? self.globalColors.darkModeBorderColor : self.globalColors.lightModeBorderColor) } func setAppearanceForOtherKey(key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) { /* override this to handle special keys */ } // TODO: avoid array copies // TODO: sizes stored not rounded? /////////////////////////// // KEY POOLING FUNCTIONS // /////////////////////////// // if pool is disabled, always returns a unique key view for the corresponding key model func pooledKey(key aKey: Key, model: Keyboard, frame: CGRect) -> KeyboardKey? { if !self.dynamicType.shouldPoolKeys { var p: Int! var r: Int! var k: Int! // TODO: O(N^2) in terms of total # of keys since pooledKey is called for each key, but probably doesn't matter var foundKey: Bool = false for (pp, page) in enumerate(model.pages) { for (rr, row) in enumerate(page.rows) { for (kk, key) in enumerate(row) { if key == aKey { p = pp r = rr k = kk foundKey = true } if foundKey { break } } if foundKey { break } } if foundKey { break } } let id = "p\(p)r\(r)k\(k)" if let key = self.nonPooledMap[id] { return key } else { let key = generateKey() self.nonPooledMap[id] = key return key } } else { if var keyArray = self.sizeToKeyMap[frame.size] { if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValueForKey(frame.size) } else { keyArray.removeLast() self.sizeToKeyMap[frame.size] = keyArray } return key } else { return nil } } else { return nil } } } func createNewKey() -> KeyboardKey { return ImageKey(vibrancy: nil) } // if pool is disabled, always generates a new key func generateKey() -> KeyboardKey { let createAndSetupNewKey = { () -> KeyboardKey in var keyView = self.createNewKey() keyView.enabled = true keyView.delegate = self self.superview.addSubview(keyView) self.keyPool.append(keyView) return keyView } if self.dynamicType.shouldPoolKeys { if !self.sizeToKeyMap.isEmpty { var (size, keyArray) = self.sizeToKeyMap[self.sizeToKeyMap.startIndex] if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValueForKey(size) } else { keyArray.removeLast() self.sizeToKeyMap[size] = keyArray } return key } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } // if pool is disabled, doesn't do anything func resetKeyPool() { if self.dynamicType.shouldPoolKeys { self.sizeToKeyMap.removeAll(keepCapacity: true) for key in self.keyPool { if var keyArray = self.sizeToKeyMap[key.frame.size] { keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } else { var keyArray = [KeyboardKey]() keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } key.hidden = true } } } // TODO: no support for more than one of the same shape // if pool disabled, always returns new shape func getShape(shapeClass: Shape.Type) -> Shape { let className = NSStringFromClass(shapeClass) if self.dynamicType.shouldPoolKeys { if let shape = self.shapePool[className] { return shape } else { var shape = shapeClass(frame: CGRectZero) self.shapePool[className] = shape return shape } } else { return shapeClass(frame: CGRectZero) } } ////////////////////// // LAYOUT FUNCTIONS // ////////////////////// func rounded(measurement: CGFloat) -> CGFloat { return round(measurement * UIScreen.mainScreen().scale) / UIScreen.mainScreen().scale } func generateKeyFrames(model: Keyboard, bounds: CGRect, page pageToLayout: Int) -> [Key:CGRect]? { if bounds.height == 0 || bounds.width == 0 { return nil } var keyMap = [Key:CGRect]() let isLandscape: Bool = { let boundsRatio = bounds.width / bounds.height return (boundsRatio >= self.layoutConstants.landscapeRatio) }() var sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(bounds.width)) let bottomEdge = sideEdges let normalKeyboardSize = bounds.width - CGFloat(2) * sideEdges let shrunkKeyboardSize = self.layoutConstants.keyboardShrunkSize(normalKeyboardSize) sideEdges += ((normalKeyboardSize - shrunkKeyboardSize) / CGFloat(2)) let topEdge: CGFloat = (isLandscape ? self.layoutConstants.topEdgeLandscape : self.layoutConstants.topEdgePortrait(bounds.width)) let rowGap: CGFloat = (isLandscape ? self.layoutConstants.rowGapLandscape : self.layoutConstants.rowGapPortrait(bounds.width)) let lastRowGap: CGFloat = (isLandscape ? rowGap : self.layoutConstants.rowGapPortraitLastRow(bounds.width)) let flexibleEndRowM = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) let flexibleEndRowC = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) let lastRowLeftSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth) let lastRowRightSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth) let lastRowKeyGap = (isLandscape ? self.layoutConstants.lastRowKeyGapLandscape(bounds.width) : self.layoutConstants.lastRowKeyGapPortrait) for (p, page) in enumerate(model.pages) { if p != pageToLayout { continue } let numRows = page.rows.count let mostKeysInRow: Int = { var currentMax: Int = 0 for (i, row) in enumerate(page.rows) { currentMax = max(currentMax, row.count) } return currentMax }() let rowGapTotal = CGFloat(numRows - 1 - 1) * rowGap + lastRowGap let keyGap: CGFloat = (isLandscape ? self.layoutConstants.keyGapLandscape(bounds.width, rowCharacterCount: mostKeysInRow) : self.layoutConstants.keyGapPortrait(bounds.width, rowCharacterCount: mostKeysInRow)) let keyHeight: CGFloat = { let totalGaps = bottomEdge + topEdge + rowGapTotal var returnHeight = (bounds.height - totalGaps) / CGFloat(numRows) return self.rounded(returnHeight) }() let letterKeyWidth: CGFloat = { let totalGaps = (sideEdges * CGFloat(2)) + (keyGap * CGFloat(mostKeysInRow - 1)) var returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow) return self.rounded(returnWidth) }() let processRow = { (row: [Key], frames: [CGRect], inout map: [Key:CGRect]) -> Void in assert(row.count == frames.count, "row and frames don't match") for (k, key) in enumerate(row) { map[key] = frames[k] } } for (r, row) in enumerate(page.rows) { let rowGapCurrentTotal = (r == page.rows.count - 1 ? rowGapTotal : CGFloat(r) * rowGap) let frame = CGRectMake(rounded(sideEdges), rounded(topEdge + (CGFloat(r) * keyHeight) + rowGapCurrentTotal), rounded(bounds.width - CGFloat(2) * sideEdges), rounded(keyHeight)) var frames: [CGRect]! // basic character row: only typable characters if self.characterRowHeuristic(row) { frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame) } // character row with side buttons: shift, backspace, etc. else if self.doubleSidedRowHeuristic(row) { frames = self.layoutCharacterWithSidesRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap) } // bottom row with things like space, return, etc. else { frames = self.layoutSpecialKeysRow(row, keyWidth: letterKeyWidth, gapWidth: lastRowKeyGap, leftSideRatio: lastRowLeftSideRatio, rightSideRatio: lastRowRightSideRatio, micButtonRatio: self.layoutConstants.micButtonPortraitWidthRatioToOtherSpecialButtons, isLandscape: isLandscape, frame: frame) } processRow(row, frames, &keyMap) } } return keyMap } func characterRowHeuristic(row: [Key]) -> Bool { return (row.count >= 1 && row[0].isCharacter) } func doubleSidedRowHeuristic(row: [Key]) -> Bool { return (row.count >= 3 && !row[0].isCharacter && row[1].isCharacter) } func layoutCharacterRow(row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, frame: CGRect) -> [CGRect] { var frames = [CGRect]() let keySpace = CGFloat(row.count) * keyWidth + CGFloat(row.count - 1) * gapWidth var actualGapWidth = gapWidth var sideSpace = (frame.width - keySpace) / CGFloat(2) // TODO: port this to the other layout functions // avoiding rounding errors if sideSpace < 0 { sideSpace = 0 actualGapWidth = (frame.width - (CGFloat(row.count) * keyWidth)) / CGFloat(row.count - 1) } var currentOrigin = frame.origin.x + sideSpace for (k, key) in enumerate(row) { let roundedOrigin = rounded(currentOrigin) // avoiding rounding errors if roundedOrigin + keyWidth > frame.origin.x + frame.width { frames.append(CGRectMake(rounded(frame.origin.x + frame.width - keyWidth), frame.origin.y, keyWidth, frame.height)) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, keyWidth, frame.height)) } currentOrigin += (keyWidth + actualGapWidth) } return frames } // TODO: pass in actual widths instead func layoutCharacterWithSidesRow(row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] { var frames = [CGRect]() let standardFullKeyCount = Int(self.layoutConstants.keyCompressedThreshhold) - 1 let standardGap = (isLandscape ? self.layoutConstants.keyGapLandscape : self.layoutConstants.keyGapPortrait)(frame.width, rowCharacterCount: standardFullKeyCount) let sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(frame.width)) var standardKeyWidth = (frame.width - sideEdges - (standardGap * CGFloat(standardFullKeyCount - 1)) - sideEdges) standardKeyWidth /= CGFloat(standardFullKeyCount) let standardKeyCount = self.layoutConstants.flexibleEndRowMinimumStandardCharacterWidth let standardWidth = CGFloat(standardKeyWidth * standardKeyCount + standardGap * (standardKeyCount - 1)) let currentWidth = CGFloat(row.count - 2) * keyWidth + CGFloat(row.count - 3) * keyGap let isStandardWidth = (currentWidth < standardWidth) let actualWidth = (isStandardWidth ? standardWidth : currentWidth) let actualGap = (isStandardWidth ? standardGap : keyGap) let actualKeyWidth = (actualWidth - CGFloat(row.count - 3) * actualGap) / CGFloat(row.count - 2) let sideSpace = (frame.width - actualWidth) / CGFloat(2) let m = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) let c = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) var specialCharacterWidth = sideSpace * m + c specialCharacterWidth = max(specialCharacterWidth, keyWidth) specialCharacterWidth = rounded(specialCharacterWidth) let specialCharacterGap = sideSpace - specialCharacterWidth var currentOrigin = frame.origin.x for (k, key) in enumerate(row) { if k == 0 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, specialCharacterWidth, frame.height)) currentOrigin += (specialCharacterWidth + specialCharacterGap) } else if k == row.count - 1 { currentOrigin += specialCharacterGap frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, specialCharacterWidth, frame.height)) currentOrigin += specialCharacterWidth } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, actualKeyWidth, frame.height)) if k == row.count - 2 { currentOrigin += (actualKeyWidth) } else { currentOrigin += (actualKeyWidth + keyGap) } } } return frames } func layoutSpecialKeysRow(row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, leftSideRatio: CGFloat, rightSideRatio: CGFloat, micButtonRatio: CGFloat, isLandscape: Bool, frame: CGRect) -> [CGRect] { var frames = [CGRect]() var keysBeforeSpace = 0 var keysAfterSpace = 0 var reachedSpace = false for (k, key) in enumerate(row) { if key.type == Key.KeyType.Space { reachedSpace = true } else { if !reachedSpace { keysBeforeSpace += 1 } else { keysAfterSpace += 1 } } } assert(keysBeforeSpace <= 3, "invalid number of keys before space (only max 3 currently supported)") assert(keysAfterSpace == 1, "invalid number of keys after space (only default 1 currently supported)") let hasButtonInMicButtonPosition = (keysBeforeSpace == 3) var leftSideAreaWidth = frame.width * leftSideRatio let rightSideAreaWidth = frame.width * rightSideRatio var leftButtonWidth = (leftSideAreaWidth - (gapWidth * CGFloat(2 - 1))) / CGFloat(2) leftButtonWidth = rounded(leftButtonWidth) var rightButtonWidth = (rightSideAreaWidth - (gapWidth * CGFloat(keysAfterSpace - 1))) / CGFloat(keysAfterSpace) rightButtonWidth = rounded(rightButtonWidth) let micButtonWidth = (isLandscape ? leftButtonWidth : leftButtonWidth * micButtonRatio) // special case for mic button if hasButtonInMicButtonPosition { leftSideAreaWidth = leftSideAreaWidth + gapWidth + micButtonWidth } var spaceWidth = frame.width - leftSideAreaWidth - rightSideAreaWidth - gapWidth * CGFloat(2) spaceWidth = rounded(spaceWidth) var currentOrigin = frame.origin.x var beforeSpace: Bool = true for (k, key) in enumerate(row) { if key.type == Key.KeyType.Space { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, spaceWidth, frame.height)) currentOrigin += (spaceWidth + gapWidth) beforeSpace = false } else if beforeSpace { if hasButtonInMicButtonPosition && k == 2 { //mic button position frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, micButtonWidth, frame.height)) currentOrigin += (micButtonWidth + gapWidth) } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, leftButtonWidth, frame.height)) currentOrigin += (leftButtonWidth + gapWidth) } } else { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, rightButtonWidth, frame.height)) currentOrigin += (rightButtonWidth + gapWidth) } } return frames } //////////////// // END LAYOUT // //////////////// func frameForPopup(key: KeyboardKey, direction: Direction) -> CGRect { let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale) let totalHeight = self.layoutConstants.popupTotalHeight(actualScreenWidth) let popupWidth = key.bounds.width + self.layoutConstants.popupWidthIncrement let popupHeight = totalHeight - self.layoutConstants.popupGap - key.bounds.height let popupCenterY = 0 return CGRectMake((key.bounds.width - popupWidth) / CGFloat(2), -popupHeight - self.layoutConstants.popupGap, popupWidth, popupHeight) } func willShowPopup(key: KeyboardKey, direction: Direction) { // TODO: actual numbers, not standins if let popup = key.popup { // TODO: total hack let actualSuperview = (self.superview.superview != nil ? self.superview.superview! : self.superview) var localFrame = actualSuperview.convertRect(popup.frame, fromView: popup.superview) if localFrame.origin.y < 3 { localFrame.origin.y = 3 key.background.attached = Direction.Down key.connector?.startDir = Direction.Down key.background.hideDirectionIsOpposite = true } else { // TODO: this needs to be reset somewhere key.background.hideDirectionIsOpposite = false } if localFrame.origin.x < 3 { localFrame.origin.x = key.frame.origin.x } if localFrame.origin.x + localFrame.width > superview.bounds.width - 3 { localFrame.origin.x = key.frame.origin.x + key.frame.width - localFrame.width } popup.frame = actualSuperview.convertRect(localFrame, toView: popup.superview) } } func willHidePopup(key: KeyboardKey) { } }
bsd-3-clause
5a29a76b68c340b0adc4a9d69c2525ec
41.814639
313
0.589409
5.368936
false
false
false
false
weyert/Whisper
Demo/WhisperDemo/WhisperDemo/ModalViewController.swift
1
2161
import UIKit import Whisper class ModalViewController: UIViewController { lazy var doneButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem( barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "dismissModalViewController") return button }() lazy var disclosureButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "presentDisclosure:", forControlEvents: .TouchUpInside) button.setTitle("Disclosure", forState: .Normal) button.setTitleColor(UIColor.grayColor(), forState: .Normal) button.layer.borderColor = UIColor.grayColor().CGColor button.layer.borderWidth = 1.5 button.layer.cornerRadius = 7.5 return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() navigationItem.title = "Secret View" navigationItem.rightBarButtonItem = doneButton view.addSubview(disclosureButton) setUpFrames() } // MARK: - Orientation changes override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { setUpFrames() } // MARK: - Actions // MARK: Disclosure button pressed func presentDisclosure(button: UIButton) { var secret = Secret(title: "Secret revealed!") secret.textColor = UIColor.whiteColor() secret.backgroundColor = UIColor.brownColor() Disclosure(secret, to: tabBarController!, completion: { print("The disclosure was silent") }) } // MARK: Done button pressed func dismissModalViewController() { navigationController?.dismissViewControllerAnimated(true, completion: nil) } // MARK: - Configuration func setUpFrames() { let totalSize = UIScreen.mainScreen().bounds let availableHeight = totalSize.height - navigationController!.navigationBar.frame.size.height - tabBarController!.tabBar.frame.size.height disclosureButton.frame = CGRect(x: 50, y: availableHeight / 2, width: totalSize.width - 100, height: 50) } }
mit
3c27823b6d6d4d6faefcdd6989dd9b59
25.353659
143
0.691809
5.207229
false
false
false
false
zalando/zmon-ios
zmon/controllers/ObservedTeamsVC.swift
1
3650
// // ObservedTeamsVC.swift // zmon // // Created by Andrej Kincel on 16/12/15. // Copyright © 2015 Zalando Tech. All rights reserved. // import UIKit import SVProgressHUD class ObservedTeamsVC: BaseVC, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { @IBOutlet weak var table: UITableView! let searchController = UISearchController(searchResultsController: nil) let zmonTeamService: ZmonTeamService = ZmonTeamService() var teamList: [String] = [] var filteredTeamList = [String]() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "ObservedTeams".localized self.setupSearch() self.table.dataSource = self self.table.delegate = self SVProgressHUD.show() zmonTeamService.listTeams { (teams: [String]) -> () in SVProgressHUD.dismiss() self.teamList = teams self.table.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK:- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearching() ? self.filteredTeamList.count : self.teamList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let teamName = isSearching() ? self.filteredTeamList[indexPath.row] : self.teamList[indexPath.row] let cell: TeamCell = tableView.dequeueReusableCellWithIdentifier("TeamCell") as! TeamCell cell.configureFor(name: teamName) if let team = Team.findByName(name: teamName) { if team.observed { tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) } } return cell } // MARK:- UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let teamName = isSearching() ? filteredTeamList[indexPath.row] : teamList[indexPath.row] let team: Team = Team(name: teamName, observed: true) team.save() } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let teamName = isSearching() ? filteredTeamList[indexPath.row] : teamList[indexPath.row] let team: Team = Team(name: teamName, observed: false) team.save() } //MARK: Searching and UISearchResultsUpdating func setupSearch() { searchController.searchResultsUpdater = self searchController.searchBar.barStyle = .Black searchController.searchBar.keyboardAppearance = .Dark searchController.searchBar.tintColor = UIColor.whiteColor() searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true table.tableHeaderView = searchController.searchBar } func isSearching() -> Bool { return searchController.active && searchController.searchBar.text != "" } func updateSearchResultsForSearchController(searchController: UISearchController) { filterTeamsForSearchText(searchController.searchBar.text!) } func filterTeamsForSearchText(searchText: String, scope: String = "All") { filteredTeamList = teamList.filter { team in return team.lowercaseString.containsString(searchText.lowercaseString) } table.reloadData() } }
mit
5dfb630e321b0e916bfbb81eec713ee4
34.427184
109
0.671143
5.382006
false
false
false
false
astrokin/EZSwiftExtensions
EZSwiftExtensionsTests/CGPointTests.swift
3
3395
// // CGPointTests.swift // EZSwiftExtensions // // Created by Sanyal, Arunav on 10/29/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest @testable import EZSwiftExtensions class CGPointTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testCGVectorConstructorTest() { let cgVector = CGVector(dx: 0.1, dy: 0.3) let cgPointFromVector = CGPoint(vector: cgVector) XCTAssertEqual(cgPointFromVector, CGPoint(x: 0.1, y: 0.3)) } func testAngleConstructorTest() { let cgAngle = CGFloat(0.5) let cgPointFromAngle = CGPoint(angle: cgAngle) XCTAssertEqual(cgPointFromAngle, CGPoint(x: cos(0.5), y: sin(0.5))) } func testPlus() { let p1 = CGPoint(x: 1, y: 2) let p2 = CGPoint(x: 3, y: 4) XCTAssertEqual(p1 + p2, CGPoint(x: 4, y: 6)) let p = CGPoint(x: 1, y: 1) let oppositeP = CGPoint(x: -1, y: -1) XCTAssertEqual(p + oppositeP, CGPoint(x: 0, y: 0)) } func testMinus() { let p1 = CGPoint(x: 1, y: 2) let p2 = CGPoint(x: 3, y: 4) XCTAssertEqual(p2 - p1, CGPoint(x:2, y:2)) XCTAssertEqual(p1 - p1, CGPoint.zero) } func testScalarProduct() { let p1 = CGPoint(x:1, y:2) XCTAssertEqual(p1 * 3.0, CGPoint(x:3.0, y:6.0)) XCTAssertEqual(CGPoint.zero * 10.0, CGPoint.zero) } func testLinearInterpolation() { let p1 = CGPoint(x:0, y:0) let p2 = CGPoint(x:1, y:1) let midPoint = CGPoint.linearInterpolation(startPoint: p1, endPoint: p2, interpolationParam: 0.5) XCTAssertEqual(midPoint, CGPoint(x:0.5, y:0.5)) let quarterPoint = CGPoint.linearInterpolation(startPoint: p1, endPoint: p2, interpolationParam: 0.25) XCTAssertEqual(quarterPoint, CGPoint(x:0.25, y:0.25)) let midPointBetweenP1AndItself = CGPoint.linearInterpolation(startPoint: p1, endPoint: p1, interpolationParam: 0.5) XCTAssertEqual(midPointBetweenP1AndItself, p1) } func testDistance() { let p1 = CGPoint(x: 3, y: 4) let p2 = CGPoint(x: 0, y: 0) XCTAssertEqual(CGPoint.distance(from: p1, to: p2), 5) XCTAssertEqual(CGPoint.distance(from: p2, to: p2), 0) } func testNormalized() { let p = CGPoint(x:3, y:4) let pNorm = p.normalized() XCTAssertEqual(pNorm, CGPoint(x:0.6, y:0.8)) XCTAssertEqual(pNorm.normalized(), pNorm) } func testAngle() { let p = CGPoint(x:1, y:1) XCTAssertEqual(p.angle, .pi/4) let onXAxisP = CGPoint(x:1, y:0) XCTAssertEqual(onXAxisP.angle, 0) let onYAxisP = CGPoint(x:0, y:1) XCTAssertEqual(onYAxisP.angle, .pi/2) let onNegativeXAxisP = CGPoint(x:-1, y:0) XCTAssertEqual(onNegativeXAxisP.angle, .pi) } func testDotProduct() { let p = CGPoint(x:1, y:2) let q = CGPoint(x:3, y:4) XCTAssertEqual(CGPoint.dotProduct(this: p, that: q), 11) let zero = CGPoint(x:0, y:0) XCTAssertEqual(CGPoint.dotProduct(this: p, that: zero), 0) } }
mit
71099ac3199ff2c2b713379fbb9bca03
28.008547
123
0.567177
3.50258
false
true
false
false
swift-lang/swift-t
turbine/code/export/files.swift
1
2991
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * 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 */ // FILES.SWIFT /* We use temporary variables named l:t for "library-temporary". */ #ifndef FILES_SWIFT #define FILES_SWIFT // Same as input file, but pretend is impure so it won't be cached @implements=uncached_input_file (file f) unsafe_uncached_input_file(string filename) "turbine" "0.0.2" "input_file"; @pure (file t[]) glob(string s) "turbine" "0.0.2" "glob"; @pure @dispatch=WORKER (string t) read(file f) "turbine" "0.0.2" "file_read" [ "set <<t>> [ turbine::file_read_local <<f>> ]" ]; @pure @dispatch=WORKER (file t) write(string s) "turbine" "0.0.2" "file_write" [ "turbine::file_write_local <<t>> <<s>>" ]; @pure (string t) file_type(file f) "turbine" "0.0.2" [ "set <<t>> [ file type [ lindex <<f>> 0 ] ]" ]; @pure (string t) file_type_string(string f) "turbine" "1.0" [ "set <<t>> [ file type <<f>> ]" ]; (boolean o) file_exists(string f) "turbine" "0.1" [ "set <<o>> [ file exists <<f>> ]" ]; (int o) file_mtime(string f) "turbine" "0.1" [ "set <<o>> [ turbine::file_mtime_impl <<f>> ]" ]; @pure (string s[]) file_lines(file f, string comment="#") "turbine" "0.1" [ "set <<s>> [ turbine::file_lines_impl <<f>> <<comment>> ] " ]; @pure (string d) dirname_string(string p) "turbine" "0.0" [ "set <<d>> [ file dirname <<p>> ]" ]; @pure (string d) dirname(file p) "turbine" "0.0" [ "set <<d>> [ file dirname <<p>> ]" ]; @pure (string f) basename_string(string p) "turbine" "0.0" [ "set <<f>> [ file tail <<p>> ]" ]; @pure (string f) basename(file p) "turbine" "0.0" [ "set l:t [ lindex <<p>> 0 ] ; set <<f>> [ file tail ${l:t} ]" ]; @pure (string f) rootname_string(string p) "turbine" "0.0" [ "set <<f>> [ file rootname <<p>> ]" ]; @pure (string f) rootname(file p) "turbine" "0.0" [ "set l:t [ lindex <<p>> 0 ] ; set <<f>> [ file rootname ${l:t} ]" ]; @pure (string f) extension_string(string p) "turbine" "0.0" [ "set <<f>> [ file extension <<p>> ]" ]; @pure (string f) extension(file p) "turbine" "0.0" [ "set l:t [ lindex <<p>> 0 ] ; set <<f>> [ file extension ${l:t} ]" ]; (file o) write_array_string(string a[], int chunk) "turbine" "1.0" "write_array_string"; (file o) write_array_string_ordered(string a[]) "turbine" "1.0" "write_array_string_ordered"; (string s) mktemp_string() "turbine" "1.0" "mktemp_string"; (file o) mktemp() { o = input(mktemp_string()); } #endif // FILES_SWIFT
apache-2.0
a796c6193854d85867c4f1c5cd0d0b55
22.738095
84
0.621866
2.734004
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/GigagroupLanding.swift
1
3805
// // GigagroupLanding.swift // Telegram // // Created by Mikhail Filimonov on 15.02.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import SwiftSignalKit import TGUIKit import TelegramCore import Postbox private final class Arguments { let context: AccountContext init(context: AccountContext) { self.context = context } } private struct State : Equatable { } private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId:Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("sticker"), equatable: nil, comparable: nil, item: { initialSize, stableId in return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: .gigagroup, text: .init()) })) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("features"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralBlockTextRowItem(initialSize, stableId: stableId, viewType: .singleItem, text: strings().broadcastGroupsIntroText, font: .normal(.text)) })) index += 1 // entries entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func GigagroupLandingController(context: AccountContext, peerId: PeerId) -> InputDataModalController { var close:(()->Void)? = nil let actionsDisposable = DisposableSet() let initialState = State() let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } let arguments = Arguments(context: context) let signal = statePromise.get() |> map { state in return InputDataSignalValue(entries: entries(state, arguments: arguments)) } let controller = InputDataController(dataSignal: signal, title: strings().broadcastGroupsIntroTitle) controller.onDeinit = { actionsDisposable.dispose() } controller.validateData = { _ in confirm(for: context.window, header: strings().broadcastGroupsConfirmationAlertTitle, information: strings().broadcastGroupsConfirmationAlertText, okTitle: strings().broadcastGroupsConfirmationAlertConvert, successHandler: { _ in _ = showModalProgress(signal: convertGroupToGigagroup(account: context.account, peerId: peerId), for: context.window).start(error: { error in switch error { case .generic: alert(for: context.window, info: strings().unknownError) } }, completed: { showModalText(for: context.window, text: strings().broadcastGroupsSuccess) close?() }) }, cancelHandler: { }) return .none } let modalInteractions = ModalInteractions(acceptTitle: strings().broadcastGroupsConvert, accept: { [weak controller] in _ = controller?.returnKeyAction() }, drawBorder: true, height: 50, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in modalController?.close() }) close = { [weak modalController] in modalController?.modal?.close() } return modalController }
gpl-2.0
a031461388089c86824e6f277ab5dc56
30.438017
237
0.679811
4.86445
false
false
false
false
NOTIFIT/notifit-ios-swift-sdk
Example/Tests/Tests.swift
1
1180
// https://github.com/Quick/Quick import Quick import Nimble import NOTIFIT_Swift class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
6ef03bcdd2dd52689728bb172b8bd4d2
22.48
63
0.364566
5.410138
false
false
false
false
tejasranade/KinveyHealth
SportShop/AppDelegate.swift
1
3351
// // AppDelegate.swift // SportShop // // Created by Tejas on 1/25/17. // Copyright © 2017 Kinvey. All rights reserved. // import UIKit import Kinvey import Material import FBSDKCoreKit import UIColor_Hex_Swift extension UIStoryboard { class func viewController(identifier: String) -> UIViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var drawerController: AppNavigationDrawerController? lazy var leftViewController: LeftViewController = { return UIStoryboard.viewController(identifier: "LeftViewController") as! LeftViewController }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { //UINavigationBar.appearance().barTintColor = UIColor.darkGray //UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] //UINavigationBar.appearance().tintColor = UIColor("#652111") initializeKinvey() // FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) // // FBSDKProfile.enableUpdates(onAccessTokenChange: true) window = UIWindow(frame: Screen.bounds) let rootViewController = UIStoryboard.viewController(identifier: "DashboardController") drawerController = AppNavigationDrawerController(rootViewController: UINavigationController(rootViewController: rootViewController), leftViewController: leftViewController) window!.rootViewController = drawerController window!.makeKeyAndVisible() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) return handled } func initializeKinvey(){ Kinvey.sharedClient.initialize(appKey: "kid_B1Vak6Ey-", appSecret: "aa9a2a42b7d741bba30bb94b599a5f0b", apiHostName: URL(string: "https://kvy-us2-baas.kinvey.com/")! ) Kinvey.sharedClient.logNetworkEnabled = true Kinvey.sharedClient.userType = HealthUser.self } } //extension Client { // func isNamedUser () -> Bool { // return activeUser != nil && activeUser?.username != "Guest" // } // // func realUserName() -> String? { // if let user = activeUser as? HealthUser { // return user.firstname // } // return activeUser?.username // } //} extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } } extension UIViewController { @IBAction func leftButtonTapped(_ sender: Any) { let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.drawerController?.toggleLeftView() } }
apache-2.0
b941da9b21312eac524c00285cdc08b6
31.843137
172
0.674627
5.234375
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Store/Sources/V3Store/CD_Models/CD_Website.swift
1
2297
// // Created by Jeffrey Bergier on 2020/11/23. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 CoreData import V3Model @objc(CD_Website) internal class CD_Website: CD_Base { internal class override var entityName: String { "CD_Website" } internal class var request: NSFetchRequest<CD_Website> { NSFetchRequest<CD_Website>(entityName: self.entityName) } override func willSave() { super.willSave() // Validate Title if let title = self.cd_title, title.trimmed == nil { self.cd_title = nil } // Validate Thumbnail Size if let thumb = self.cd_thumbnail, thumb.count > Website.maxSize { self.cd_thumbnail = nil } } } extension Website { internal init(_ cd: CD_Website) { self.init(id: .init(cd.objectID), isArchived: cd.cd_isArchived, originalURL: cd.cd_originalURL, resolvedURL: cd.cd_resolvedURL, title: cd.cd_title, thumbnail: cd.cd_thumbnail, dateCreated: cd.cd_dateCreated, dateModified: cd.cd_dateModified) } }
mit
9d13117bc908de2a483a550c1227755e
35.460317
82
0.661733
4.293458
false
false
false
false
linbin00303/Dotadog
DotaDog/DotaDog/Classes/Common/DDogHeroesAndItemsDataSync.swift
1
12604
// // DDogHeroesAndItemsDataSync.swift // DotaDog // // Created by 林彬 on 16/5/28. // Copyright © 2016年 linbin. All rights reserved. // // 同步获取数据 import UIKit import Foundation class DDogHeroesAndItemsDataSync: NSObject { private lazy var heroesInfo : NSMutableDictionary = { let heroesInfo = NSMutableDictionary() return heroesInfo }() private var heroesNameEN : NSMutableArray = { let heroesNameEN = NSMutableArray() return heroesNameEN }() private var heroesNameZH : NSMutableArray = { let heroesNameZH = NSMutableArray() return heroesNameZH }() private var abilitys : NSMutableDictionary = { let abilitys = NSMutableDictionary() return abilitys }() private var items : NSMutableDictionary = { let items = NSMutableDictionary() return items }() // 单例 static let shareInstance = DDogHeroesAndItemsDataSync() // MARK:- 从网络获取英雄信息 func handleHeroesInfoData(isFinish : (results : Bool) -> ()){ //创建NSURL对象 var urlString:String="http://www.dota2.com/jsfeed/heropickerdata?v=3468515b3468515&l=schinese" var url:NSURL! = NSURL(string:urlString) //创建请求对象 let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.timeoutInterval = 10 let session = NSURLSession.sharedSession() var semaphore = dispatch_semaphore_create(0) var dataTask = session.dataTaskWithRequest(request,completionHandler: {[weak self](data, response, error) -> Void in if error != nil{ print(error?.code) print(error?.description) }else{ let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary self?.heroesInfo = dict! // print(self.heroesInfo) } dispatch_semaphore_signal(semaphore) }) as NSURLSessionTask dataTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) // print("heroesInfo数据加载完毕!") //--------------------------------------------------------------------- urlString = "http://www.dota2.com/jsfeed/abilitydata?v=3468515b3468515&l=schinese" url = NSURL(string:urlString) //创建请求对象 let request1 : NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "GET" request1.timeoutInterval = 10 semaphore = dispatch_semaphore_create(0) dataTask = session.dataTaskWithRequest(request1,completionHandler: {[weak self](data, response, error) -> Void in if error != nil{ // print(error?.code) // print(error?.description) }else{ let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary self?.abilitys = dict!["abilitydata"] as! NSMutableDictionary // print(self.abilitys) } dispatch_semaphore_signal(semaphore) }) as NSURLSessionTask //使用resume方法启动任务 dataTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) print("abilitys数据加载完毕!") //--------------------------------------------------------------------- urlString = "https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=75571F3D1597EA1E8E287E127F7C563F&language=en" url = NSURL(string:urlString) let request2 : NSMutableURLRequest = NSMutableURLRequest(URL: url) request2.HTTPMethod = "GET" request2.timeoutInterval = 10 semaphore = dispatch_semaphore_create(0) dataTask = session.dataTaskWithRequest(request2,completionHandler: {[weak self](data, response, error) -> Void in if error != nil{ // print(error?.code) // print(error?.description) }else{ let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary self?.heroesNameEN = dict!["result"]!["heroes"] as! NSMutableArray // print(self.heroesNameEN) } dispatch_semaphore_signal(semaphore) }) as NSURLSessionTask dataTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) print("heroesNameEN数据加载完毕!") //--------------------------------------------------------------------- urlString = "https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=75571F3D1597EA1E8E287E127F7C563F&language=Zh" url = NSURL(string:urlString) let request3 : NSMutableURLRequest = NSMutableURLRequest(URL: url) request3.HTTPMethod = "GET" request3.timeoutInterval = 10 semaphore = dispatch_semaphore_create(0) dataTask = session.dataTaskWithRequest(request3,completionHandler: {[weak self](data, response, error) -> Void in if error != nil{ // print(error?.code) // print(error?.description) }else{ let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary self?.heroesNameZH = dict!["result"]!["heroes"] as! NSMutableArray } dispatch_semaphore_signal(semaphore) }) as NSURLSessionTask dataTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) // print("heroesNameZH数据加载完毕!") isFinish(results: true) // 把英雄数据添加到数据库中 saveHeroesInfoIntoSqlite { (results) in } // 把物品数据添加到数据库中 saveAbilitysInfoIntoSqlite { (results) in } } // MARK:- 从网络获取物品信息 func handleItemsInfoData(isFinish : (results : Bool) -> ()){ //--------------------------------------------------------------------- let urlString = "http://www.dota2.com/jsfeed/heropediadata?feeds=itemdata&v=21201034030358593&l=schinese" let url = NSURL(string:urlString) let request4 : NSMutableURLRequest = NSMutableURLRequest(URL: url!) request4.HTTPMethod = "GET" request4.timeoutInterval = 10 let semaphore = dispatch_semaphore_create(0) let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request4,completionHandler: {[weak self](data, response, error) -> Void in if error != nil{ // print(error?.code) // print(error?.description) }else{ let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary self?.items = dict!["itemdata"] as! NSMutableDictionary } dispatch_semaphore_signal(semaphore) }) as NSURLSessionTask dataTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) // print("ItemsInfo数据加载完毕!") isFinish(results: true) // 把物品信息添加到数据库中 saveItemsInfoIntoSqlite { (results) in } } } // MARK:- 数据库操作 extension DDogHeroesAndItemsDataSync { func saveHeroesInfoIntoSqlite(isFinish : (results : Bool) -> ()){ // 创建表 DDogFMDBTool.shareInstance.update_createHeroesTable() // 获取数据 let count = self.heroesNameEN.count var id = 0 var localized_name = "" var name_en = "" var name_zh = "" var tempStr : String = "" var atk = "" var bio = "" var roles : NSArray = [] var data : NSData = NSData() for i in 0..<count { id = heroesNameEN[i]["id"] as! Int localized_name = heroesNameEN[i]["localized_name"] as! String // 做截取处理 tempStr = heroesNameEN[i]["name"] as! String let endIndex = tempStr.startIndex.advancedBy(14) name_en = tempStr.substringFromIndex(endIndex) name_zh = heroesInfo[name_en]!["name"] as! String atk = heroesInfo[name_en]!["atk_l"] as! String bio = heroesInfo[name_en]!["bio"] as! String // 数组,转换为NSData存储 roles = heroesInfo[name_en]!["roles_l"] as! NSArray data = NSKeyedArchiver.archivedDataWithRootObject(roles) // let image = UIImage(named: "iconPlace") // let imageData = UIImagePNGRepresentation(image!)! let arr = [id,localized_name,name_en,name_zh,atk,bio,data] let sql = "INSERT INTO hero(id, localized_name, name_en, name_zh, atk, bio, roles) VALUES(?, ?, ?, ?, ?, ? ,?)" DDogFMDBTool.shareInstance.update_insertHeroData(sql, objs: arr) } } func saveAbilitysInfoIntoSqlite(isFinish : (results : Bool) -> ()){ // 创建表 DDogFMDBTool.shareInstance.update_createAbilitysTable() var ability = "" var tempDict = NSDictionary() var affects = "" var attrib = "" var cmb = "" var desc = "" var dname = "" var hurl = "" var lore = "" var notes = "" for key in abilitys.allKeys { ability = key as! String tempDict = abilitys[ability] as! NSDictionary affects = tempDict["affects"] as! String attrib = tempDict["attrib"] as! String cmb = tempDict["cmb"] as! String desc = tempDict["desc"] as! String dname = tempDict["dname"] as! String hurl = (tempDict["hurl"] as! String).lowercaseString.stringByReplacingOccurrencesOfString("_", withString: "").stringByReplacingOccurrencesOfString("-", withString: "").stringByReplacingOccurrencesOfString("'", withString: "") lore = tempDict["lore"] as! String notes = tempDict["notes"] as! String let arr = [ability,affects,attrib,cmb,desc,dname,hurl,lore,notes] let sql = "INSERT INTO ability(ability,affects, attrib, cmb, desc, dname, hurl, lore, notes) VALUES(?,?, ?, ?, ?, ?, ? ,? ,?)" DDogFMDBTool.shareInstance.update_insertAbilitysData(sql, objs: arr) } } func saveItemsInfoIntoSqlite(isFinish : (results : Bool) -> ()){ // 创建表 DDogFMDBTool.shareInstance.update_createItemsTable() var name = "" var tempDict = NSDictionary() var id = 0 var dname = "" var img = "" var cost = 0 var desc = "" var notes = "" var lore = "" var created = false for key in items.allKeys { name = key as! String tempDict = items[name] as! NSDictionary dname = tempDict["dname"] as! String img = tempDict["img"] as! String desc = tempDict["desc"] as! String cost = tempDict["cost"] as! Int id = tempDict["id"] as! Int notes = tempDict["notes"] as! String lore = tempDict["lore"] as! String created = tempDict["created"] as! Bool let arr = [id,name,dname,img,cost,desc,notes,lore,created] let sql = "INSERT INTO items(id, name, dname, img, cost, desc, notes, lore, created) VALUES(?, ?, ?, ?, ?, ? ,? ,? ,?)" DDogFMDBTool.shareInstance.update_insertItemsData(sql,objs: arr as [AnyObject]) } } }
mit
be9885977dce4de07776e2b638b6d644
35.592262
238
0.553152
4.957661
false
false
false
false
SwiftKidz/Slip
Tests/Core/BlockFlowTests.swift
1
2577
/* MIT License Copyright (c) 2016 SwiftKidz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest import Slip class BlockFlowTests: XCTestCase { func testQueues() { let queue = DispatchQueue(label: "Queue", attributes: .concurrent) let key = DispatchSpecificKey<String>() queue.setSpecific(key: key, value: "Concurrent") print(queue.getSpecific(key: key) ?? "Nothing") } func testFunctionality() { let expectation = self.expectation(description: name ?? "Test") let blocks: [BlockFlowApi.RunBlock] = [Int](0..<TestConfig.operationNumber).map { n in return { (f: BlockOp, i: Int, r: Any?) in f.finish(i) } } let flow = BlockFlow<Int>(runBlocks: blocks, limit: 10) .onFinish { state, result in // XCTAssert(state == State.finished(_)) XCTAssertNotNil(result.value) XCTAssert(result.value?.count == TestConfig.operationNumber) expectation.fulfill() } flow.onCancel { XCTFail() }.onError { _ in XCTFail() }.start() waitForExpectations(timeout: TestConfig.timeout, handler: nil) } func testNoBlocksFunctionality() { let expectation = self.expectation(description: name ?? "Test") let blocks = BlockFlow<Int>(runBlocks: []) .onFinish { state, result in expectation.fulfill() } blocks.start() waitForExpectations(timeout: TestConfig.timeout, handler: nil) } }
mit
1c036f37f6263e501f2a8f00f44372ed
33.824324
94
0.670547
4.676951
false
true
false
false
Witcast/witcast-ios
Pods/PullToRefreshKit/Source/Classes/PullToRefresh.swift
1
10208
// // PullToRefreshKit.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/11. // I refer a lot logic for MJRefresh https://github.com/CoderMJLee/MJRefresh ,thanks to this lib and all contributors. // Copyright © 2016年 Leo. All rights reserved. import Foundation import UIKit @objc public enum RefreshResult:Int{ /** * 刷新成功 */ case success = 200 /** * 刷新失败 */ case failure = 400 /** * 默认状态 */ case none = 0 } @objc public protocol RefreshableHeader:class{ /** 在刷新状态的时候,距离顶部的距离 */ func heightForRefreshingState()->CGFloat /** 进入刷新状态的回调,在这里将视图调整为刷新中 */ func didBeginRefreshingState() /** 刷新结束,将要进行隐藏的动画,一般在这里告诉用户刷新的结果 - parameter result: 刷新结果 */ func didBeginEndRefershingAnimation(_ result:RefreshResult) /** 刷新结束,隐藏的动画结束,一般在这里把视图隐藏,各个参数恢复到最初状态 - parameter result: 刷新结果 */ func didCompleteEndRefershingAnimation(_ result:RefreshResult) /** 状态改变 - parameter newState: 新的状态 - parameter oldState: 老得状态 */ @objc optional func stateDidChanged(_ oldState:RefreshHeaderState, newState:RefreshHeaderState) /** 触发刷新的距离,可选,如果没有实现,则默认触发刷新的距离就是 heightForRefreshingState */ @objc optional func heightForFireRefreshing()->CGFloat /** 不在刷新状态的时候,百分比回调,在这里你根据百分比来动态的调整你的刷新视图 - parameter percent: 拖拽的百分比,比如一共距离是100,那么拖拽10的时候,percent就是0.1 */ @objc optional func percentUpdateDuringScrolling(_ percent:CGFloat) /** 刷新结束,隐藏header的时间间隔,默认0.4s */ @objc optional func durationWhenEndRefreshing()->Double } @objc public protocol RefreshableFooter:class{ /** 触发动作的距离,对于header/footer来讲,就是视图的高度;对于left/right来讲,就是视图的宽度 */ func heightForRefreshingState()->CGFloat /** 不需要下拉加载更多的回调 */ func didUpdateToNoMoreData() /** 重新设置到常态的回调 */ func didResetToDefault() /** 结束刷新的回调 */ func didEndRefreshing() /** 已经开始执行刷新逻辑,在一次刷新中,只会调用一次 */ func didBeginRefreshing() /** 当Scroll触发刷新,这个方法返回是否需要刷新 */ func shouldBeginRefreshingWhenScroll()->Bool } public protocol RefreshableLeftRight:class{ /** 触发动作的距离,对于header/footer来讲,就是视图的高度;对于left/right来讲,就是视图的宽度 */ func heightForRefreshingState()->CGFloat /** 已经开始执行刷新逻辑,在一次刷新中,只会调用一次 */ func didBeginRefreshing() /** 结束刷新的回调 */ func didCompleteEndRefershingAnimation() /** 拖动百分比变化的回调 - parameter percent: 拖动百分比,大于0 */ func percentUpdateDuringScrolling(_ percent:CGFloat) } public protocol SetUp {} public extension SetUp where Self: AnyObject { //Add @noescape to make sure that closure is sync and can not be stored @discardableResult public func SetUp(_ closure: (Self) -> Void) -> Self { closure(self) return self } } extension NSObject: SetUp {} //Header public extension UIScrollView{ @discardableResult public func setUpHeaderRefresh(_ action:@escaping ()->())->DefaultRefreshHeader{ let header = DefaultRefreshHeader(frame:CGRect(x: 0,y: 0,width: self.frame.width,height: PullToRefreshKitConst.defaultHeaderHeight)) return setUpHeaderRefresh(header, action: action) } @discardableResult public func setUpHeaderRefresh<T:UIView>(_ header:T,action:@escaping ()->())->T where T:RefreshableHeader{ let oldContain = self.viewWithTag(PullToRefreshKitConst.headerTag) oldContain?.removeFromSuperview() let containFrame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height) let containComponent = RefreshHeaderContainer(frame: containFrame) if let endDuration = header.durationWhenEndRefreshing?(){ containComponent.durationOfEndRefreshing = endDuration } containComponent.tag = PullToRefreshKitConst.headerTag containComponent.refreshAction = action self.addSubview(containComponent) containComponent.delegate = header header.autoresizingMask = [.flexibleWidth,.flexibleHeight] let bounds = CGRect(x: 0,y: containFrame.height - header.frame.height,width: self.frame.width,height: header.frame.height) header.frame = bounds containComponent.addSubview(header) return header } public func beginHeaderRefreshing(){ let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer header?.beginRefreshing() } public func endHeaderRefreshing(_ result:RefreshResult = .none,delay:Double = 0.0){ let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer header?.endRefreshing(result,delay: delay) } } //Footer public extension UIScrollView{ @discardableResult public func setUpFooterRefresh(_ action:@escaping ()->())->DefaultRefreshFooter{ let footer = DefaultRefreshFooter(frame: CGRect(x: 0,y: 0,width: self.frame.width,height: PullToRefreshKitConst.defaultFooterHeight)) return setUpFooterRefresh(footer, action: action) } @discardableResult public func setUpFooterRefresh<T:UIView>(_ footer:T,action:@escaping ()->())->T where T:RefreshableFooter{ let oldContain = self.viewWithTag(PullToRefreshKitConst.footerTag) oldContain?.removeFromSuperview() let frame = CGRect(x: 0,y: 0,width: self.frame.width, height: PullToRefreshKitConst.defaultFooterHeight) let containComponent = RefreshFooterContainer(frame: frame) containComponent.tag = PullToRefreshKitConst.footerTag containComponent.refreshAction = action self.insertSubview(containComponent, at: 0) containComponent.delegate = footer footer.autoresizingMask = [.flexibleWidth,.flexibleHeight] footer.frame = containComponent.bounds containComponent.addSubview(footer) return footer } public func beginFooterRefreshing(){ let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer footer?.beginRefreshing() } public func endFooterRefreshing(){ let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer footer?.endRefreshing() } public func setFooterNoMoreData(){ let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer footer?.endRefreshing() } public func resetFooterToDefault(){ let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer footer?.resetToDefault() } public func endFooterRefreshingWithNoMoreData(){ let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer footer?.endRefreshing() footer?.updateToNoMoreData() } } //Left extension UIScrollView{ @discardableResult public func setUpLeftRefresh(_ action:@escaping ()->())->DefaultRefreshLeft{ let left = DefaultRefreshLeft(frame: CGRect(x: 0,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height)) return setUpLeftRefresh(left, action: action) } @discardableResult public func setUpLeftRefresh<T:UIView>(_ left:T,action:@escaping ()->())->T where T:RefreshableLeftRight{ let oldContain = self.viewWithTag(PullToRefreshKitConst.leftTag) oldContain?.removeFromSuperview() let frame = CGRect(x: -1.0 * PullToRefreshKitConst.defaultLeftWidth,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height) let containComponent = RefreshLeftContainer(frame: frame) containComponent.tag = PullToRefreshKitConst.leftTag containComponent.refreshAction = action self.insertSubview(containComponent, at: 0) containComponent.delegate = left left.autoresizingMask = [.flexibleWidth,.flexibleHeight] left.frame = containComponent.bounds containComponent.addSubview(left) return left } } //Right extension UIScrollView{ @discardableResult public func setUpRightRefresh(_ action:@escaping ()->())->DefaultRefreshRight{ let right = DefaultRefreshRight(frame: CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height )) return setUpRightRefresh(right, action: action) } @discardableResult public func setUpRightRefresh<T:UIView>(_ right:T,action:@escaping ()->())->T where T:RefreshableLeftRight{ let oldContain = self.viewWithTag(PullToRefreshKitConst.rightTag) oldContain?.removeFromSuperview() let frame = CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height ) let containComponent = RefreshRightContainer(frame: frame) containComponent.tag = PullToRefreshKitConst.rightTag containComponent.refreshAction = action self.insertSubview(containComponent, at: 0) containComponent.delegate = right right.autoresizingMask = [.flexibleWidth,.flexibleHeight] right.frame = containComponent.bounds containComponent.addSubview(right) return right } }
apache-2.0
9e7b758baeed957b650e94cc8912c020
33.891791
154
0.691049
4.734684
false
false
false
false
rhx/gir2swift
Sources/libgir2swift/emitting/emit-signals.swift
1
16368
import Foundation /// This file contains support for signal generation. Since signals are described differently than other function types in .gir files, custom behavior for type generation and casting is implemented. /// Since the custom generation was already needed, focus of this implementation is safety. If a argument lacks a implementation of safe interface generation, whole signal is ommited. All signals are checked before generation and the decision process was summarized into 9 conditions. The future aim is to lift those limitation progressively. Such feature will require better support from the rest of gir2swift. /// This method verifies, whether signal is fit to be generated. /// - Returns: Array of string which contains all the reasons why signal could not be generated. Empty array implies signal is fit to be generated. func signalSanityCheck(_ signal: GIR.Signal) -> [String] { var errors = [String]() if !signal.args.allSatisfy({ $0.ownershipTransfer == .none }) { errors.append("(1) argument with ownership transfer is not allowed") } if !signal.args.allSatisfy({ $0.direction == .in }) { errors.append("(2) `out` or `inout` argument direction is not allowed") } if !signal.args.allSatisfy({ $0.typeRef.type.name != "Void" }) { errors.append("(3) Void argument is not yet supported") } if !signal.args.allSatisfy({ $0.typeRef.type.name != "gpointer" }) { errors.append("(4) gpointer argument is not yet supported") } if !signal.args.allSatisfy({ !($0.knownType is GIR.Alias) }) || (signal.returns.knownType is GIR.Alias) { errors.append("(5) Alias argument or return is not yet supported") } if signal.returns.isOptional { errors.append("(6) optional argument or return type is not allowed") } if !signal.args.allSatisfy({ !$0.isArray }) || signal.returns.isArray { errors.append("(7) array argument or return type is not allowed") } if signal.returns.isNullable == true { errors.append("(8) nullable argument or return type is not allowed") } if signal.returns.knownType is GIR.Record { errors.append("(9) Record return type is not yet supported") } return errors } func buildSignalExtension(for record: GIR.Record) -> String { let recordName = record.name.swift let signalType = recordName + "SignalName" if record.signals.isEmpty { return "// MARK: \(record.name.swift) has no signals\n" } return Code.block(indentation: nil) { "// MARK: \(recordName) signals" "public extension \(record.protocolName) {" Code.block { "/// Connect a Swift signal handler to the given, typed `\(signalType)` signal" "/// - Parameters:" "/// - signal: The signal to connect" "/// - flags: The connection flags to use" "/// - data: A pointer to user data to provide to the callback" "/// - destroyData: A `GClosureNotify` C function to destroy the data pointed to by `userData`" "/// - handler: The Swift signal handler (function or callback) to invoke on the given signal" "/// - Returns: The signal handler ID (always greater than 0 for successful connections)" "@inlinable @discardableResult func connect(signal s: \(signalType), flags f: ConnectFlags = ConnectFlags(0), handler h: @escaping SignalHandler) -> Int {" Code.block { "\(record is GIR.Interface ? "GLibObject.ObjectRef(raw: ptr)." : "" )connect(s, flags: f, handler: h)" } "}\n\n" "/// Connect a C signal handler to the given, typed `\(signalType)` signal" "/// - Parameters:" "/// - signal: The signal to connect" "/// - flags: The connection flags to use" "/// - data: A pointer to user data to provide to the callback" "/// - destroyData: A `GClosureNotify` C function to destroy the data pointed to by `userData`" "/// - signalHandler: The C function to be called on the given signal" "/// - Returns: The signal handler ID (always greater than 0 for successful connections)" "@inlinable @discardableResult func connect(signal s: \(signalType), flags f: ConnectFlags = ConnectFlags(0), data userData: gpointer!, destroyData destructor: GClosureNotify? = nil, signalHandler h: @escaping GCallback) -> Int {" Code.block { (record is GIR.Interface ? "GLibObject.ObjectRef(raw: ptr)." : "") + "connectSignal(s, flags: f, data: userData, destroyData: destructor, handler: h)" } "}\n\n" // Generation of unavailable signals Code.loop(over: record.signals.filter( {!signalSanityCheck($0).isEmpty} )) { signal in buildUnavailableSignal(record: record, signal: signal) } // Generation of available signals Code.loop(over: record.signals.filter( {signalSanityCheck($0).isEmpty } )) { signal in buildAvailableSignal(record: record, signal: signal) } // Generation of property obsevers. Property observers have the same declaration as GObject signal `notify`. This sinal should be available at all times. if let knownObject = GIR.knownRecords["GLibObject.Object"] ?? GIR.knownRecords["Object"], let notifySignal = knownObject.signals.first(where: { $0.name == "notify"}) { Code.loop(over: record.properties) { property in buildSignalForProperty(record: record, property: property, notify: notifySignal) } } else { "// \(recordName) property signals were not generated due to unavailability of GObject during generation time" } } "}\n\n" } } /// Modifies provided signal model to notify about property change. /// - Parameter record: Record of the property /// - Parameter property: Property which observer will be genrated /// - Parameter notify: GObject signal "notify" which is basis for the signal generation. private func buildSignalForProperty(record: GIR.Record, property: GIR.Property, notify: GIR.Signal) -> String { let propertyNotify = GIR.Signal( name: notify.name + "::" + property.name, cname: notify.cname, returns: notify.returns, args: notify.args, comment: notify.comment, introspectable: notify.introspectable, deprecated: notify.deprecated, throwsAnError: notify.throwsError ) return buildAvailableSignal(record: record, signal: propertyNotify) } @CodeBuilder private func buildAvailableSignal(record: GIR.Record, signal: GIR.Signal) -> String { addDocumentation(signal: signal) let recordName = record.name.swift let signalType = recordName + "SignalName" let swiftSignal = signal.name.replacingOccurrences(of: "::", with: "_").kebabSnakeCase2camelCase "/// Run the given callback whenever the `\(swiftSignal)` signal is emitted" Code.line { "@discardableResult @inlinable func on\(swiftSignal.capitalised)(" "flags: ConnectFlags = ConnectFlags(0), " "handler: " handlerType(record: record, signal: signal) " ) -> Int {" } Code.block { "typealias SwiftHandler = \(signalClosureHolderDecl(record: record, signal: signal))" Code.line { "let cCallback: " cCallbackDecl(record: record, signal: signal) " = { " cCallbackArgumentsDecl(record: record, signal: signal) " in" } Code.block { "let holder = Unmanaged<SwiftHandler>.fromOpaque(userData).takeUnretainedValue()" "let output\(signal.returns.typeRef.type.name == "Void" ? ": Void" : "") = holder.\(generateCCallbackCall(record: record, signal: signal))" generateReturnStatement(record: record, signal: signal) } "}" "return connect(" Code.block { "signal: .\(swiftSignal)," "flags: flags," "data: Unmanaged.passRetained(SwiftHandler(handler)).toOpaque()," "destroyData: { userData, _ in UnsafeRawPointer(userData).flatMap(Unmanaged<SwiftHandler>.fromOpaque(_:))?.release() }," "signalHandler: unsafeBitCast(cCallback, to: GCallback.self)" } ")" } "}\n" "/// Typed `\(signal.name)` signal for using the `connect(signal:)` methods" "static var \(swiftSignal)Signal: \(signalType) { .\(swiftSignal) }\n" } /// This function build documentation and name for unavailable signal. @CodeBuilder private func buildUnavailableSignal(record: GIR.Record, signal: GIR.Signal) -> String { addDocumentation(signal: signal) let recordName = record.name.swift let signalType = recordName + "SignalName" let swiftSignal = signal.name.replacingOccurrences(of: "::", with: "_").kebabSnakeCase2camelCase "/// - Warning: a `on\(swiftSignal.capitalised)` wrapper for this signal could not be generated because it contains unimplemented features: { \( signalSanityCheck(signal).joined(separator: ", ") ) }" "/// - Note: Instead, you can connect `\(swiftSignal)Signal` using the `connect(signal:)` methods" "static var \(swiftSignal)Signal: \(signalType) { .\(swiftSignal) }" } /// This function build Swift closure handler declaration. @CodeBuilder private func handlerType(record: GIR.Record, signal: GIR.Signal) -> String { "@escaping ( _ unownedSelf: \(record.structName)" Code.loop(over: signal.args) { argument in ", _ \(argument.prefixedArgumentName): \(argument.swiftIdiomaticType())" } ") -> " signal.returns.swiftIdiomaticType() } /// This function builds declaration for the typealias holding the reference to the Swift closure handler private func signalClosureHolderDecl(record: GIR.Record, signal: GIR.Signal) -> String { return Code.line { "GLib.ClosureHolder<" "(" + ([record.structName] + signal.args.map { $0.swiftIdiomaticType() }).joined(separator: ", ") + "), " signal.returns.swiftIdiomaticType() ">" } } /// This function adds Parameter documentation to the signal on top of existing documentation generation. @CodeBuilder private func addDocumentation(signal: GIR.Signal) -> String { { str -> String in str.isEmpty ? CodeBuilder.unused : str}(commentCode(signal)) "/// - Note: This represents the underlying `\(signal.name)` signal" "/// - Parameter flags: Flags" "/// - Parameter unownedSelf: Reference to instance of self" Code.loop(over: signal.args) { argument in let comment = gtkDoc2SwiftDoc(argument.comment, linePrefix: "").replacingOccurrences(of: "\n", with: " ") "/// - Parameter \(argument.prefixedArgumentName): \(comment.isEmpty ? "none" : comment)" } let returnComment = gtkDoc2SwiftDoc(signal.returns.comment, linePrefix: "").replacingOccurrences(of: "\n", with: " ") "/// - Parameter handler: \(returnComment.isEmpty ? "The signal handler to call" : returnComment)" } /// Returns declaration for c callback. @CodeBuilder private func cCallbackDecl(record: GIR.Record, signal: GIR.Signal) -> String { "@convention(c) (" GIR.gpointerType.typeName + ", " // Representing record itself Code.loop(over: signal.args) { argument in argument.swiftCCompatibleType() + ", " } GIR.gpointerType.typeName // Representing user data ") -> " signal.returns.swiftCCompatibleType() } /// list of names of arguments of c callback private func cCallbackArgumentsDecl(record: GIR.Record, signal: GIR.Signal) -> String { Code.line { "unownedSelf" Code.loopEnumerated(over: signal.args) { index, _ in ", arg\(index + 1)" } ", userData" } } /// Returns correct call of Swift handler from c callback scope with correct casting. private func generateCCallbackCall(record: GIR.Record, signal: GIR.Signal) -> String { Code.line { "call((\(record.structRef.type.swiftName)(raw: unownedSelf)" Code.loopEnumerated(over: signal.args) { index, argument in ", \(argument.swiftSignalArgumentConversion(at: index + 1))" } "))" } } /// Generates correct return statement. This method currently contains implementation of ownership-transfer ability for String. private func generateReturnStatement(record: GIR.Record, signal: GIR.Signal) -> String { switch signal.returns.knownType { case is GIR.Record: return "return \(signal.returns.typeRef.cast(expression: "output", from: signal.returns.swiftSignalRef))" case is GIR.Alias: // use containedTypes return "" case is GIR.Bitfield: return "return output.rawValue" case is GIR.Enumeration: return "return output.rawValue" case nil where signal.returns.swiftSignalRef == GIR.stringRef && signal.returns.ownershipTransfer == .full: return Code.block { "let length = output.utf8CString.count" "let buffer = UnsafeMutablePointer<gchar>.allocate(capacity: length)" "buffer.initialize(from: output, count: length)" "return buffer" } default: // Treat as fundamental (if not a fundamental, report error) return "return \(signal.returns.typeRef.cast(expression: "output", from: signal.returns.swiftSignalRef))" } } private extension GIR.Argument { /// Returns type names for Swift adjusted for the needs of signal generation func swiftIdiomaticType() -> String { switch knownType { case is GIR.Record: let type = typeRef.type let typeName = optionalIfNullableOrOptional(type.prefixedWhereNecessary(type.swiftName + "Ref")) return typeName case is GIR.Alias: // use containedTypes return "" case is GIR.Bitfield, is GIR.Enumeration: return optionalIfNullableOrOptional(argumentTypeName) default: // Treat as fundamental (if not a fundamental, report error) return optionalIfNullableOrOptional(swiftSignalRef.fullSwiftTypeName) } } /// Returns names name for C adjusted for the needs of signal generation func swiftCCompatibleType() -> String { switch knownType { case is GIR.Record: return optionalIfNullableOrOptional(GIR.gpointerType.typeName) case is GIR.Alias: // use containedTypes return "" case is GIR.Bitfield, is GIR.Enumeration: return optionalIfNullableOrOptional(GIR.uint32Type.typeName) default: // Treat as fundamental (if not a fundamental, report error) return self.callbackArgumentTypeName } } /// Generates correct cast from C type/argument to Swift type. This method currently supports optionals. func swiftSignalArgumentConversion(at index: Int) -> String { switch knownType { case is GIR.Record: let type = typeRef.type let refName = type.prefixedWhereNecessary(type.swiftName) + "Ref" if (isNullable || isOptional) { return "arg\(index).flatMap(\(refName).init(raw:))" } return refName + "(raw: arg\(index))" case is GIR.Alias: // use containedTypes return "" case is GIR.Bitfield: if (isNullable || isOptional) { return "arg\(index).flatMap(\(self.argumentTypeName).init(_:))" } return self.argumentTypeName + "(arg\(index))" case is GIR.Enumeration: if (isNullable || isOptional) { return "arg\(index).flatMap(\(self.argumentTypeName).init(_:))" } return self.argumentTypeName + "(arg\(index))" case nil where swiftSignalRef == GIR.stringRef: return swiftSignalRef.cast(expression: "arg\(index)", from: typeRef) + ((isNullable || isOptional) ? "" : "!") default: // Treat as fundamental (if not a fundamental, report error) return swiftSignalRef.cast(expression: "arg\(index)", from: typeRef) } } }
bsd-2-clause
dd4ab92223e183eb88465407890cf0ce
45.765714
411
0.64229
4.545404
false
false
false
false
tristanchu/FlavorFinder
FlavorFinder/FlavorFinder/LoginUtils.swift
1
4390
// // Utils.swift // FlavorFinder // // Created by Jon on 10/27/15. // Copyright © 2015 TeamFive. All rights reserved. // import UIKit import Parse // Input validation values: var USERNAME_CHAR_MAX = 25 var USERNAME_CHAR_MIN = 1 var PASSWORD_CHAR_MIN = 6 var PASSWORD_CHAR_MAX = 25 // Colors: var backgroundColor_normal: UIColor! var backgroundColor_error: UIColor = UIColor(red: 250/255.0, green: 126/255.0, blue: 107/255.0, alpha: 0.5) var currentUser: PFUser? // ---------------------------------------------------------------------- // SESSION VALIDATION FUNCTIONS --------------------------------------- // ---------------------------------------------------------------------- /** isUserLoggedIn @return: Bool - True if user is currently logged into a session */ func isUserLoggedIn() -> Bool { return currentUser != nil } /** setUserSession @param: user - PFUser */ func setUserSession(user: PFUser) -> Void { // Store current PFUser currentUser = user getUserVotesFromCloud(user) getUserFavoritesFromCloud(user) getUserListsFromCloud(user) } /** removeUserSession Removes stored PFUser */ func removeUserSession() -> Void { // remove stored PFUser: currentUser = nil } // ---------------------------------------------------------------------- // INPUT VALIDATION FUNCTIONS ------------------------------------------- // ---------------------------------------------------------------------- /** isInvalidEmail @param: email - String @return: True if email address is not in a valid email format. */ func isInvalidEmail(email:String) -> Bool { let emailRegex = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex) return !emailTest.evaluateWithObject(email) } /** isInvalidUsername @param: username - String @return: True if username = empty, too long, or too short. */ func isInvalidUsername(username: String) -> Bool { return (username.isEmpty || username.characters.count > USERNAME_CHAR_MAX || username.characters.count < USERNAME_CHAR_MIN) } /** isInvalidPassword @param: password - String @return: True if password = empty, too long, too short, or contains spaces. */ func isInvalidPassword(password: String) -> Bool { return (password.isEmpty || password.characters.count > PASSWORD_CHAR_MAX || password.characters.count < PASSWORD_CHAR_MIN) || password.characters.contains(" ") } // ---------------------------------------------------------------------- // KEYCHAIN FUNCTIONS --------------------------------------------------- // ---------------------------------------------------------------------- // NOTE: Keeping Keychain functions for when we develop persistent data since // now we will need it when dealing with exiting and re-entering the app. /** storeLoginInKeychain Stores current user's username and password in the Keychain @param: user - PFUser */ func storeLoginInKeychain(username: String, password: String) -> Void { MyKeychainWrapper.mySetObject(password, forKey: kSecValueData) MyKeychainWrapper.mySetObject(username, forKey: kSecAttrAccount) MyKeychainWrapper.writeToKeychain() } /** getUsernameFromKeychain Gets username currently stored in the Keychain. If no user stored, gets the default username "default" as String. @return: username - String */ func getUsernameFromKeychain() -> String { return MyKeychainWrapper.myObjectForKey(kSecAttrAccount) as! String } /** getPasswordFromKeychain Gets password currently stored in the Keychain. If no user stored, gets the default password "default" as String. @return: password - String */ func getPasswordFromKeychain() -> String { return MyKeychainWrapper.myObjectForKey(kSecValueData) as! String } // ---------------------------------------------------------------------- // USER UTILITIES --------------------------------------------------- // ---------------------------------------------------------------------- /** requestPasswordReset Parse sends a password reset email allowing the user to reset their password */ func requestPasswordReset() { PFUser.requestPasswordResetForEmailInBackground((currentUser?.email)!) }
mit
0136846efb5f8ef76add7059db25a629
26.43125
156
0.57872
4.629747
false
false
false
false
pitput/SwiftWamp
SwiftWamp/Subscription.swift
1
2025
// // Created by Dany Sousa on 28/10/2016. // Copyright (c) 2016 danysousa. All rights reserved. // import Foundation /** Subscription is a class describing a subscribe, you can find the subscribe id, the session, the status and the event callback. This class is used for SubscribeCallback param and cannot instantiate outside the SwiftWamp target */ open class Subscription { fileprivate let session: SwampSession internal let subscription: NSNumber internal let queue: DispatchQueue internal var eventCallback: EventCallback fileprivate var isActive: Bool = true open let topic: String internal init(session: SwampSession, subscription: NSNumber, onEvent: @escaping EventCallback, topic: String, queue: DispatchQueue) { self.session = session self.subscription = subscription self.eventCallback = onEvent self.topic = topic self.queue = queue } internal func invalidate() { self.isActive = false } /** Cancel is the method for unsubscribe this subscription. This function is an alias of SwampSession.unsubscribe - Parameter onSuccess: it's the function called if the unsubscribe request succeeded the type of this function is the typealias UnsubscribeCallback, here is the complete signature : () -> Void - Parameter onError: it's the function called if the unsubscribe request failed the type of this function is the typealias ErrorUnsubscribeCallback, here is the complete signature : (_ details: [String: Any], _ error: String) -> Void */ open func cancel(_ onSuccess: @escaping UnsubscribeCallback, onError: @escaping ErrorUnsubscribeCallback) { if !self.isActive { onError([:], "Subscription already inactive.") } self.session.unsubscribe(self.subscription, onSuccess: onSuccess, onError: onError) } open func changeEventCallback(callback: @escaping EventCallback) { self.eventCallback = callback } }
mit
7fce721f82318fb7b0e06e2446648133
35.818182
137
0.706667
5.024814
false
false
false
false
PJayRushton/stats
Pods/Presentr/Presentr/AlertViewController.swift
3
8378
// // AlertViewController.swift // OneUP // // Created by Daniel Lozano on 5/10/16. // Copyright © 2016 Icalia Labs. All rights reserved. // import UIKit public typealias AlertActionHandler = ((AlertAction) -> Void) /// Describes each action that is going to be shown in the 'AlertViewController' public class AlertAction { public let title: String public let style: AlertActionStyle public let handler: AlertActionHandler? /** Initialized an 'AlertAction' - parameter title: The title for the action, that will be used as the title for a button in the alert controller - parameter style: The style for the action, that will be used to style a button in the alert controller. - parameter handler: The handler for the action, that will be called when the user clicks on a button in the alert controller. - returns: An inmutable AlertAction object */ public init(title: String, style: AlertActionStyle, handler: AlertActionHandler?) { self.title = title self.style = style self.handler = handler } } /** Describes the style for an action, that will be used to style a button in the alert controller. - Default: Green text label. Meant to draw attention to the action. - Cancel: Gray text label. Meant to be neutral. - Destructive: Red text label. Meant to warn the user about the action. */ public enum AlertActionStyle { case `default` case cancel case destructive case custom(textColor: UIColor) /** Decides which color to use for each style - returns: UIColor representing the color for the current style */ func color() -> UIColor { switch self { case .default: return ColorPalette.greenColor case .cancel: return ColorPalette.grayColor case .destructive: return ColorPalette.redColor case let .custom(color): return color } } } private enum Font: String { case Montserrat = "Montserrat-Regular" case SourceSansPro = "SourceSansPro-Regular" func font(_ size: CGFloat = 15.0) -> UIFont { return UIFont(name: self.rawValue, size: size)! } } private struct ColorPalette { static let grayColor = UIColor(red: 151.0/255.0, green: 151.0/255.0, blue: 151.0/255.0, alpha: 1) static let greenColor = UIColor(red: 58.0/255.0, green: 213.0/255.0, blue: 91.0/255.0, alpha: 1) static let redColor = UIColor(red: 255.0/255.0, green: 103.0/255.0, blue: 100.0/255.0, alpha: 1) } /// UIViewController subclass that displays the alert public class AlertViewController: UIViewController { /// Text that will be used as the title for the alert public var titleText: String? /// Text that will be used as the body for the alert public var bodyText: String? /// If set to false, alert wont auto-dismiss the controller when an action is clicked. Dismissal will be up to the action's handler. Default is true. public var autoDismiss: Bool = true /// If autoDismiss is set to true, then set this property if you want the dismissal to be animated. Default is true. public var dismissAnimated: Bool = true fileprivate var actions = [AlertAction]() @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var firstButton: UIButton! @IBOutlet weak var secondButton: UIButton! @IBOutlet weak var firstButtonWidthConstraint: NSLayoutConstraint! override public func loadView() { let name = "AlertViewController" let bundle = Bundle(for: type(of: self)) guard let view = bundle.loadNibNamed(name, owner: self, options: nil)?.first as? UIView else { fatalError("Nib not found.") } self.view = view } override public func viewDidLoad() { super.viewDidLoad() if actions.isEmpty { let okAction = AlertAction(title: "ok 🕶", style: .default, handler: nil) addAction(okAction) } loadFonts setupFonts() setupLabels() setupButtons() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override public func updateViewConstraints() { if actions.count == 1 { // If only one action, second button will have been removed from superview // So, need to add constraint for first button trailing to superview if let constraint = firstButtonWidthConstraint { view.removeConstraint(constraint) } let views: [String: UIView] = ["button" : firstButton] let constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[button]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) view.addConstraints(constraints) } super.updateViewConstraints() } // MARK: AlertAction's /** Adds an 'AlertAction' to the alert controller. There can be maximum 2 actions. Any more will be ignored. The order is important. - parameter action: The 'AlertAction' to be added */ public func addAction(_ action: AlertAction) { guard actions.count < 2 else { return } actions += [action] } // MARK: Setup fileprivate func setupFonts() { titleLabel.font = Font.Montserrat.font() bodyLabel.font = Font.SourceSansPro.font() firstButton.titleLabel?.font = Font.Montserrat.font(11.0) secondButton.titleLabel?.font = Font.Montserrat.font(11.0) } fileprivate func setupLabels() { titleLabel.text = titleText ?? "Alert" bodyLabel.text = bodyText ?? "This is an alert." } fileprivate func setupButtons() { guard let firstAction = actions.first else { return } apply(firstAction, toButton: firstButton) if actions.count == 2 { let secondAction = actions.last! apply(secondAction, toButton: secondButton) } else { secondButton.removeFromSuperview() } } fileprivate func apply(_ action: AlertAction, toButton: UIButton) { let title = action.title.uppercased() let style = action.style toButton.setTitle(title, for: UIControlState()) toButton.setTitleColor(style.color(), for: UIControlState()) } // MARK: IBAction's @IBAction func didSelectFirstAction(_ sender: AnyObject) { guard let firstAction = actions.first else { return } if let handler = firstAction.handler { handler(firstAction) } dismiss() } @IBAction func didSelectSecondAction(_ sender: AnyObject) { guard let secondAction = actions.last, actions.count == 2 else { return } if let handler = secondAction.handler { handler(secondAction) } dismiss() } // MARK: Helper's func dismiss() { guard autoDismiss else { return } self.dismiss(animated: dismissAnimated, completion: nil) } } // MARK: - Font Loading let loadFonts: () = { let loadedFontMontserrat = AlertViewController.loadFont(Font.Montserrat.rawValue) let loadedFontSourceSansPro = AlertViewController.loadFont(Font.SourceSansPro.rawValue) if loadedFontMontserrat && loadedFontSourceSansPro { print("LOADED FONTS") } }() extension AlertViewController { static func loadFont(_ name: String) -> Bool { let bundle = Bundle(for: self) guard let fontPath = bundle.path(forResource: name, ofType: "ttf"), let data = try? Data(contentsOf: URL(fileURLWithPath: fontPath)), let provider = CGDataProvider(data: data as CFData), let font = CGFont(provider) else { return false } var error: Unmanaged<CFError>? let success = CTFontManagerRegisterGraphicsFont(font, &error) if !success { print("Error loading font. Font is possibly already registered.") return false } return true } }
mit
151b3c52e76e6d7d271c8a3b715d087d
30.961832
153
0.62909
4.796105
false
false
false
false