repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
UniTN-Mechatronics/NoTremor | Container/MXChart.swift | 1 | 11230 | //
// MXChartView.swift
//
//
// Created by Paolo Bosetti on 07/10/14.
// Copyright (c) 2014 University of Trento. All rights reserved.
//
import UIKit
class MXDataSeries : NSObject {
var data = Array<CGPoint>()
var name = String()
var lineColor: UIColor = UIColor.redColor()
var lineWidth: CGFloat = 1
var capacity: Int? {
didSet {
if let capa = capacity {
data = Array(count: capa, repeatedValue: CGPointMake(0, 0))
self.data.reserveCapacity(capa + 1)
}
}
}
init(name: String) {
self.name = name
}
func count() -> Int {
return self.data.count
}
func randomFill(from: CGFloat, to: CGFloat, length: Int) {
var x, y: CGFloat
let rng = to - from
for i in 0...length {
x = from + (CGFloat(i) / CGFloat(length)) * rng
y = CGFloat(rand()) / CGFloat(RAND_MAX)
data.append(CGPointMake(x, y))
}
}
func append(x: CGFloat, y: CGFloat) {
let p = CGPointMake(x, y)
data.append(p)
if let capa = self.capacity {
data.removeRange(0..<1)
}
}
func addFromString(data: String, xCol: Int, yCol: Int) {
let lines = split(data) { $0 == "\n" }
for line in lines {
if !line.hasPrefix("#") {
let cols = split(line) { $0 == " " }
let x = cols[xCol] as NSString
let y = cols[yCol] as NSString
self.append(CGFloat(x.floatValue), y: CGFloat(y.floatValue))
}
}
}
func range() -> CGRect {
if let first = data.first {
let (y0, y1) = data.reduce((first.y, first.y)) { (min($0.0, $1.y), max($0.1, $1.y)) }
let (x0, x1) = (first.x, data.last!.x)
return CGRectMake(x0, y0, x1 - x0, y1 - y0)
}
else {
return CGRectMake(0, 0, 1, 1)
}
}
}
@IBDesignable class MXChart : UIView {
@IBInspectable var borderColor: UIColor = UIColor.blackColor()
@IBInspectable var fillColor: UIColor = UIColor.clearColor()
@IBInspectable var defaultPlotColor: UIColor = UIColor.redColor()
@IBInspectable var axesColor: UIColor = UIColor.grayColor()
@IBInspectable var textColor: UIColor = UIColor.blackColor()
@IBInspectable var borderWidth: CGFloat = 1
@IBInspectable var cornerRadius: CGFloat = 3
@IBInspectable var range: CGRect = CGRectMake(-1, -2, 20, 4) {
didSet {
if (self.range.width <= 0 || self.range.height <= 0) {
range = CGRectMake(range.origin.x, range.origin.y, 20, 4)
}
}
}
@IBInspectable var xLabel: String = "X axis"
@IBInspectable var yLabel: String = "Y axis"
@IBInspectable var showXAxis: Bool = true
@IBInspectable var showYAxis: Bool = true
@IBInspectable var showLegend: Bool = true
@IBInspectable var legendLineOffset: CGFloat = 15
var series = Dictionary<String,MXDataSeries>()
override func awakeFromNib() {
super.awakeFromNib()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
drawChartView(fillColor, rectangle: self.bounds, strokeWidth: borderWidth, radius: cornerRadius, xLabelText: xLabel, yLabelText: yLabel)
}
override func prepareForInterfaceBuilder() {
var x, s, c: CGFloat
let n = 100
series.removeAll(keepCapacity: false)
series["sin"] = MXDataSeries(name: "Sine")
series["sin"]!.lineColor = self.defaultPlotColor
series["sin"]!.lineWidth = 1
series["cos"] = MXDataSeries(name: "Cosine")
series["cos"]!.lineColor = UIColor.blueColor()
series["cos"]!.lineWidth = 1
for i in 0...n {
x = CGFloat(CGFloat(i) * CGFloat(range.width) / CGFloat(n) + CGFloat(range.origin.x))
s = CGFloat(sin(x))
c = CGFloat(cos(x))
series["sin"]?.append(x, y: s)
series["cos"]?.append(x, y: c)
}
series["rnd"] = MXDataSeries(name: "Random")
series["rnd"]?.randomFill(range.origin.x, to: range.origin.x + range.width, length: n)
series["rnd"]!.lineColor = UIColor.greenColor()
series["rnd"]!.lineWidth = 2
}
func reset() {
series.removeAll(keepCapacity: false)
}
func cleanup() {
for (n, s) in series {
s.data.removeAll(keepCapacity: true)
}
}
func remap(point: CGPoint, fromRect: CGRect, toRect: CGRect) -> CGPoint {
var p = CGPointMake(0, 0)
p.x = ((point.x - fromRect.origin.x) / fromRect.width) * toRect.width + toRect.origin.x
p.y = ((point.y - fromRect.origin.y) / fromRect.height) * toRect.height + toRect.origin.y
p.y = -p.y + toRect.height
return p
}
func addSeries(key: String, withLabel: String) {
series[key] = MXDataSeries(name: withLabel)
}
func counts() -> Dictionary<String, Int> {
var result = Dictionary<String, Int>()
for (k, v) in series {
result[k] = v.count()
}
return result
}
func addPointToSerie(serie: String, x: CGFloat, y: CGFloat) {
self.series[serie]?.append(x, y: y)
self.setNeedsDisplay()
}
func autoRescaleOnSerie(serie: String, xAxis: Bool, yAxis: Bool) {
autoRescaleOnSerie(serie, axes: (x: xAxis, y: yAxis))
}
func autoRescaleOnSerie(serie: String, axes: (x: Bool, y: Bool) ) {
let s = self.series[serie]
let rect = s!.range()
let (x, y, width, height) = (rect.origin.x, rect.origin.y, rect.width, rect.height)
switch axes {
case (true, true):
self.range.origin.x = x
self.range.size.width = width
self.range.origin.y = y
self.range.size.height = height
case (true, false):
self.range.origin.x = x
self.range.size.width = width
case (false, true):
self.range.origin.y = y
self.range.size.height = height
default:
return
}
self.setNeedsDisplay()
}
func drawPlot(inRect: CGRect, atOffset: CGPoint) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextTranslateCTM(context, atOffset.x, atOffset.y)
for (name, serie) in series {
var bezierPath = UIBezierPath()
if let startPoint = serie.data.first {
var p = remap(startPoint, fromRect: range, toRect: inRect)
bezierPath.moveToPoint(p)
for element in serie.data {
p = remap(element, fromRect: range, toRect: inRect)
bezierPath.addLineToPoint(p)
}
serie.lineColor.setStroke()
bezierPath.lineWidth = serie.lineWidth
bezierPath.stroke()
}
}
if (showXAxis) {
var xAxisPath = UIBezierPath()
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [4, 2], 2)
xAxisPath.moveToPoint(remap(CGPointMake(range.origin.x, 0), fromRect: range, toRect: inRect))
xAxisPath.addLineToPoint(remap(CGPointMake(range.origin.x + range.width, 0), fromRect: range, toRect: inRect))
self.axesColor.setStroke()
xAxisPath.stroke()
CGContextRestoreGState(context)
}
if (showYAxis) {
var yAxisPath = UIBezierPath()
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [4, 2], 2)
yAxisPath.moveToPoint(remap(CGPointMake(0, range.origin.y), fromRect: range, toRect: inRect))
yAxisPath.addLineToPoint(remap(CGPointMake(0, range.origin.y + range.height), fromRect: range, toRect: inRect))
self.axesColor.setStroke()
yAxisPath.stroke()
CGContextRestoreGState(context)
}
CGContextRestoreGState(context)
}
func drawChartView(fillColor: UIColor, rectangle: CGRect, strokeWidth: CGFloat, radius: CGFloat, xLabelText: String, yLabelText: String) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Variable Declarations
let labelHeight: CGFloat = 15
let rectWidth = rectangle.width - labelHeight - strokeWidth
let rectHeight = rectangle.height - labelHeight - strokeWidth
let rectOffset = CGPointMake(rectangle.origin.x, rectangle.origin.y + strokeWidth / 2.0)
//// Chart Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
let chartRect = CGRectMake(labelHeight + strokeWidth / 2.0, 0, rectWidth, rectHeight)
let chartPath = UIBezierPath(roundedRect: chartRect, cornerRadius: radius)
fillColor.setFill()
borderColor.setStroke()
chartPath.fill()
chartPath.lineWidth = strokeWidth
chartPath.stroke()
CGContextRestoreGState(context)
//// Draw data
drawPlot(chartRect, atOffset: rectOffset)
//// Label styles
let labelFont = UIFont(name: "Helvetica", size: 9)!
let cLabelStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
let lLabelStyle: NSMutableParagraphStyle = cLabelStyle.mutableCopy() as! NSMutableParagraphStyle
let rLabelStyle: NSMutableParagraphStyle = cLabelStyle.mutableCopy() as! NSMutableParagraphStyle
cLabelStyle.alignment = NSTextAlignment.Center
lLabelStyle.alignment = NSTextAlignment.Left
rLabelStyle.alignment = NSTextAlignment.Right
//// Legend drawing
if self.showLegend {
var offset: CGFloat = 0
let labelMargin = cornerRadius + borderWidth
CGContextSaveGState(context)
for (k, v) in self.series {
let text2Rect = CGRectMake(labelHeight + labelMargin, offset + labelMargin, 112, 20)
let text2FontAttributes = [NSFontAttributeName: UIFont(name: "Helvetica", size: 12)!, NSForegroundColorAttributeName: v.lineColor, NSParagraphStyleAttributeName: lLabelStyle]
v.name.drawInRect(text2Rect, withAttributes: text2FontAttributes);
offset += legendLineOffset
}
CGContextRestoreGState(context)
}
let labelColor = self.textColor
let labelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: cLabelStyle]
let minLabelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: lLabelStyle]
let maxLabelFontAttributes = [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelColor, NSParagraphStyleAttributeName: rLabelStyle]
//// xLabel Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
let xLabelRect = CGRectMake(labelHeight, rectHeight + strokeWidth / 2.0, rectWidth + strokeWidth, labelHeight)
NSString(string: xLabelText).drawInRect(xLabelRect, withAttributes: labelFontAttributes);
NSString(string: "\(range.origin.x)").drawInRect(xLabelRect, withAttributes: minLabelFontAttributes);
NSString(string: "\(range.origin.x + range.width)").drawInRect(xLabelRect, withAttributes: maxLabelFontAttributes);
CGContextRestoreGState(context)
//// yLabel Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, rectOffset.x, rectOffset.y)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let yLabelRect = CGRectMake(-rectHeight, 0, rectHeight, labelHeight)
NSString(string: yLabelText).drawInRect(yLabelRect, withAttributes: labelFontAttributes);
NSString(string: "\(range.origin.y)").drawInRect(yLabelRect, withAttributes: minLabelFontAttributes);
NSString(string: "\(range.origin.y + range.height)").drawInRect(yLabelRect, withAttributes: maxLabelFontAttributes);
CGContextRestoreGState(context)
}
}
| gpl-2.0 |
francisceioseph/Swift-Files-App | Swift-Files/UIViewControllerExtension.swift | 1 | 590 | //
// UIViewControllerExtension.swift
// Swift-Files
//
// Created by Francisco José A. C. Souza on 26/12/15.
// Copyright © 2015 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
extension UIViewController {
func makeSimpleAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Home/TipOff/TipOffViewController.swift | 1 | 3809 | //
// TipOffViewController.swift
// HiPDA
//
// Created by leizh007 on 2017/7/22.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class TipOffViewController: BaseViewController {
@IBOutlet fileprivate weak var sendButton: UIButton!
@IBOutlet fileprivate weak var textView: UITextView!
@IBOutlet fileprivate weak var containerBottomConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var tipOffLabel: UILabel!
var user: User!
fileprivate var viewModel: TipOffViewModel!
override func viewDidLoad() {
super.viewDidLoad()
textView.layer.borderWidth = 1
textView.layer.borderColor = #colorLiteral(red: 0.831372549, green: 0.831372549, blue: 0.831372549, alpha: 1).cgColor
tipOffLabel.text = "举报: \(user.name)"
configureKeyboard()
viewModel = TipOffViewModel(user: user)
textView.rx.text.orEmpty.map { !$0.isEmpty }.bindTo(sendButton.rx.isEnabled).disposed(by: disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
show()
}
fileprivate func configureKeyboard() {
KeyboardManager.shared.keyboardChanged.drive(onNext: { [weak self, unowned keyboardManager = KeyboardManager.shared] transition in
guard let `self` = self else { return }
guard transition.toVisible.boolValue else {
self.containerBottomConstraint.constant = -176
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
return
}
let keyboardFrame = keyboardManager.convert(transition.toFrame, to: self.view)
self.containerBottomConstraint.constant = keyboardFrame.size.height
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}).addDisposableTo(disposeBag)
}
@IBAction fileprivate func cancelButtonPressed(_ sender: UIButton) {
dismiss()
}
@IBAction fileprivate func sendButtonPressed(_ sender: UIButton) {
guard let window = UIApplication.shared.windows.last else { return }
showPromptInformation(of: .loading("正在发送..."), in: window)
viewModel.sendMessage(textView.text ?? "") { [weak self] result in
self?.hidePromptInformation(in: window)
switch result {
case .success(let info):
self?.showPromptInformation(of: .success(info), in: window)
delay(seconds: 0.25) {
self?.dismiss()
}
case .failure(let error):
self?.showPromptInformation(of: .failure(error.localizedDescription), in: window)
}
}
}
@IBAction fileprivate func backgroundDidTapped(_ sender: Any) {
dismiss()
}
private func show() {
textView.becomeFirstResponder()
UIView.animate(withDuration: C.UI.animationDuration) {
self.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4)
}
}
private func dismiss() {
view.endEditing(true)
UIView.animate(withDuration: C.UI.animationDuration, animations: {
self.view.backgroundColor = .clear
}, completion: { _ in
self.presentingViewController?.dismiss(animated: false, completion: nil)
})
}
}
// MARK: - StoryboardLoadable
extension TipOffViewController: StoryboardLoadable { }
| mit |
domenicosolazzo/practice-swift | CoreData/Boosting Data Access in Table Views/Boosting Data Access in Table Views/AppDelegate.swift | 1 | 6471 | //
// AppDelegate.swift
// Boosting Data Access in Table Views
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Boosting_Data_Access_in_Table_Views" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Boosting_Data_Access_in_Table_Views", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Boosting_Data_Access_in_Table_Views.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit |
codergaolf/DouYuTV | DouYuTV/DouYuTV/Classes/Room/Controller/RoomNormalViewController.swift | 1 | 916 | //
// RoomNormalViewController.swift
// DouYuTV
//
// Created by 高立发 on 2016/11/19.
// Copyright © 2016年 GG. All rights reserved.
//
import UIKit
class RoomNormalViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.orange
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1,隐藏导航栏
navigationController?.setNavigationBarHidden(true, animated: true)
//2,依然保持手势
// navigationController?.interactivePopGestureRecognizer?.delegate = self
// navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
| mit |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Timer.swift | 30 | 4058 | //
// Timer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where E : RxAbstractInteger {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
}
extension ObservableType where E: RxAbstractInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType)
-> Observable<E> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
final fileprivate class TimerSink<O: ObserverType> : Sink<O> where O.E : RxAbstractInteger {
typealias Parent = Timer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.schedulePeriodic(0 as O.E, startAfter: _parent._dueTime, period: _parent._period!) { state in
self.forwardOn(.next(state))
return state &+ 1
}
}
}
final fileprivate class TimerOneOffSink<O: ObserverType> : Sink<O> where O.E : RxAbstractInteger {
typealias Parent = Timer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRelative(self, dueTime: _parent._dueTime) { (`self`) -> Disposable in
self.forwardOn(.next(0))
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
}
}
final fileprivate class Timer<E: RxAbstractInteger>: Producer<E> {
fileprivate let _scheduler: SchedulerType
fileprivate let _dueTime: RxTimeInterval
fileprivate let _period: RxTimeInterval?
init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) {
_scheduler = scheduler
_dueTime = dueTime
_period = period
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
if let _ = _period {
let sink = TimerSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
else {
let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
}
| mit |
hughbe/swift | test/SILGen/specialize_attr.swift | 13 | 4910 | // RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s
// CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float)
// CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
@_specialize(where T == Int, U == Float)
func specializeThis<T, U>(_ t: T, u: U) {}
public protocol PP {
associatedtype PElt
}
public protocol QQ {
associatedtype QElt
}
public struct RR : PP {
public typealias PElt = Float
}
public struct SS : QQ {
public typealias QElt = Int
}
public struct GG<T : PP> {}
// CHECK-LABEL: public class CC<T> where T : PP {
// CHECK-NEXT: @_specialize(exported: false, kind: full, where T == RR, U == SS)
// CHECK-NEXT: @inline(never) public func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ
public class CC<T : PP> {
@inline(never)
@_specialize(where T == RR, U == SS)
public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4Thisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
// -----------------------------------------------------------------------------
// Test user-specialized subscript accessors.
public protocol TestSubscriptable {
associatedtype Element
subscript(i: Int) -> Element { get set }
}
public class ASubscriptable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
get {
return storage[i]
}
@_specialize(where Element == Int)
set(rhs) {
storage[i] = rhs
}
}
}
// ASubscriptable.subscript.getter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
// ASubscriptable.subscript.setter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
// ASubscriptable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr14ASubscriptableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
public class Addressable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
unsafeAddress {
return UnsafePointer<Element>(storage + i)
}
@_specialize(where Element == Int)
unsafeMutableAddress {
return UnsafeMutablePointer<Element>(storage + i)
}
}
}
// Addressable.subscript.getter with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
// Addressable.subscript.unsafeAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicflu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
// Addressable.subscript.setter with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
// Addressable.subscript.unsafeMutableAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicfau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
// Addressable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
| apache-2.0 |
Pre1/TestGit | hallo_v2.swift | 1 | 646 | #!/usr/bin/env xcrun swift
print("Hey, Git!")
print("test")
print("with soft, mixxed and haed reset")
let test = "Testting new braches"
// get how many characters in the string
let countString: Int = test.characters.count
print("playing_conf new feature")
// make changes
// add the changes -> git add .
// commit changes to repo w/ msg
// -> git commit -m "[Text]"
// commit message best practices
// - short single-line summary (less than 50 characters)
// - optionally followed by a blank line and a more complete
// description
// - keep each line to less than 72 characters
// HEAD is pointer that points to last commit in current repo | unlicense |
laerador/barista | Barista/Application/AboutPreferencesView.swift | 1 | 1061 | //
// AboutPreferencesView.swift
// Barista
//
// Created by Franz Greiling on 23.07.18.
// Copyright © 2018 Franz Greiling. All rights reserved.
//
import Cocoa
class AboutPreferencesView: NSView {
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var aboutTextView: NSTextView!
override func awakeFromNib() {
super.awakeFromNib()
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let buildnr = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
versionLabel.stringValue = "Version \(version) (\(buildnr))"
aboutTextView.readRTFD(fromFile: Bundle.main.path(forResource: "About", ofType: "rtf")!)
aboutTextView.font = NSFont.systemFont(ofSize: NSFont.systemFontSize)
aboutTextView.textColor = NSColor.labelColor
if #available(OSX 10.14, *) {
aboutTextView.linkTextAttributes?[.foregroundColor] = NSColor.controlAccentColor
}
}
}
| bsd-2-clause |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Site Settings/DiscussionSettingsViewController.swift | 1 | 25702 | import Foundation
import CocoaLumberjack
import WordPressShared
/// The purpose of this class is to render the Discussion Settings associated to a site, and
/// allow the user to tune those settings, as required.
///
open class DiscussionSettingsViewController: UITableViewController {
// MARK: - Initializers / Deinitializers
@objc public convenience init(blog: Blog) {
self.init(style: .grouped)
self.blog = blog
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
setupTableView()
setupNotificationListeners()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadSelectedRow()
tableView.deselectSelectedRowWithAnimation(true)
refreshSettings()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
saveSettingsIfNeeded()
}
// MARK: - Setup Helpers
fileprivate func setupNavBar() {
title = NSLocalizedString("Discussion", comment: "Title for the Discussion Settings Screen")
}
fileprivate func setupTableView() {
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
// Note: We really want to handle 'Unselect' manually.
// Reason: we always reload previously selected rows.
clearsSelectionOnViewWillAppear = false
}
fileprivate func setupNotificationListeners() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(DiscussionSettingsViewController.handleContextDidChange(_:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: settings.managedObjectContext)
}
// MARK: - Persistance!
fileprivate func refreshSettings() {
let service = BlogService(managedObjectContext: settings.managedObjectContext!)
service.syncSettings(for: blog,
success: { [weak self] in
self?.tableView.reloadData()
DDLogInfo("Reloaded Settings")
},
failure: { (error: Error) in
DDLogError("Error while sync'ing blog settings: \(error)")
})
}
fileprivate func saveSettingsIfNeeded() {
if !settings.hasChanges {
return
}
let service = BlogService(managedObjectContext: settings.managedObjectContext!)
service.updateSettings(for: blog,
success: nil,
failure: { (error: Error) -> Void in
DDLogError("Error while persisting settings: \(error)")
})
}
@objc open func handleContextDidChange(_ note: Foundation.Notification) {
guard let context = note.object as? NSManagedObjectContext else {
return
}
if !context.updatedObjects.contains(settings) {
return
}
saveSettingsIfNeeded()
}
// MARK: - UITableViewDataSoutce Methods
open override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rowAtIndexPath(indexPath)
let cell = cellForRow(row, tableView: tableView)
switch row.style {
case .Switch:
configureSwitchCell(cell as! SwitchTableViewCell, row: row)
default:
configureTextCell(cell as! WPTableViewCell, row: row)
}
return cell
}
open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].headerText
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footerText
}
open override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionFooter(view)
}
// MARK: - UITableViewDelegate Methods
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rowAtIndexPath(indexPath).handler?(tableView)
}
// MARK: - Cell Setup Helpers
fileprivate func rowAtIndexPath(_ indexPath: IndexPath) -> Row {
return sections[indexPath.section].rows[indexPath.row]
}
fileprivate func cellForRow(_ row: Row, tableView: UITableView) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: row.style.rawValue) {
return cell
}
switch row.style {
case .Value1:
return WPTableViewCell(style: .value1, reuseIdentifier: row.style.rawValue)
case .Switch:
return SwitchTableViewCell(style: .default, reuseIdentifier: row.style.rawValue)
}
}
fileprivate func configureTextCell(_ cell: WPTableViewCell, row: Row) {
cell.textLabel?.text = row.title ?? String()
cell.detailTextLabel?.text = row.details ?? String()
cell.accessoryType = .disclosureIndicator
WPStyleGuide.configureTableViewCell(cell)
}
fileprivate func configureSwitchCell(_ cell: SwitchTableViewCell, row: Row) {
cell.name = row.title ?? String()
cell.on = row.boolValue ?? true
cell.onChange = { (newValue: Bool) in
row.handler?(newValue as AnyObject?)
}
}
// MARK: - Row Handlers
fileprivate func pressedCommentsAllowed(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsAllowed = enabled
}
fileprivate func pressedPingbacksInbound(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.pingbackInboundEnabled = enabled
}
fileprivate func pressedPingbacksOutbound(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.pingbackOutboundEnabled = enabled
}
fileprivate func pressedRequireNameAndEmail(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsRequireNameAndEmail = enabled
}
fileprivate func pressedRequireRegistration(_ payload: AnyObject?) {
guard let enabled = payload as? Bool else {
return
}
settings.commentsRequireRegistration = enabled
}
fileprivate func pressedCloseCommenting(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Close commenting", comment: "Close Comments Title")
pickerViewController.switchVisible = true
pickerViewController.switchOn = settings.commentsCloseAutomatically
pickerViewController.switchText = NSLocalizedString("Automatically Close", comment: "Discussion Settings")
pickerViewController.selectionText = NSLocalizedString("Close after", comment: "Close comments after a given number of days")
pickerViewController.selectionFormat = NSLocalizedString("%d days", comment: "Number of days")
pickerViewController.pickerHint = NSLocalizedString("Automatically close comments on content after a certain number of days.", comment: "Discussion Settings: Comments Auto-close")
pickerViewController.pickerFormat = NSLocalizedString("%d days", comment: "Number of days")
pickerViewController.pickerMinimumValue = commentsAutocloseMinimumValue
pickerViewController.pickerMaximumValue = commentsAutocloseMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsCloseAutomaticallyAfterDays as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsCloseAutomatically = enabled
self?.settings.commentsCloseAutomaticallyAfterDays = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedSortBy(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Sort By", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsSortOrder
settingsViewController.titles = CommentsSorting.allTitles
settingsViewController.values = CommentsSorting.allValues
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newSortOrder = CommentsSorting(rawValue: selected as! Int) else {
return
}
self?.settings.commentsSorting = newSortOrder
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedThreading(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Threading", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsThreading.rawValue as NSObject
settingsViewController.titles = CommentsThreading.allTitles
settingsViewController.values = CommentsThreading.allValues
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newThreadingDepth = CommentsThreading(rawValue: selected as! Int) else {
return
}
self?.settings.commentsThreading = newThreadingDepth
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedPaging(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Paging", comment: "Comments Paging")
pickerViewController.switchVisible = true
pickerViewController.switchOn = settings.commentsPagingEnabled
pickerViewController.switchText = NSLocalizedString("Paging", comment: "Discussion Settings")
pickerViewController.selectionText = NSLocalizedString("Comments per page", comment: "A label title.")
pickerViewController.pickerHint = NSLocalizedString("Break comment threads into multiple pages.", comment: "Text snippet summarizing what comment paging does.")
pickerViewController.pickerMinimumValue = commentsPagingMinimumValue
pickerViewController.pickerMaximumValue = commentsPagingMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsPageSize as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsPagingEnabled = enabled
self?.settings.commentsPageSize = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedAutomaticallyApprove(_ payload: AnyObject?) {
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Automatically Approve", comment: "Discussion Settings Title")
settingsViewController.currentValue = settings.commentsAutoapproval.rawValue as NSObject
settingsViewController.titles = CommentsAutoapproval.allTitles
settingsViewController.values = CommentsAutoapproval.allValues
settingsViewController.hints = CommentsAutoapproval.allHints
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
guard let newApprovalStatus = CommentsAutoapproval(rawValue: selected as! Int) else {
return
}
self?.settings.commentsAutoapproval = newApprovalStatus
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedLinksInComments(_ payload: AnyObject?) {
let pickerViewController = SettingsPickerViewController(style: .grouped)
pickerViewController.title = NSLocalizedString("Links in comments", comment: "Comments Paging")
pickerViewController.switchVisible = false
pickerViewController.selectionText = NSLocalizedString("Links in comments", comment: "A label title")
pickerViewController.pickerHint = NSLocalizedString("Require manual approval for comments that include more than this number of links.", comment: "An explaination of a setting.")
pickerViewController.pickerMinimumValue = commentsLinksMinimumValue
pickerViewController.pickerMaximumValue = commentsLinksMaximumValue
pickerViewController.pickerSelectedValue = settings.commentsMaximumLinks as? Int
pickerViewController.onChange = { [weak self] (enabled: Bool, newValue: Int) in
self?.settings.commentsMaximumLinks = newValue as NSNumber
}
navigationController?.pushViewController(pickerViewController, animated: true)
}
fileprivate func pressedModeration(_ payload: AnyObject?) {
let moderationKeys = settings.commentsModerationKeys
let settingsViewController = SettingsListEditorViewController(collection: moderationKeys)
settingsViewController.title = NSLocalizedString("Hold for Moderation", comment: "Moderation Keys Title")
settingsViewController.insertTitle = NSLocalizedString("New Moderation Word", comment: "Moderation Keyword Insertion Title")
settingsViewController.editTitle = NSLocalizedString("Edit Moderation Word", comment: "Moderation Keyword Edition Title")
settingsViewController.footerText = NSLocalizedString("When a comment contains any of these words in its content, name, URL, e-mail or IP, it will be held in the moderation queue. You can enter partial words, so \"press\" will match \"WordPress\".",
comment: "Text rendered at the bottom of the Discussion Moderation Keys editor")
settingsViewController.onChange = { [weak self] (updated: Set<String>) in
self?.settings.commentsModerationKeys = updated
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
fileprivate func pressedBlocklist(_ payload: AnyObject?) {
let blocklistKeys = settings.commentsBlocklistKeys
let settingsViewController = SettingsListEditorViewController(collection: blocklistKeys)
settingsViewController.title = NSLocalizedString("Blocklist", comment: "Blocklist Title")
settingsViewController.insertTitle = NSLocalizedString("New Blocklist Word", comment: "Blocklist Keyword Insertion Title")
settingsViewController.editTitle = NSLocalizedString("Edit Blocklist Word", comment: "Blocklist Keyword Edition Title")
settingsViewController.footerText = NSLocalizedString("When a comment contains any of these words in its content, name, URL, e-mail, or IP, it will be marked as spam. You can enter partial words, so \"press\" will match \"WordPress\".",
comment: "Text rendered at the bottom of the Discussion Blocklist Keys editor")
settingsViewController.onChange = { [weak self] (updated: Set<String>) in
self?.settings.commentsBlocklistKeys = updated
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
// MARK: - Computed Properties
fileprivate var sections: [Section] {
return [postsSection, commentsSection, otherSection]
}
fileprivate var postsSection: Section {
let headerText = NSLocalizedString("Defaults for New Posts", comment: "Discussion Settings: Posts Section")
let footerText = NSLocalizedString("You can override these settings for individual posts.", comment: "Discussion Settings: Footer Text")
let rows = [
Row(style: .Switch,
title: NSLocalizedString("Allow Comments", comment: "Settings: Comments Enabled"),
boolValue: self.settings.commentsAllowed,
handler: { [weak self] in
self?.pressedCommentsAllowed($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Send Pingbacks", comment: "Settings: Sending Pingbacks"),
boolValue: self.settings.pingbackOutboundEnabled,
handler: { [weak self] in
self?.pressedPingbacksOutbound($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Receive Pingbacks", comment: "Settings: Receiving Pingbacks"),
boolValue: self.settings.pingbackInboundEnabled,
handler: { [weak self] in
self?.pressedPingbacksInbound($0)
})
]
return Section(headerText: headerText, footerText: footerText, rows: rows)
}
fileprivate var commentsSection: Section {
let headerText = NSLocalizedString("Comments", comment: "Settings: Comment Sections")
let rows = [
Row(style: .Switch,
title: NSLocalizedString("Require name and email", comment: "Settings: Comments Approval settings"),
boolValue: self.settings.commentsRequireNameAndEmail,
handler: { [weak self] in
self?.pressedRequireNameAndEmail($0)
}),
Row(style: .Switch,
title: NSLocalizedString("Require users to log in", comment: "Settings: Comments Approval settings"),
boolValue: self.settings.commentsRequireRegistration,
handler: { [weak self] in
self?.pressedRequireRegistration($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Close Commenting", comment: "Settings: Close comments after X period"),
details: self.detailsForCloseCommenting,
handler: { [weak self] in
self?.pressedCloseCommenting($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Sort By", comment: "Settings: Comments Sort Order"),
details: self.detailsForSortBy,
handler: { [weak self] in
self?.pressedSortBy($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Threading", comment: "Settings: Comments Threading preferences"),
details: self.detailsForThreading,
handler: { [weak self] in
self?.pressedThreading($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Paging", comment: "Settings: Comments Paging preferences"),
details: self.detailsForPaging,
handler: { [weak self] in
self?.pressedPaging($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Automatically Approve", comment: "Settings: Comments Approval settings"),
details: self.detailsForAutomaticallyApprove,
handler: { [weak self] in
self?.pressedAutomaticallyApprove($0)
}),
Row(style: .Value1,
title: NSLocalizedString("Links in comments", comment: "Settings: Comments Approval settings"),
details: self.detailsForLinksInComments,
handler: { [weak self] in
self?.pressedLinksInComments($0)
}),
]
return Section(headerText: headerText, rows: rows)
}
fileprivate var otherSection: Section {
let rows = [
Row(style: .Value1,
title: NSLocalizedString("Hold for Moderation", comment: "Settings: Comments Moderation"),
handler: self.pressedModeration),
Row(style: .Value1,
title: NSLocalizedString("Blocklist", comment: "Settings: Comments Blocklist"),
handler: self.pressedBlocklist)
]
return Section(rows: rows)
}
// MARK: - Row Detail Helpers
fileprivate var detailsForCloseCommenting: String {
if !settings.commentsCloseAutomatically {
return NSLocalizedString("Off", comment: "Disabled")
}
let numberOfDays = settings.commentsCloseAutomaticallyAfterDays ?? 0
let format = NSLocalizedString("%@ days", comment: "Number of days after which comments should autoclose")
return String(format: format, numberOfDays)
}
fileprivate var detailsForSortBy: String {
return settings.commentsSorting.description
}
fileprivate var detailsForThreading: String {
if !settings.commentsThreadingEnabled {
return NSLocalizedString("Off", comment: "Disabled")
}
let levels = settings.commentsThreadingDepth ?? 0
let format = NSLocalizedString("%@ levels", comment: "Number of Threading Levels")
return String(format: format, levels)
}
fileprivate var detailsForPaging: String {
if !settings.commentsPagingEnabled {
return NSLocalizedString("None", comment: "Disabled")
}
let pageSize = settings.commentsPageSize ?? 0
let format = NSLocalizedString("%@ comments", comment: "Number of Comments per Page")
return String(format: format, pageSize)
}
fileprivate var detailsForAutomaticallyApprove: String {
switch settings.commentsAutoapproval {
case .disabled:
return NSLocalizedString("None", comment: "No comment will be autoapproved")
case .everything:
return NSLocalizedString("All", comment: "Autoapprove every comment")
case .fromKnownUsers:
return NSLocalizedString("Known Users", comment: "Autoapprove only from known users")
}
}
fileprivate var detailsForLinksInComments: String {
guard let numberOfLinks = settings.commentsMaximumLinks else {
return String()
}
let format = NSLocalizedString("%@ links", comment: "Number of Links")
return String(format: format, numberOfLinks)
}
// MARK: - Private Nested Classes
fileprivate class Section {
let headerText: String?
let footerText: String?
let rows: [Row]
init(headerText: String? = nil, footerText: String? = nil, rows: [Row]) {
self.headerText = headerText
self.footerText = footerText
self.rows = rows
}
}
fileprivate class Row {
let style: Style
let title: String?
let details: String?
let handler: Handler?
var boolValue: Bool?
init(style: Style, title: String? = nil, details: String? = nil, boolValue: Bool? = nil, handler: Handler? = nil) {
self.style = style
self.title = title
self.details = details
self.boolValue = boolValue
self.handler = handler
}
typealias Handler = ((AnyObject?) -> Void)
enum Style: String {
case Value1 = "Value1"
case Switch = "SwitchCell"
}
}
// MARK: - Private Properties
fileprivate var blog: Blog!
// MARK: - Computed Properties
fileprivate var settings: BlogSettings {
return blog.settings!
}
// MARK: - Typealiases
fileprivate typealias CommentsSorting = BlogSettings.CommentsSorting
fileprivate typealias CommentsThreading = BlogSettings.CommentsThreading
fileprivate typealias CommentsAutoapproval = BlogSettings.CommentsAutoapproval
// MARK: - Constants
fileprivate let commentsPagingMinimumValue = 1
fileprivate let commentsPagingMaximumValue = 100
fileprivate let commentsLinksMinimumValue = 1
fileprivate let commentsLinksMaximumValue = 100
fileprivate let commentsAutocloseMinimumValue = 1
fileprivate let commentsAutocloseMaximumValue = 120
}
| gpl-2.0 |
Shivam0911/IOS-Training-Projects | ListViewToGridViewConverter/ListViewToGridViewConverter/ListToGridVC.swift | 1 | 6140 | //
// ListToGridVC.swift
// ListViewToGridViewConverter
//
// Created by MAC on 13/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class ListToGridVC: UIViewController {
var flag = 0
let carData = CarData()
let indexCount = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
@IBOutlet weak var appInventivLogo: UIImageView!
@IBOutlet weak var listButtonOutlet: UIButton!
@IBOutlet weak var gridButtonOutlet: UIButton!
@IBOutlet weak var imageViewCollectionOutlet: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
imageViewCollectionOutlet.dataSource = self
imageViewCollectionOutlet.delegate = self
let listcellnib = UINib(nibName: "listViewCell", bundle: nil)
imageViewCollectionOutlet.register(listcellnib, forCellWithReuseIdentifier: "ListID")
let gridcellnib = UINib(nibName: "GridViewCell", bundle: nil)
imageViewCollectionOutlet.register(gridcellnib, forCellWithReuseIdentifier: "GridCellID")
appInventivLogo.layer.cornerRadius = appInventivLogo.layer.bounds.width/2
// self.listButtonOutlet.layer.borderWidth = 1
// self.listButtonOutlet.layer.borderColor = UIColor.black.cgColor
// self.gridButtonOutlet.layer.borderWidth = 1
// self.gridButtonOutlet.layer.borderColor = UIColor.black.cgColor
// Do any additional setup after loading the view.
}
}
extension ListToGridVC : UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.carData.car.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
if indexPath.row < carData.car.count {
if flag == 0 {
let cell1 = returnGridCell(collectionView,indexPath)
return cell1
}
else {
let cell2 = returnListCell(collectionView,indexPath)
return cell2
}
}
else {
fatalError("no cell to display")
}
}
// MARK: UICollectionViewDelegateFlowLayout Methods
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: 30, height: 30)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if flag == 0 {
let width = 170.0
return CGSize(width: width, height: width + 20.0)
}
else {
let width = 400 //self.imageViewCollectionOutlet.frame.width
return CGSize(width: width, height: 70)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK : GridButtonAction
@IBAction func gridButtonPressed(_ sender: UIButton) {
flag = 0
imageViewCollectionOutlet.reloadData()
sender.backgroundColor = UIColor.gray
sender.titleLabel?.textColor = UIColor.white
listButtonOutlet.backgroundColor = UIColor.lightGray
// imageViewCollectionOutlet.performBatchUpdates({ }, completion: nil)
}
//MARK : ListButtonAction
@IBAction func listButtonPressed(_ sender: UIButton) {
flag = 1
imageViewCollectionOutlet.reloadData()
sender.backgroundColor = UIColor.gray
sender.titleLabel?.textColor = UIColor.white
gridButtonOutlet.backgroundColor = UIColor.lightGray
// imageViewCollectionOutlet.performBatchUpdates({ }, completion: nil)
}
}
extension ListToGridVC {
//MARK : ReturnGridCell Method
func returnGridCell(_ collectionView: UICollectionView,_ indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GridCellID", for: indexPath) as? GridViewCell else{
fatalError("Cell Not Found !")
}
cell.populateTheDataInGridView(carData.car[indexPath.item] as! [String : String])
return cell
}
//MARK: ReturnListCell Method
func returnListCell(_ collectionView: UICollectionView,_ indexPath: IndexPath) -> UICollectionViewCell {
print("flag = \(flag)")
print(#function)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListID", for: indexPath) as? listViewCell else{
fatalError("Cell Not Found !")
}
cell.populateTheData(carData.car[indexPath.item] as! [String : String])
return cell
}
}
| mit |
uasys/swift | test/SILGen/c_materializeForSet_linkage.swift | 4 | 915 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import AppKit
protocol Pointable {
var x: Float { get set }
var y: Float { get set }
}
extension NSPoint: Pointable {}
extension NSReferencePoint: Pointable {}
// Make sure synthesized materializeForSet and its callbacks have shared linkage
// for properties imported from Clang
// CHECK-LABEL: sil shared [transparent] [serializable] @_T0SC7NSPointV1xSfvm
// CHECK-LABEL: sil shared [transparent] [serializable] @_T0SC7NSPointV1ySfvm
// CHECK-LABEL: sil shared [serializable] @_T0So16NSReferencePointC1xSfvmytfU_
// CHECK-LABEL: sil shared [serializable] @_T0So16NSReferencePointC1xSfvm
// CHECK-LABEL: sil shared [serializable] @_T0So16NSReferencePointC1ySfvmytfU_
// CHECK-LABEL: sil shared [serializable] @_T0So16NSReferencePointC1ySfvm
| apache-2.0 |
duliodenis/cs193p-Spring-2016 | democode/Smashtag-L11/Smashtag/Tweet+CoreDataProperties.swift | 1 | 515 | //
// Tweet+CoreDataProperties.swift
// Smashtag
//
// Created by CS193p Instructor.
// Copyright © 2016 Stanford University. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Tweet {
@NSManaged var text: String?
@NSManaged var unique: String?
@NSManaged var posted: NSDate?
@NSManaged var tweeter: TwitterUser?
}
| mit |
Nykho/Swifternalization | Swifternalization/LoadedTranslation.swift | 4 | 634 | //
// LoadedTranslation.swift
// Swifternalization
//
// Created by Tomasz Szulc on 30/07/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Struct that represents loaded translation.
*/
struct LoadedTranslation {
/**
A type of translation. It is used later to convert object into translation
correclty.
*/
let type: LoadedTranslationType
/**
Key that identifies this translation.
*/
var key: String
/**
A content of translation just loaded from a file user in future processing.
*/
let content: Dictionary<String, AnyObject>
}
| mit |
google/swift-benchmark | Tests/BenchmarkTests/MockTextOutputStream.swift | 1 | 955 | // Copyright 2020 Google LLC
//
// 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.
@testable import Benchmark
final class MockTextOutputStream: FlushableTextOutputStream {
public private(set) var lines: [String] = []
func write(_ string: String) {
guard !string.isEmpty else { return }
lines.append(string)
}
func flush() {
}
func result() -> String {
return lines.joined(separator: "\n")
}
}
| apache-2.0 |
lorentey/swift | test/decl/protocol/sr8767.swift | 21 | 1493 | // RUN: %target-typecheck-verify-swift
// SR-8767: a number of related problems with unqualified lookup of
// associated type names.
// #1
public protocol PA {
associatedtype F
}
public protocol PDA : PA {
}
public protocol PrB {
associatedtype F
}
extension PDA where Self : PrB {
public init(first: F?) {
fatalError()
}
}
// #2
public protocol S { associatedtype F }
public protocol AM : S {}
public protocol AL { associatedtype F }
extension AM where Self : AL {
public init(first: F?) { fatalError() }
}
// #3
public protocol S2 { associatedtype F }
public protocol A2 : S2 {}
public protocol Z2 { associatedtype F }
extension A2 where Self : Z2 {
public init(first: F?) { fatalError() }
}
// #4
public protocol BM { associatedtype F }
public protocol C : BM {}
public protocol BL { associatedtype F }
extension C where Self : BL { public init(first: F?) { fatalError() } }
// #5
public protocol AZ { associatedtype F }
public protocol ZA : AZ {}
public protocol AA { associatedtype F }
extension ZA where Self : AA { public init(first: F?) { fatalError() } }
// #6
public protocol AZ2 { associatedtype F }
public protocol ZA2 : AZ2 {}
public protocol ZZ2 { associatedtype F }
extension ZA2 where Self : ZZ2 { public init(first: F?) { fatalError() } }
// #7
public protocol ZA3 { associatedtype F }
public protocol AZ3 : ZA3 {}
public protocol ZZ3 { associatedtype F }
extension AZ3 where Self : ZZ3 { public init(first: F?) { fatalError() } }
| apache-2.0 |
powerytg/Accented | Accented/Core/Storage/Models/CommentCollectionModel.swift | 1 | 750 | //
// CommentCollectionModel.swift
// Accented
//
// Collection model that represents a specific photo's comments and replies
//
// Created by Tiangong You on 5/23/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class CommentCollectionModel: CollectionModel<CommentModel> {
// Parent photo id
var photoId : String
init(photoId : String) {
self.photoId = photoId
super.init()
// Generate an uuid
self.modelId = photoId
}
override func copy(with zone: NSZone? = nil) -> Any {
let clone = CommentCollectionModel(photoId : photoId)
clone.totalCount = self.totalCount
clone.items = items
return clone
}
}
| mit |
thatseeyou/SpriteKitExamples.playground | Pages/Slither.xcplaygroundpage/Contents.swift | 1 | 3570 | /*:
### Joint 예제
*
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
let pi:CGFloat = CGFloat(M_PI)
override func didMove(to view: SKView) {
if self.contentCreated != true {
self.physicsWorld.speed = 1.0
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
var prevNode : SKNode?
for i in 0..<10 {
let currentNode = addBall(CGPoint(x: 40 + 20 * CGFloat(i), y: 240))
if let prevNode = prevNode {
// anchorA, anchorB의 좌표는 scene이 된다.
let limitJoint = SKPhysicsJointLimit.joint(withBodyA: prevNode.physicsBody!, bodyB: currentNode.physicsBody!, anchorA: prevNode.position, anchorB: currentNode.position)
limitJoint.maxLength = 30.0
self.physicsWorld.add(limitJoint)
}
prevNode = currentNode
}
// 마지막 노드 1개에만 힘을 가한다.
prevNode?.physicsBody?.applyForce(CGVector(dx: 0, dy: -9.8))
// let head = prevNode as! SKShapeNode
// do {
// head.name = "head"
// head.strokeColor = [#Color(colorLiteralRed: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 1)#]
// head.position = CGPointMake(280, 100)
// }
self.contentCreated = true
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let nodes = self.nodes(at: location)
for node in nodes {
if node.name == "head" {
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let nodes = self.nodes(at: location)
for node in nodes {
if node.name == "head" {
}
}
}
}
func addBall(_ position:CGPoint) -> SKNode {
let radius = CGFloat(20.0)
let ball = SKShapeNode(circleOfRadius: radius)
ball.position = position
ball.physicsBody = SKPhysicsBody(circleOfRadius: radius)
ball.physicsBody?.categoryBitMask = 0x1
ball.physicsBody?.collisionBitMask = 0x2
addChild(ball)
return ball
}
func angularImpulse() -> SKAction {
let waitAction = SKAction.wait(forDuration: 2.0)
let impulse = SKAction.applyAngularImpulse(0.7, duration: 3.0)
let delayImpulse = SKAction.sequence([waitAction, impulse])
return delayImpulse
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size: CGSize(width: 320, height: 480))
do {
scene.scaleMode = .aspectFit
}
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
do {
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.presentScene(scene)
}
self.view.addSubview(skView)
}
}
PlaygroundHelper.showViewController(ViewController())
| isc |
ronp001/SwiftRedis | SwiftRedis/RedisResponse.swift | 1 | 6473 | //
// RedisResponse.swift
// ActivityKeeper
//
// Created by Ron Perry on 11/7/15.
// Copyright © 2015 ronp001. All rights reserved.
//
import Foundation
class RedisResponse : CustomStringConvertible {
enum ResponseType { case int, string, data, error, array, unknown }
class ParseError : NSError {
init(msg: String) {
super.init(domain: "RedisResponse", code: 0, userInfo: ["message": msg])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let responseType: ResponseType
var intVal: Int?
fileprivate var stringValInternal: String?
var stringVal: String? {
get {
switch responseType {
case .string:
return self.stringValInternal
case .data:
return String(describing: NSString(data: self.dataVal!, encoding: String.Encoding.utf8.rawValue))
case .int:
return String(describing: intVal)
case .error:
return nil
case .unknown:
return nil
case .array:
var ar: [String?] = []
for elem in arrayVal! {
ar += [elem.stringVal]
}
return String(describing: ar)
}
}
set(value) {
stringValInternal = value
}
}
var dataVal: Data?
var errorVal: String?
var arrayVal: [RedisResponse]?
var parseErrorMsg: String? = nil
init(intVal: Int? = nil, dataVal: Data? = nil, stringVal: String? = nil, errorVal: String? = nil, arrayVal: [RedisResponse]? = nil, responseType: ResponseType? = nil)
{
self.parseErrorMsg = nil
self.intVal = intVal
self.stringValInternal = stringVal
self.errorVal = errorVal
self.arrayVal = arrayVal
self.dataVal = dataVal
if intVal != nil { self.responseType = .int }
else if stringVal != nil { self.responseType = .string }
else if errorVal != nil { self.responseType = .error }
else if arrayVal != nil { self.responseType = .array }
else if dataVal != nil { self.responseType = .data }
else if responseType != nil { self.responseType = responseType! }
else { self.responseType = .unknown }
if self.responseType == .array && self.arrayVal == nil {
self.arrayVal = [RedisResponse]()
}
}
func parseError(_ msg: String)
{
NSLog("Parse error - \(msg)")
parseErrorMsg = msg
}
// should only be called if the current object responseType is .Array
func addArrayElement(_ response: RedisResponse)
{
self.arrayVal!.append(response)
}
var description: String {
var result = "RedisResponse(\(self.responseType):"
switch self.responseType {
case .error:
result += self.errorVal!
case .string:
result += self.stringVal!
case .int:
result += String(self.intVal!)
case .data:
result += "[Data - \(self.dataVal!.count) bytes]"
case .array:
result += "[Array - \(self.arrayVal!.count) elements]"
case .unknown:
result += "?"
break
}
result += ")"
return result
}
// reads data from the buffer according to own responseType
func readValueFromBuffer(_ buffer: RedisBuffer, numBytes: Int?) -> Bool?
{
let data = buffer.getNextDataOfSize(numBytes)
if data == nil { return nil }
if numBytes != nil { // ensure there is also a CRLF after the buffer
let crlfData = buffer.getNextDataUntilCRLF()
if crlfData == nil { // didn't find data
buffer.restoreRemovedData(data!)
return nil
}
// if the data was CRLF, it would have been removed by getNxtDataUntilCRLF, so buffer should be empty
if crlfData!.count != 0 {
buffer.restoreRemovedData(crlfData!)
return false
}
}
switch responseType {
case .data:
self.dataVal = data
return true
case .string:
self.stringVal = String(data: data!, encoding: String.Encoding.utf8)
if ( self.stringVal == nil ) {
parseError("Could not parse string")
return false
}
return true
case .error:
self.errorVal = String(data: data!, encoding: String.Encoding.utf8)
if ( self.errorVal == nil ) {
parseError("Could not parse string")
return false
}
return true
case .int:
let str = String(data: data!, encoding: String.Encoding.utf8)
if ( str == nil ) {
parseError("Could not parse string")
return false
}
self.intVal = Int(str!)
if ( self.intVal == nil ) {
parseError("Received '\(str)' when expecting Integer")
return false
}
return true
case .array:
parseError("Array parsing not supported yet")
return false
case .unknown:
parseError("Trying to parse when ResponseType == .Unknown")
return false
}
}
}
func != (left: RedisResponse, right: RedisResponse) -> Bool {
return !(left == right)
}
func == (left: RedisResponse, right: RedisResponse) -> Bool {
if left.responseType != right.responseType { return false }
switch left.responseType {
case .int:
return left.intVal == right.intVal
case .string:
return left.stringVal == right.stringVal
case .error:
return left.errorVal == right.errorVal
case .unknown:
return true
case .data:
return (left.dataVal! == right.dataVal!)
case .array:
if left.arrayVal!.count != right.arrayVal!.count { return false }
for i in 0 ... left.arrayVal!.count-1 {
if !(left.arrayVal![i] == right.arrayVal![i]) { return false }
}
return true
}
}
| mit |
JohnCoates/Aerial | Aerial/Source/Models/API/APISecrets.swift | 1 | 556 | //
// APISecrets.swift
// Aerial
//
// Created by Guillaume Louel on 25/03/2020.
// Copyright © 2020 Guillaume Louel. All rights reserved.
//
import Foundation
// This is where Aerial stores credentials for various external API providers.
// Those are intentionally left blank in the repository, as to keep them secret
// and still let them be used for everyone in the officially distributed Aerial.
struct APISecrets {
static let yahooAppId = "intentionally"
static let yahooClientId = "left"
static let yahooClientSecret = "empty!"
}
| mit |
kickstarter/ios-oss | Kickstarter-iOS/Features/Comments/Views/Cells/RootCommentCell.swift | 1 | 2567 | import KsApi
import Library
import Prelude
import UIKit
private enum Layout {
enum Border {
static let height: CGFloat = 1.0
}
}
final class RootCommentCell: UITableViewCell, ValueCell {
// MARK: - Properties
private lazy var bodyTextView: UITextView = { UITextView(frame: .zero) }()
private lazy var bottomBorder: UIView = {
UIView(frame: .zero)
|> \.backgroundColor .~ UIColor.ksr_support_200
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var commentCellHeaderStackView: CommentCellHeaderStackView = {
CommentCellHeaderStackView(frame: .zero)
}()
private lazy var rootStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private let viewModel = RootCommentCellViewModel()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.bindStyles()
self.configureViews()
self.bindViewModel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
_ = self.rootStackView
|> commentCellRootStackViewStyle
_ = self.bodyTextView
|> commentBodyTextViewStyle
}
// MARK: - Configuration
internal func configureWith(value: Comment) {
self.commentCellHeaderStackView
.configureWith(comment: value)
self.viewModel.inputs.configureWith(comment: value)
}
private func configureViews() {
let rootViews = [
self.commentCellHeaderStackView,
self.bodyTextView
]
_ = (self.rootStackView, self.contentView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = (rootViews, self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = (self.bottomBorder, self.contentView)
|> ksr_addSubviewToParent()
NSLayoutConstraint.activate([
self.bottomBorder.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
self.bottomBorder.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
self.bottomBorder.bottomAnchor.constraint(equalTo: self.rootStackView.bottomAnchor),
self.bottomBorder.heightAnchor.constraint(equalToConstant: Layout.Border.height)
])
}
// MARK: - View model
internal override func bindViewModel() {
self.bodyTextView.rac.text = self.viewModel.outputs.body
}
}
| apache-2.0 |
neonichu/realm-cocoa | RealmSwift-swift2.0/Realm.swift | 2 | 22204 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `init(inMemoryIdentifier:)`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
- warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/**
The location of the default Realm as a string. Can be overridden.
`~/Library/Application Support/{bundle ID}/default.realm` on OS X.
`default.realm` in your application's documents directory on iOS.
- returns: Location of the default Realm.
*/
public class var defaultPath: String {
get {
return RLMRealm.defaultRealmPath()
}
set {
RLMRealm.setDefaultRealmPath(newValue)
}
}
// MARK: Initializers
/**
Obtains a Realm instance persisted at the specified file path. Defaults to
`Realm.defaultPath`
- parameter path: Path to the realm file.
*/
public convenience init(path: String = Realm.defaultPath) throws {
let rlmRealm = try RLMRealm(path: path, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance with persistence to a specific file path with
options.
Like `init(path:)`, but with the ability to open read-only realms and
encrypted realms.
- warning: Read-only Realms do not support changes made to the file while the
`Realm` exists. This means that you cannot open a Realm as both read-only
and read-write at the same time. Read-only Realms should normally only be used
on files which cannot be opened in read-write mode, and not just for enforcing
correctness in code that should not need to write to the Realm.
- parameter path: Path to the file you want the data saved in.
- parameter readOnly: Bool indicating if this Realm is read-only (must use for read-only files).
- parameter encryptionKey: 64-byte key to use to encrypt the data.
*/
public convenience init(path: String, readOnly: Bool, encryptionKey: NSData? = nil) throws {
let rlmRealm = try RLMRealm(path: path, key: encryptionKey, readOnly: readOnly, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
/**
Obtains a Realm instance for an un-persisted in-memory Realm. The identifier
used to create this instance can be used to access the same in-memory Realm from
multiple threads.
Because in-memory Realms are not persisted, you must be sure to hold on to a
reference to the `Realm` object returned from this for as long as you want
the data to last. Realm's internal cache of `Realm`s will not keep the
in-memory Realm alive across cycles of the run loop, so without a strong
reference to the `Realm` a new Realm will be created each time. Note that
`Object`s, `List`s, and `Results` that refer to objects persisted in a Realm have a
strong reference to the relevant `Realm`, as do `NotifcationToken`s.
- parameter identifier: A string used to identify a particular in-memory Realm.
*/
public convenience init(inMemoryIdentifier: String) {
self.init(RLMRealm.inMemoryRealmWithIdentifier(inMemoryIdentifier))
}
// MARK: Transactions
/**
Helper to perform actions contained within the given block inside a write transation.
- parameter block: The block to be executed inside a write transaction.
*/
public func write(block: (() -> Void)) {
rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction with throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction.
After this is called, the `Realm` reverts back to being read-only.
Calling this when not in a write transaction will throw an exception.
*/
public func commitWrite() {
rlmRealm.commitWriteTransaction()
}
/**
Revert all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not reinstate deleted
accessor objects. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all linked (child) objects referenced by this object will also be
added to the Realm if they are not already in it. If the object or any linked
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
- parameter object: Object to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
- see: add(object:update:)
- parameter objects: A sequence which contains objects to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given value.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- parameter type: The object type to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
// FIXME: use T.className()
let className = (T.self as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
- parameter object: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
- parameter type: The type of the objects to be returned.
- returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
// FIXME: use T.className()
return Results<T>(RLMGetObjects(rlmRealm, (T.self as Object.Type).className(), nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- parameter type: The type of the objects to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
// FIXME: use T.className()
return unsafeBitCast(RLMGetObject(rlmRealm, (T.self as Object.Type).className(), key), Optional<T>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
- returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
- parameter notificationToken: The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call -refresh on the Realm to
update it to get the latest version.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
- returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
- parameter path: Path to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws {
if let encryptionKey = encryptionKey {
try rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey)
} else {
try rlmRealm.writeCopyToPath(path)
}
}
// MARK: Encryption
/**
Set the encryption key to use when opening Realms at a certain path.
This can be used as an alternative to explicitly passing the key to
`Realm(path:, encryptionKey:, readOnly:, error:)` each time a Realm instance is
needed. The encryption key will be used any time a Realm is opened with
`Realm(path:)` or `Realm()`.
If you do not want Realm to hold on to your encryption keys any longer than
needed, then use `Realm(path:, encryptionKey:, readOnly:, error:)` rather than this
method.
- parameter encryptionKey: 64-byte encryption key to use, or `nil` to unset.
- parameter path: Realm path to set the encryption key for.
+*/
public class func setEncryptionKey(encryptionKey: NSData?, forPath: String = Realm.defaultPath) {
RLMRealm.setEncryptionKey(encryptionKey, forRealmsAtPath: forPath)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns whether the two realms are equal.
public func ==(lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange are posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`beginWriteTransaction()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notifcation has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
| apache-2.0 |
slxl/ReactKit | Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Alamofire/Source/ServerTrustPolicy.swift | 2 | 13027 | //
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
- returns: The new `ServerTrustPolicyManager` instance.
*/
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/**
Returns the `ServerTrustPolicy` for the given host if applicable.
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
this method and implement more complex mapping implementations such as wildcards.
- parameter host: The host to use when searching for a matching policy.
- returns: The server trust policy for the given host if found.
*/
public func serverTrustPolicyForHost(_ host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
*/
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((serverTrust: SecTrust, host: String) -> Bool)
// MARK: - Bundle Location
/**
Returns all certificates within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `.cer` files.
- returns: All certificates within the given bundle.
*/
public static func certificatesInBundle(_ bundle: Bundle = Bundle.main()) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.pathsForResources(ofType: fileExtension, inDirectory: nil)
}.flatten())
for path in paths {
if let
certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)),
certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/**
Returns all public keys within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `*.cer` files.
- returns: All public keys within the given bundle.
*/
public static func publicKeysInBundle(_ bundle: Bundle = Bundle.main()) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificatesInBundle(bundle) {
if let publicKey = publicKeyForCertificate(certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/**
Evaluates whether the server trust is valid for the given host.
- parameter serverTrust: The server trust to evaluate.
- parameter host: The host of the challenge protection space.
- returns: Whether the server trust is valid.
*/
public func evaluateServerTrust(_ serverTrust: SecTrust, isValidForHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!] )
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!])
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy!])
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateDataForTrust(_ trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateDataForCertificates(certificates)
}
private func certificateDataForCertificates(_ certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeysForTrust(_ trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let
certificate = SecTrustGetCertificateAtIndex(trust, index),
publicKey = publicKeyForCertificate(certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKeyForCertificate(_ certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust where trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
| mit |
ngageoint/mage-ios | Mage/StraightLineNav/StraightLineNavigation.swift | 1 | 7707 | //
// StraightLineNavigation.swift
// MAGE
//
// Created by Daniel Barela on 3/25/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
struct StraightLineNavigationNotification {
var image: UIImage? = nil
var imageURL: URL? = nil
var title: String? = nil
var coordinate: CLLocationCoordinate2D
var user: User? = nil
var feedItem: FeedItem? = nil
var observation: Observation? = nil
}
protocol StraightLineNavigationDelegate {
func cancelStraightLineNavigation();
}
class StraightLineNavigation: NSObject {
var delegate: StraightLineNavigationDelegate?;
weak var mapView: MKMapView?;
weak var mapStack: UIStackView?;
var navigationModeEnabled: Bool = false
var headingModeEnabled: Bool = false
var navView: StraightLineNavigationView?;
var headingPolyline: NavigationOverlay?;
var relativeBearingPolyline: NavigationOverlay?;
var relativeBearingColor: UIColor {
get {
return UserDefaults.standard.bearingTargetColor;
}
}
var headingColor: UIColor {
get {
return UserDefaults.standard.headingColor;
}
}
init(mapView: MKMapView, locationManager: CLLocationManager?, mapStack: UIStackView) {
self.mapView = mapView;
self.mapStack = mapStack;
}
deinit {
navView?.removeFromSuperview();
navView = nil
}
func startNavigation(manager: CLLocationManager, destinationCoordinate: CLLocationCoordinate2D, delegate: StraightLineNavigationDelegate?, image: UIImage?, imageURL: URL?, scheme: MDCContainerScheming? = nil) {
navigationModeEnabled = true;
headingModeEnabled = true;
navView = StraightLineNavigationView(locationManager: manager, destinationMarker: image, destinationCoordinate: destinationCoordinate, delegate: delegate, scheme: scheme, targetColor: relativeBearingColor, bearingColor: headingColor);
navView?.destinationMarkerUrl = imageURL
updateNavigationLines(manager: manager, destinationCoordinate: destinationCoordinate);
self.delegate = delegate;
mapStack?.addArrangedSubview(navView!);
}
func startHeading(manager: CLLocationManager) {
headingModeEnabled = true;
updateHeadingLine(manager: manager);
}
@discardableResult
func stopHeading() -> Bool {
if (!navigationModeEnabled && headingModeEnabled) {
headingModeEnabled = false;
if let headingPolyline = headingPolyline {
mapView?.removeOverlay(headingPolyline);
}
return true;
}
return false;
}
func stopNavigation() {
if let navView = navView {
navView.removeFromSuperview()
}
navigationModeEnabled = false;
if let relativeBearingPolyline = relativeBearingPolyline {
mapView?.removeOverlay(relativeBearingPolyline);
}
if let headingPolyline = headingPolyline {
mapView?.removeOverlay(headingPolyline);
}
}
func calculateBearingPoint(startCoordinate: CLLocationCoordinate2D, bearing: CLLocationDirection) -> CLLocationCoordinate2D {
var metersDistanceForBearing = 500000.0;
let span = mapView?.region.span ?? MKCoordinateSpan(latitudeDelta: 5, longitudeDelta: 5)
let center = mapView?.region.center ?? startCoordinate
let loc1 = CLLocation(latitude: center.latitude - span.latitudeDelta, longitude: center.longitude)
let loc2 = CLLocation(latitude: center.latitude + span.latitudeDelta, longitude: center.longitude)
let loc3 = CLLocation(latitude: center.latitude, longitude: center.longitude - span.longitudeDelta)
let loc4 = CLLocation(latitude: center.latitude, longitude: center.longitude + span.longitudeDelta)
metersDistanceForBearing = min(metersDistanceForBearing, max(loc1.distance(from: loc2), loc3.distance(from: loc4)) * 2.0)
let radDirection = bearing * (.pi / 180.0);
return locationWithBearing(bearing: radDirection, distanceMeters: metersDistanceForBearing, origin: startCoordinate)
}
func locationWithBearing(bearing:Double, distanceMeters:Double, origin:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let distRadians = distanceMeters / (6372797.6) // earth radius in meters
let lat1 = origin.latitude * .pi / 180
let lon1 = origin.longitude * .pi / 180
let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing))
let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))
return CLLocationCoordinate2D(latitude: lat2 * 180 / .pi, longitude: lon2 * 180 / .pi)
}
func updateHeadingLine(manager: CLLocationManager) {
if (self.headingModeEnabled) {
guard let location = manager.location else {
return;
}
guard let userCoordinate = manager.location?.coordinate else {
return;
}
// if the user is moving, use their direction of movement
var bearing = location.course;
let speed = location.speed;
if (bearing < 0 || speed <= 0 || location.courseAccuracy < 0 || location.courseAccuracy >= 180) {
// if the user is not moving, use the heading of the phone or the course accuracy is invalid
if let trueHeading = manager.heading?.trueHeading {
bearing = trueHeading;
} else {
return;
}
}
let bearingPoint = MKMapPoint(calculateBearingPoint(startCoordinate: userCoordinate, bearing: bearing));
let userLocationPoint = MKMapPoint(userCoordinate)
let coordinates: [MKMapPoint] = [userLocationPoint, bearingPoint]
if (headingPolyline != nil) {
mapView?.removeOverlay(headingPolyline!);
}
headingPolyline = NavigationOverlay(points: coordinates, count: 2, color: headingColor)
headingPolyline?.accessibilityLabel = "heading"
mapView?.addOverlay(headingPolyline!, level: .aboveLabels);
navView?.populate(relativeBearingColor: relativeBearingColor, headingColor: headingColor);
}
}
func updateNavigationLines(manager: CLLocationManager, destinationCoordinate: CLLocationCoordinate2D?) {
guard let userCoordinate = manager.location?.coordinate else {
return;
}
if navigationModeEnabled, let destinationCoordinate = destinationCoordinate {
let userLocationPoint = MKMapPoint(userCoordinate)
let endCoordinate = MKMapPoint(destinationCoordinate)
let coordinates: [MKMapPoint] = [userLocationPoint, endCoordinate]
if (relativeBearingPolyline != nil) {
mapView?.removeOverlay(relativeBearingPolyline!);
}
relativeBearingPolyline = NavigationOverlay(points: coordinates, count: 2, color: relativeBearingColor)
relativeBearingPolyline?.accessibilityLabel = "relative bearing"
mapView?.addOverlay(relativeBearingPolyline!);
navView?.populate(relativeBearingColor: relativeBearingColor, headingColor: headingColor, destinationCoordinate: destinationCoordinate);
}
updateHeadingLine(manager: manager);
}
}
| apache-2.0 |
ngageoint/mage-ios | Mage/AttachmentCell.swift | 1 | 11384 | //
// AttachmentCell.m
// Mage
//
//
import UIKit
import Kingfisher
@objc class AttachmentCell: UICollectionViewCell {
private var button: MDCFloatingButton?;
private lazy var imageView: AttachmentUIImageView = {
let imageView: AttachmentUIImageView = AttachmentUIImageView(image: nil);
imageView.configureForAutoLayout();
imageView.clipsToBounds = true;
return imageView;
}();
override init(frame: CGRect) {
super.init(frame: frame);
self.configureForAutoLayout();
self.addSubview(imageView);
imageView.autoPinEdgesToSuperviewEdges();
setNeedsLayout();
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.imageView.kf.cancelDownloadTask();
self.imageView.image = nil;
for view in self.imageView.subviews{
view.removeFromSuperview()
}
button?.removeFromSuperview();
}
func getAttachmentUrl(attachment: Attachment) -> URL? {
if let localPath = attachment.localPath, FileManager.default.fileExists(atPath: localPath) {
return URL(fileURLWithPath: localPath);
} else if let url = attachment.url {
return URL(string: url);
}
return nil;
}
func getAttachmentUrl(size: Int, attachment: Attachment) -> URL? {
if let localPath = attachment.localPath, FileManager.default.fileExists(atPath: localPath) {
return URL(fileURLWithPath: localPath);
} else if let url = attachment.url {
return URL(string: String(format: "%@?size=%ld", url, size));
}
return nil;
}
override func removeFromSuperview() {
self.imageView.cancel();
}
@objc public func setImage(newAttachment: [String : AnyHashable], button: MDCFloatingButton? = nil, scheme: MDCContainerScheming? = nil) {
layoutSubviews();
self.button = button;
self.imageView.kf.indicatorType = .activity;
guard let contentType = newAttachment["contentType"] as? String, let localPath = newAttachment["localPath"] as? String else {
return
}
if (contentType.hasPrefix("image")) {
self.imageView.setImage(url: URL(fileURLWithPath: localPath), cacheOnly: !DataConnectionUtilities.shouldFetchAttachments());
self.imageView.accessibilityLabel = "attachment \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFill;
} else if (contentType.hasPrefix("video")) {
let provider: VideoImageProvider = VideoImageProvider(localPath: localPath);
self.imageView.contentMode = .scaleAspectFill;
DispatchQueue.main.async {
self.imageView.kf.setImage(with: provider, placeholder: UIImage(systemName: "play.circle.fill"), options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.transition(.fade(0.2)),
.scaleFactor(UIScreen.main.scale),
.processor(DownsamplingImageProcessor(size: self.imageView.frame.size)),
.cacheOriginalImage
], completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.contentMode = .scaleAspectFill;
self.imageView.accessibilityLabel = "local \(localPath) loaded";
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
case .failure(let error):
print(error);
self.imageView.backgroundColor = UIColor.init(white: 0, alpha: 0.06);
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
}
});
}
} else if (contentType.hasPrefix("audio")) {
self.imageView.image = UIImage(systemName: "speaker.wave.2.fill");
self.imageView.accessibilityLabel = "local \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
} else {
self.imageView.image = UIImage(systemName: "paperclip");
self.imageView.accessibilityLabel = "local \(localPath) loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
let label = UILabel.newAutoLayout()
label.text = newAttachment["contentType"] as? String
label.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6)
label.font = scheme?.typographyScheme.overline
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.autoSetDimension(.height, toSize: label.font.pointSize)
imageView.addSubview(label)
label.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), excludingEdge: .bottom)
}
self.backgroundColor = scheme?.colorScheme.surfaceColor
if let button = button {
self.addSubview(button);
button.autoPinEdge(.bottom, to: .bottom, of: self.imageView, withOffset: -8);
button.autoPinEdge(.right, to: .right, of: self.imageView, withOffset: -8);
}
}
@objc public func setImage(attachment: Attachment, formatName:NSString, button: MDCFloatingButton? = nil, scheme: MDCContainerScheming? = nil) {
layoutSubviews();
self.button = button;
self.imageView.kf.indicatorType = .activity;
if (attachment.contentType?.hasPrefix("image") ?? false) {
self.imageView.setAttachment(attachment: attachment);
self.imageView.tintColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.87);
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loading";
self.imageView.showThumbnail(cacheOnly: !DataConnectionUtilities.shouldFetchAttachments(),
completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
NSLog("Loaded the image \(self.imageView.accessibilityLabel ?? "")")
case .failure(let error):
print(error);
}
});
} else if (attachment.contentType?.hasPrefix("video") ?? false) {
guard let url = self.getAttachmentUrl(attachment: attachment) else {
self.imageView.contentMode = .scaleAspectFit;
self.imageView.image = UIImage(named: "upload");
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
return;
}
var localPath: String? = nil;
if (attachment.localPath != nil && FileManager.default.fileExists(atPath: attachment.localPath!)) {
localPath = attachment.localPath;
}
let provider: VideoImageProvider = VideoImageProvider(url: url, localPath: localPath);
self.imageView.contentMode = .scaleAspectFit;
DispatchQueue.main.async {
self.imageView.kf.setImage(with: provider, placeholder: UIImage(systemName: "play.circle.fill"), options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.transition(.fade(0.2)),
.scaleFactor(UIScreen.main.scale),
.processor(DownsamplingImageProcessor(size: self.imageView.frame.size)),
.cacheOriginalImage
], completionHandler:
{ result in
switch result {
case .success(_):
self.imageView.contentMode = .scaleAspectFill;
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
let overlay: UIImageView = UIImageView(image: UIImage(systemName: "play.circle.fill"));
overlay.contentMode = .scaleAspectFit;
self.imageView.addSubview(overlay);
overlay.autoCenterInSuperview();
case .failure(let error):
print(error);
}
});
}
} else if (attachment.contentType?.hasPrefix("audio") ?? false) {
self.imageView.image = UIImage(systemName: "speaker.wave.2.fill");
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
} else {
self.imageView.image = UIImage(systemName: "paperclip");
self.imageView.accessibilityLabel = "attachment \(attachment.name ?? "") loaded";
self.imageView.tintColor = scheme?.colorScheme.onBackgroundColor.withAlphaComponent(0.4);
self.imageView.contentMode = .scaleAspectFit;
let label = UILabel.newAutoLayout()
label.text = attachment.name
label.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6)
label.font = scheme?.typographyScheme.overline
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.autoSetDimension(.height, toSize: label.font.pointSize)
imageView.addSubview(label)
label.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), excludingEdge: .bottom)
}
self.backgroundColor = scheme?.colorScheme.backgroundColor
if let button = button {
self.addSubview(button);
button.autoPinEdge(.bottom, to: .bottom, of: self.imageView, withOffset: -8);
button.autoPinEdge(.right, to: .right, of: self.imageView, withOffset: -8);
}
}
}
| apache-2.0 |
takayoshiotake/SevenSegmentSampler_swift | SevenSegmentViewSampler/BBSevenSegmentView.swift | 1 | 4547 | //
// BBSevenSegmentView.swift
// SevenSegmentViewSampler
//
// Created by Takayoshi Otake on 2015/11/08.
// Copyright © 2015 Takayoshi Otake. All rights reserved.
//
import UIKit
@IBDesignable
class BBSevenSegmentView: UIView {
enum Pins {
case A
case B
case C
case D
case E
case F
case G
case DP
case QM
static let Values: [Pins] = [.A, .B, .C, .D, .E, .F, .G, .DP, .QM]
}
// protected
var switchesOnPins: [Pins: Bool] = [.A: false, .B: false, .C: false, .D: false, .E: false, .F: false, .G: false, .DP: false, .QM: false]
@IBInspectable
var pinA: Bool {
set {
switchesOnPins[Pins.A] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.A]!
}
}
@IBInspectable
var pinB: Bool {
set {
switchesOnPins[Pins.B] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.B]!
}
}
@IBInspectable
var pinC: Bool {
set {
switchesOnPins[Pins.C] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.C]!
}
}
@IBInspectable
var pinD: Bool {
set {
switchesOnPins[Pins.D] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.D]!
}
}
@IBInspectable
var pinE: Bool {
set {
switchesOnPins[Pins.E] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.E]!
}
}
@IBInspectable
var pinF: Bool {
set {
switchesOnPins[Pins.F] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.F]!
}
}
@IBInspectable
var pinG: Bool {
set {
switchesOnPins[Pins.G] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.G]!
}
}
@IBInspectable
var pinDP: Bool {
set {
switchesOnPins[Pins.DP] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.DP]!
}
}
@IBInspectable
var pinQM: Bool {
set {
switchesOnPins[Pins.QM] = newValue
setNeedsDisplay()
}
get {
return switchesOnPins[Pins.QM]!
}
}
@IBInspectable
var pinBits: Int16 {
set {
switchesOnPins[Pins.A] = (newValue >> 0) & 1 == 1
switchesOnPins[Pins.B] = (newValue >> 1) & 1 == 1
switchesOnPins[Pins.C] = (newValue >> 2) & 1 == 1
switchesOnPins[Pins.D] = (newValue >> 3) & 1 == 1
switchesOnPins[Pins.E] = (newValue >> 4) & 1 == 1
switchesOnPins[Pins.F] = (newValue >> 5) & 1 == 1
switchesOnPins[Pins.G] = (newValue >> 6) & 1 == 1
switchesOnPins[Pins.DP] = (newValue >> 7) & 1 == 1
switchesOnPins[Pins.QM] = (newValue >> 8) & 1 == 1
setNeedsDisplay()
}
get {
var value: Int16 = 0
value |= (switchesOnPins[Pins.A]! ? 1 : 0) << 0
value |= (switchesOnPins[Pins.B]! ? 1 : 0) << 1
value |= (switchesOnPins[Pins.C]! ? 1 : 0) << 2
value |= (switchesOnPins[Pins.D]! ? 1 : 0) << 3
value |= (switchesOnPins[Pins.E]! ? 1 : 0) << 4
value |= (switchesOnPins[Pins.F]! ? 1 : 0) << 5
value |= (switchesOnPins[Pins.G]! ? 1 : 0) << 6
value |= (switchesOnPins[Pins.DP]! ? 1 : 0) << 7
value |= (switchesOnPins[Pins.QM]! ? 1 : 0) << 8
return value
}
}
@IBInspectable
var onColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var offColor: UIColor? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
onColor = tintColor
offColor = tintColor.colorWithAlphaComponent(0.05)
self.backgroundColor = UIColor.clearColor()
}
}
| mit |
hyperoslo/Catalog | Source/Models/Card.swift | 1 | 239 | import Foundation
public class Card: NSObject {
public var item: Item?
public var relatedItems = [Item]()
public init(item: Item? = nil, relatedItems: [Item] = []) {
self.item = item
self.relatedItems = relatedItems
}
}
| mit |
xcodeswift/xcproj | Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildFileTests.swift | 1 | 204 | import Foundation
import XcodeProj
import XCTest
final class PBXBuildFileTests: XCTestCase {
func test_isa_returnsTheCorrectValue() {
XCTAssertEqual(PBXBuildFile.isa, "PBXBuildFile")
}
}
| mit |
eljeff/AudioKit | Sources/AudioKit/Internals/Microtonality/TuningTable+Scala.swift | 2 | 8985 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
extension TuningTable {
/// Use a Scala file to write the tuning table. Returns notes per octave or nil when file couldn't be read.
public func scalaFile(_ filePath: String) -> Int? {
guard
let contentData = FileManager.default.contents(atPath: filePath),
let contentStr = String(data: contentData, encoding: .utf8) else {
Log("can't read filePath: \(filePath)")
return nil
}
if let scalaFrequencies = frequencies(fromScalaString: contentStr) {
let npo = tuningTable(fromFrequencies: scalaFrequencies)
return npo
}
// error
return nil
}
fileprivate func stringTrimmedForLeadingAndTrailingWhiteSpacesFromString(_ inputString: String?) -> String? {
guard let string = inputString else {
return nil
}
let leadingTrailingWhiteSpacesPattern = "(?:^\\s+)|(?:\\s+$)"
let regex: NSRegularExpression
do {
try regex = NSRegularExpression(pattern: leadingTrailingWhiteSpacesPattern,
options: .caseInsensitive)
} catch let error as NSError {
Log("ERROR: create regex: \(error)")
return nil
}
let stringRange = NSRange(location: 0, length: string.count)
let trimmedString = regex.stringByReplacingMatches(in: string,
options: .reportProgress,
range: stringRange,
withTemplate: "$1")
return trimmedString
}
/// Get frequencies from a Scala string
public func frequencies(fromScalaString rawStr: String?) -> [Frequency]? {
guard let inputStr = rawStr else {
return nil
}
// default return value is [1.0]
var scalaFrequencies = [Frequency(1)]
var actualFrequencyCount = 1
var frequencyCount = 1
var parsedScala = true
var parsedFirstCommentLine = false
let values = inputStr.components(separatedBy: .newlines)
var parsedFirstNonCommentLine = false
var parsedAllFrequencies = false
// REGEX match for a cents or ratio
// (RATIO |CENTS )
// ( a / b |- a . b |- . b |- a .|- a )
let regexStr = "(\\d+\\/\\d+|-?\\d+\\.\\d+|-?\\.\\d+|-?\\d+\\.|-?\\d+)"
let regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: regexStr,
options: .caseInsensitive)
} catch let error as NSError {
Log("ERROR: cannot parse scala file: \(error)")
return scalaFrequencies
}
for rawLineStr in values {
var lineStr = stringTrimmedForLeadingAndTrailingWhiteSpacesFromString(rawLineStr) ?? rawLineStr
if lineStr.isEmpty { continue }
if lineStr.hasPrefix("!") {
if !parsedFirstCommentLine {
parsedFirstCommentLine = true
#if false
// currently not using the scala file name embedded in the file
let components = lineStr.components(separatedBy: "!")
if components.count > 1 {
proposedScalaFilename = components[1]
}
#endif
}
continue
}
if !parsedFirstNonCommentLine {
parsedFirstNonCommentLine = true
#if false
// currently not using the scala short description embedded in the file
scalaShortDescription = lineStr
#endif
continue
}
if parsedFirstNonCommentLine && !parsedAllFrequencies {
if let newFrequencyCount = Int(lineStr) {
frequencyCount = newFrequencyCount
if frequencyCount == 0 || frequencyCount > 127 {
// #warning SPEC SAYS 0 notes is okay because 1/1 is implicit
Log("ERROR: number of notes in scala file: \(frequencyCount)")
parsedScala = false
break
} else {
parsedAllFrequencies = true
continue
}
}
}
if actualFrequencyCount > frequencyCount {
Log("actual frequency cont: \(actualFrequencyCount) > frequency count: \(frequencyCount)")
}
/* The first note of 1/1 or 0.0 cents is implicit and not in the files.*/
// REGEX defined above this loop
let rangeOfFirstMatch = regex.rangeOfFirstMatch(
in: lineStr,
options: .anchored,
range: NSRange(location: 0, length: lineStr.count))
if NSEqualRanges(rangeOfFirstMatch, NSRange(location: NSNotFound, length: 0)) == false {
let nsLineStr = lineStr as NSString?
let substringForFirstMatch = nsLineStr?.substring(with: rangeOfFirstMatch) as NSString? ?? ""
if substringForFirstMatch.range(of: ".").length != 0 {
if var scaleDegree = Frequency(lineStr) {
// ignore 0.0...same as 1.0, 2.0, etc.
if scaleDegree != 0 {
scaleDegree = fabs(scaleDegree)
// convert from cents to frequency
scaleDegree /= 1_200
scaleDegree = pow(2, scaleDegree)
scalaFrequencies.append(scaleDegree)
actualFrequencyCount += 1
continue
}
}
} else {
if substringForFirstMatch.range(of: "/").length != 0 {
if substringForFirstMatch.range(of: "-").length != 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
}
// Parse rational numerator/denominator
let slashPos = substringForFirstMatch.range(of: "/")
let numeratorStr = substringForFirstMatch.substring(to: slashPos.location)
let numerator = Int(numeratorStr) ?? 0
let denominatorStr = substringForFirstMatch.substring(from: slashPos.location + 1)
let denominator = Int(denominatorStr) ?? 0
if denominator == 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
} else {
let mt = Frequency(numerator) / Frequency(denominator)
if mt == 1.0 || mt == 2.0 {
// skip 1/1, 2/1
continue
} else {
scalaFrequencies.append(mt)
actualFrequencyCount += 1
continue
}
}
} else {
// a whole number, treated as a rational with a denominator of 1
if let whole = Int(substringForFirstMatch as String) {
if whole <= 0 {
Log("ERROR: invalid ratio: \(substringForFirstMatch)")
parsedScala = false
break
} else if whole == 1 || whole == 2 {
// skip degrees of 1 or 2
continue
} else {
scalaFrequencies.append(Frequency(whole))
actualFrequencyCount += 1
continue
}
}
}
}
} else {
Log("ERROR: error parsing: \(lineStr)")
continue
}
}
if !parsedScala {
Log("FATAL ERROR: cannot parse Scala file")
return nil
}
Log("frequencies: \(scalaFrequencies)")
return scalaFrequencies
}
}
| mit |
ustwo/mongolabkit-swift | MongoLabKit/Sources/Classes/MongoLabResponseParser.swift | 1 | 900 | //
// MongoLabResponseParser.swift
// MongoLabKit
//
// Created by luca strazzullo on 12/03/16.
// Copyright © 2016 ustwo. All rights reserved.
//
import Foundation
class MongoLabResponseParser {
func parse(_ data: Data?, response: URLResponse?, error: Error?) throws -> AnyObject {
guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
throw MongoLabError.connectionError
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) else {
throw MongoLabError.parserError
}
guard httpResponse.statusCode == 200 || httpResponse.statusCode == 201 else {
throw try MongoLabErrorParser().errorFrom(data, statusCode: httpResponse.statusCode)
}
return jsonObject as AnyObject
}
}
| mit |
HJliu1123/LearningNotes-LHJ | April/通讯录/通讯录/HJDictToModelTool.swift | 1 | 1174 | //
// HJDictToModelTool.swift
// 通讯录
//
// Created by liuhj on 16/4/5.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
class HJDictToModelTool: NSObject {
//
// static func dataTool(dict : NSDictionary) ->AnyObject {
//
// let conn = HJConnect()
// conn.name = dict["name"] as? String
// conn.telNum = dict["telNum"] as? String
// conn.email = dict["email"] as? String
// conn.addr = dict["addr"] as? String
//
//
//
// return conn
// }
class func getConnArr() ->NSArray {
let connArray = NSMutableArray()
let path = NSBundle.mainBundle().pathForResource("ConnectList", ofType: "plist")
let arr = NSArray.init(contentsOfFile: path!)
for dict in arr! {
let conn = HJConnect()
conn.setValuesForKeysWithDictionary(dict as! [String : AnyObject])
connArray.addObject(conn)
}
return connArray.copy() as! NSArray
}
}
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/28250-swift-typechecker-typecheckdecl.swift | 4 | 463 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
// REQUIRES: asserts
class B<h{var d={struct d{typealias e:B
let t:e,A
| apache-2.0 |
jeden/kocomojo-kit | KocomojoKit/KocomojoKit/entities/Plan.swift | 1 | 1489 | //
// Plan.swift
// KocomojoKit
//
// Created by Antonio Bello on 1/26/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
import Foundation
public struct Plan {
public var recommended: Bool
public var nickName: String
public var name: String
public var description: String
public var monthlyFee: Double
public var features: [String]
init(recommended: Bool, nickName: String, name: String, description: String, monthlyFee: Double, features: [String]) {
self.recommended = recommended
self.nickName = nickName
self.name = name
self.description = description
self.monthlyFee = monthlyFee
self.features = features
}
}
extension Plan : JsonDecodable {
static func create(recommended: Bool)(nickName: String)(name: String)(description: String)(monthlyFee: Double)(features: [JsonType]) -> Plan {
return Plan(recommended: recommended, nickName: nickName, name: name, description: description, monthlyFee: monthlyFee, features: features as [String])
}
public static func decode(json: JsonType) -> Plan? {
let a = Plan.create <^> json["recommended"] >>> JsonBool
let b = a <&&> json["nick_name"] >>> JsonString
let c = b <&&> json["name"] >>> JsonString
let d = c <&&> json["description"] >>> JsonString
let e = d <&&> json["monthly_fee"] >>> JsonDouble
let f = e <&&> json["features"] >>> JsonArrayType
return f
}
}
| mit |
dkerzig/CAJ-Einschreibungen | CAJ-Einschreibungen/TableViewController.swift | 1 | 5303 | //
// ViewController.swift
// CAJ-Einschreibungen
//
// Contains Cocoa-Touch and Foundation
// Informations: https://goo.gl/g0H9Q1
import UIKit
// The ViewController of our Course-Table which is asked for the contents
// of the table by the table itself, because we have marked this class as
// 'UITableViewDataSource' in the Interface-Builder ('.storyboard'-file).
// It also cares about instantiating a 'CAJController'-instance, asking it
// to fetch 'CAJCourses' and handles the results as a 'CAJControllerDelegate'.
class TableViewController: UITableViewController, UITableViewDataSource, CAJControllerDelegate {
// MARK: - VARIABLES
// An array of all Courses which is empty by default
var courses: [CAJCourse] = []
// Our instance of 'CAJController' which fetches the data from the CAJ
var cajController: CAJController? = nil
// A "lazily" computed property which represents the modal-view which
// pops up and asks for username&password. Lazy means the closure will
// execute first just after the property is used it's first time.
// Informations: https://goo.gl/QNiQxr
lazy var loginAlertController: UIAlertController = { [unowned self] in
// Create Alert Controller with title and subtitle
let alertController = UIAlertController(title: "CAJ-Anmeldung", message: "Gib dein Nutzerkürzel mit entsprechendem Passwort ein, um fortzufahren.", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { $0.placeholder = "Benutzerkürzel" }
alertController.addTextFieldWithConfigurationHandler { $0.placeholder = "Passwort"; $0.secureTextEntry = true }
// Add "Anmelden"-Action
alertController.addAction(UIAlertAction(title: "Anmelden", style: .Default) { _ in
// Get Textfields
let nameField = alertController.textFields?[0] as! UITextField
let pwField = alertController.textFields?[1] as! UITextField
// Instantiate CAJController with username & password
self.cajController = CAJController(username: nameField.text, password: pwField.text)
self.cajController?.delegate = self
self.cajController?.loginAndGetCourses()
})
// Add "Abbrechen"-Action
alertController.addAction(UIAlertAction(title: "Abbrechen", style: .Destructive) { _ in })
return alertController
}()
// MARK: - VIEW-CONTROLLER-LIFECYCLE
// This function is called after the view-hierachy did
// loaded successfully from the memory
override func viewDidLoad() {
super.viewDidLoad()
// Start Loading
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: Selector("loadCAJCourses"), forControlEvents: .ValueChanged)
self.refreshControl?.beginRefreshing()
self.loadCAJCourses()
}
// MARK: - FETCH/GET CAJ-COURSES
// If we already passed in our password/username this method
// asks the 'cajController' to fetch again, otherwise the 'loginAlertController'
// is prompted, and it's completion-handler intantiates our
// 'cajController' and asks it to fetch the data from CAJ.
func loadCAJCourses() {
// Ask for Login and Passwort if nil, otherwise fetch again
if self.cajController == nil {
self.parentViewController?.presentViewController(self.loginAlertController, animated: true, completion: nil)
} else {
self.cajController!.loginAndGetCourses()
}
}
// Becourse web-requests should not be handled synchronously, we don't
// get any results from the 'loginAndGetCourses' function. Has the
// 'cajController' fetched everything successfully it's calling this
// method. The compiler knows that we implement this method because we
// conform to the 'CAJControllerDelegate'.
func didLoadCAJCourses(fetchedCourses: [CAJCourse]?) {
if fetchedCourses != nil {
self.courses = fetchedCourses!
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
// MARK: - UITableViewDataSource
// We return the number of rows which is equivalent to the number of courses
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses.count
}
// We create a new cell (actually we 'dequeue a reusable' one but don't care about that)
// and customize it to display the Course-Name, -Dozent, ... in it's labels.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CourseCell", forIndexPath: indexPath) as! UITableViewCell
let course = self.courses[indexPath.row]
let courseShortType = "[" + (course.typ as NSString).substringToIndex(1) + "]"
cell.textLabel?.text = "\(courseShortType) \(course.name) von \(course.dozent)"
cell.detailTextLabel?.text = "Ort: \(course.ort), Zeit: \(course.zeit)"
return cell
}
}
| mit |
JeziL/WeekCount | WeekCount/StatusMenuController.swift | 1 | 5640 | //
// StatusMenuController.swift
// WeekCount
//
// Created by Li on 16/6/13.
// Copyright © 2016 Jinli Wang. All rights reserved.
//
import Cocoa
let DEFAULT_STARTDATE = Date()
let DEFAULT_LASTCOUNT = 18
let DEFAULT_DISPLAYFORMAT = "Week {W}"
let DEFAULT_FONTSIZE: Float = 14.2
class StatusMenuController: NSObject, PreferencesWindowDelegate {
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet weak var dateMenuItem: NSMenuItem!
var preferencesWindow: PreferencesWindow!
var aboutWindow: AboutWindow!
var startDate: Date!
var lastCount: Int!
var displayFormat: String!
var fontSize: Float!
var autoLaunch: Int!
var sem: Semester!
var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
override func awakeFromNib() {
preferencesWindow = PreferencesWindow()
aboutWindow = AboutWindow()
preferencesWindow.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.updateAll), name: NSNotification.Name(rawValue: "URLSchemesUpdate"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.showPreferencesWindow), name: NSNotification.Name(rawValue: "URLSchemesShowPreferences"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.quit), name: NSNotification.Name(rawValue: "URLSchemesQuit"), object: nil)
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(StatusMenuController.updateAll), userInfo: nil, repeats: true)
let loop = RunLoop.main
loop.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
statusMenu.items.last!.action = #selector(StatusMenuController.quit)
statusItem.menu = statusMenu
}
@IBAction func showPreferencesWindow(sender: NSMenuItem) {
NSApp.activate(ignoringOtherApps: true)
preferencesWindow.showWindow(nil)
}
@IBAction func showAboutWindow(sender: NSMenuItem) {
NSApp.activate(ignoringOtherApps: true)
aboutWindow.showWindow(nil)
}
@IBAction func quitApp(_ sender: NSMenuItem) {
quit()
}
@objc func quit() {
NSApplication.shared.terminate(self)
}
func resetPreferences() {
UserDefaults.standard.setPersistentDomain(["":""], forName: Bundle.main.bundleIdentifier!)
updateAll()
}
@objc func updateAll() {
let formatter = DateFormatter()
formatter.locale = NSLocale.autoupdatingCurrent
formatter.dateStyle = .full
dateMenuItem.title = formatter.string(from: Date())
updatePreferences()
updateDisplay()
}
func preferencesDidUpdate() {
updateAll()
}
func updatePreferences() {
let defaults = UserDefaults.standard
startDate = defaults.value(forKey: "startDate") as? Date ?? DEFAULT_STARTDATE
if let count = defaults.string(forKey: "lastCount") {
if let countNo = Int(count) {
lastCount = countNo
} else { lastCount = DEFAULT_LASTCOUNT }
} else { lastCount = DEFAULT_LASTCOUNT }
displayFormat = defaults.string(forKey: "displayFormat") ?? DEFAULT_DISPLAYFORMAT
if let size = defaults.string(forKey: "fontSize") {
if let sizeNo = Float(size) {
fontSize = sizeNo
} else { fontSize = DEFAULT_FONTSIZE }
} else { fontSize = DEFAULT_FONTSIZE }
sem = Semester.init(startDate: startDate, lastCount: lastCount)
}
func updateDisplay() {
if let button = statusItem.button {
button.attributedTitle = showWeekCount(count: sem.getWeekNo())
}
}
func convertToChinese(count: Int) -> String {
let hiDict = [0: "", 1: "十", 2: "二十", 3: "三十", 4: "四十", 5: "五十", 6: "六十", 7: "七十", 8: "八十", 9: "九十"]
let loDict = [0: "", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九"]
guard (count > 0 && count < 100) else { return "" }
let hi = count / 10
let lo = count % 10
return hiDict[hi]! + loDict[lo]!
}
func iso8601Format(str: String) -> String {
var str = str
let formatter = DateFormatter()
formatter.locale = NSLocale.autoupdatingCurrent
let supportedStrings = ["YYYY", "YY", "Y", "yyyy", "yy", "y", "MM", "M", "dd", "d", "EEEE", "eeee", "HH", "H", "hh", "h", "mm", "m", "ss", "s"]
for e in supportedStrings {
formatter.dateFormat = e
let convertedStr = formatter.string(from: Date())
str = str.replacingOccurrences(of: e, with: convertedStr)
}
str = str.replacingOccurrences(of: "星期", with: "周")
return str
}
func showWeekCount(count: Int) -> NSAttributedString {
let font = NSFont.systemFont(ofSize: CGFloat(fontSize))
if count > 0 {
var rawStr = displayFormat.replacingOccurrences(of: "{W}", with: String(count))
rawStr = rawStr.replacingOccurrences(of: "{zhW}", with: convertToChinese(count: count))
rawStr = iso8601Format(str: rawStr)
return NSAttributedString.init(string: rawStr, attributes: [NSAttributedStringKey.font: font])
} else {
return NSAttributedString.init(string: "WeekCount", attributes: [NSAttributedStringKey.font: font])
}
}
}
| gpl-2.0 |
boyvanamstel/Picsojags-iOS | PicsojagsTests/PicsojagsTests.swift | 1 | 589 | //
// PicsojagsTests.swift
// PicsojagsTests
//
// Created by Boy van Amstel on 19/02/2017.
// Copyright © 2017 Danger Cove. All rights reserved.
//
import XCTest
@testable import Picsojags
class PicsojagsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| mit |
accesscode-2-2/unit-4-assignments | HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift | 2 | 126 | //: https://docs.google.com/document/d/1T7tYRqpDPWoxarfmXqfRCHB-YqvA8-Qx_mEyy5smtfc
//1)
//a)
//b)
//c)
//2)
//3) | mit |
rockbruno/ErrorKing | Example/ErrorKingExampleUITests/ErrorKingExampleUITests.swift | 2 | 1266 | //
// ErrorKingExampleUITests.swift
// ErrorKingExampleUITests
//
// Created by Bruno Rocha on 8/15/16.
// Copyright © 2016 Movile. All rights reserved.
//
import XCTest
class ErrorKingExampleUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
nerdycat/Cupcake | Cupcake-Demo/Cupcake-Demo/AppStoreViewController.swift | 1 | 3902 | //
// AppStoreViewController.swift
// Cupcake-Demo
//
// Created by nerdycat on 2017/5/15.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
class AppStoreCell: UITableViewCell {
var iconView: UIImageView!
var actionButton: UIButton!
var indexLabel, titleLabel, categoryLabel: UILabel!
var ratingLabel, countLabel, iapLabel: UILabel!
func update(app: Dictionary<String, Any>, index: Int) {
indexLabel.str(index + 1)
iconView.img(app["iconName"] as! String)
titleLabel.text = app["title"] as? String
categoryLabel.text = app["category"] as? String
countLabel.text = Str("(%@)", app["commentCount"] as! NSNumber)
iapLabel.isHidden = !(app["iap"] as! Bool)
let rating = (app["rating"] as! NSNumber).intValue
var result = ""
for i in 0..<5 { result = result + (i < rating ? "★" : "☆") }
ratingLabel.text = result
let price = app["price"] as! String
actionButton.str( price.count > 0 ? "$" + price : "GET")
}
func setupUI() {
indexLabel = Label.font(17).color("darkGray").align(.center).pin(.w(44))
iconView = ImageView.pin(64, 64).radius(10).border(1.0 / UIScreen.main.scale, "#CCC")
titleLabel = Label.font(15).lines(2)
categoryLabel = Label.font(13).color("darkGray")
ratingLabel = Label.font(11).color("orange")
countLabel = Label.font(11).color("darkGray")
actionButton = Button.font("15").color("#0065F7").border(1, "#0065F7").radius(3)
actionButton.highColor("white").highBg("#0065F7").padding(5, 10)
iapLabel = Label.font(9).color("darkGray").lines(2).str("In-App\nPurchases").align(.center)
let ratingStack = HStack(ratingLabel, countLabel).gap(5)
let midStack = VStack(titleLabel, categoryLabel, ratingStack).gap(4)
let actionStack = VStack(actionButton, iapLabel).gap(4).align(.center)
HStack(indexLabel, iconView, 10, midStack, "<-->", 10, actionStack).embedIn(self.contentView, 10, 0, 10, 15)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class AppStoreViewController: UITableViewController {
var appList: Array<Dictionary<String, Any>>!
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AppStoreCell
let app = self.appList[indexPath.row]
cell.update(app: app, index: indexPath.row)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 84
self.tableView.register(AppStoreCell.self, forCellReuseIdentifier: "cell")
self.tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 34, right: 0)
let path = Bundle.main.path(forResource: "appList", ofType: "plist")
appList = NSArray(contentsOfFile: path!) as? Array<Dictionary<String, Any>>
for _ in 1..<5 { appList.append(contentsOf: appList) }
}
}
| mit |
GuoMingJian/DouYuZB | DYZB/DYZB/Classes/Home/Controller/AmuseViewController.swift | 1 | 3867 | //
// AmuseViewController.swift
// DYZB
//
// Created by 郭明健 on 2017/12/22.
// Copyright © 2017年 com.joy.www. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - kItemMargin * 3) / 2
private let kItemNormalH = kItemW * 3 / 4
private let kItemPrettyH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kHeaderViewID = "kHeaderViewID"
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
class AmuseViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemNormalH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//2.创建collectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]//随着父控件缩小而缩小
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
//3.注册cell
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
return collectionView
}()
//MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK:- 设置UI界面
extension AmuseViewController {
fileprivate func setupUI() {
view.addSubview(collectionView)
}
}
//MARK:- 请求数据
extension AmuseViewController {
fileprivate func loadData() {
amuseVM.loadAmuseData {
self.collectionView.reloadData()
}
}
}
//MARK:- 遵守UICollectionView的数据源协议
extension AmuseViewController : UICollectionViewDataSource, UICollectionViewDelegate
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return amuseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return amuseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.取出模型对象
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
//2.给cell设置数据
cell.anchor = amuseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
//2.给HeaderView设置数据
headerView.group = amuseVM.anchorGroups[indexPath.section]
return headerView
}
}
| mit |
lacklock/ReactiveCocoaExtension | Pods/ReactiveSwift/Sources/Flatten.swift | 2 | 34893 | //
// Flatten.swift
// ReactiveSwift
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case merge
/// The producers should be concatenated, so that their values are sent in
/// the order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have
/// completed.
case concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed
/// of.
///
/// The resulting producer will complete only when the producer-of-producers
/// and the latest producer has completed.
case latest
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - note: `interrupted` events on inner producers will be treated like
/// `Completed events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .merge:
return self.merge()
case .concat:
return self.concat()
case .latest:
return self.switchToLatest()
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner signal emits an error, the
/// returned signal will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned signal
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `signal` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init($0) }
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner signal emits an error, the
/// returned producer will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If an active inner signal emits an error, the returned producer
/// will forward that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerProtocol where Value: SignalProtocol, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer
/// of values), according to the semantics of the given strategy.
///
/// - note: If `producer` emits an error, the returned producer will forward
/// that error immediately.
///
/// - warning: `interrupted` events on inner signals will be treated like
/// `completed` events on inner signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerProtocol where Value: Sequence, Error == NoError {
/// Flattens the `sequence` value sent by `producer` according to
/// the semantics of the given strategy.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Iterator.Element, Error> {
return self.flatMap(strategy) { .init($0) }
}
}
extension SignalProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProducerProtocol where Value: PropertyProtocol {
/// Flattens the inner properties sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer }
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted
/// from `signal`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers fail, the returned signal will
/// forward that failure immediately
///
/// - note: The returned signal completes only when `signal` and all
/// producers emitted from `signal` complete.
fileprivate func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeConcat(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = Atomic(ConcatState<Value.Value, Error>())
func startNextIfNeeded() {
while let producer = state.modify({ $0.dequeue() }) {
producer.startWithSignal { signal, inner in
let handle = disposable?.add(inner)
signal.observe { event in
switch event {
case .completed, .interrupted:
handle?.remove()
let shouldStart: Bool = state.modify {
$0.active = nil
return !$0.isStarting
}
if shouldStart {
startNextIfNeeded()
}
case .value, .failed:
observer.action(event)
}
}
}
state.modify { $0.isStarting = false }
}
}
return observe { event in
switch event {
case let .value(value):
state.modify { $0.queue.append(value.producer) }
startNextIfNeeded()
case let .failed(error):
observer.send(error: error)
case .completed:
state.modify { state in
state.queue.append(SignalProducer.empty.on(completed: observer.sendCompleted))
}
startNextIfNeeded()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted
/// from `producer`, waiting until each inner producer completes before
/// beginning to send the values from the next inner producer.
///
/// - note: If any of the inner producers emit an error, the returned
/// producer will emit that error.
///
/// - note: The returned producer completes only when `producer` and all
/// producers emitted from `producer` complete.
fileprivate func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerProtocol {
/// `concat`s `next` onto `self`.
public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>([ self.producer, next ]).flatten(.concat)
}
/// `concat`s `value` onto `self`.
public func concat(value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
public func prefix<P: SignalProducerProtocol>(_ previous: P) -> SignalProducer<Value, Error>
where P.Value == Value, P.Error == Error
{
return previous.concat(self.producer)
}
/// `concat`s `self` onto initial `value`.
public func prefix(value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcatState<Value, Error: Swift.Error> {
typealias SignalProducer = ReactiveSwift.SignalProducer<Value, Error>
/// The active producer, if any.
var active: SignalProducer? = nil
/// The producers waiting to be started.
var queue: [SignalProducer] = []
/// Whether the active producer is currently starting.
/// Used to prevent deep recursion.
var isStarting: Bool = false
/// Dequeue the next producer if one should be started.
///
/// - note: The caller *must* set `isStarting` to false after the returned
/// producer has been started.
///
/// - returns: The `SignalProducer` to start or `nil` if no producer should
/// be started.
func dequeue() -> SignalProducer? {
if active != nil {
return nil
}
active = queue.first
if active != nil {
queue.removeFirst()
isStarting = true
}
return active
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
fileprivate func observeMerge(_ observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let shouldComplete: Bool = inFlight.modify {
$0 -= 1
return $0 == 0
}
if shouldComplete {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .value(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 += 1 }
let handle = disposable.add(innerDisposable)
innerSignal.observe { event in
switch event {
case .completed, .interrupted:
handle.remove()
decrementInFlight()
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
decrementInFlight()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased
/// toward the producer added earlier. Returns a Signal that will forward
/// events from the inner producers as they arrive.
fileprivate func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
_ = signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalProtocol {
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<Seq: Sequence, S: SignalProtocol>(_ signals: Seq) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer<S, Error>(signals)
.flatten(.merge)
.startAndRetrieveSignal()
}
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
public static func merge<S: SignalProtocol>(_ signals: S...) -> Signal<Value, Error>
where S.Value == Value, S.Error == Error
{
return Signal.merge(signals)
}
}
extension SignalProducerProtocol {
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<Seq: Sequence, S: SignalProducerProtocol>(_ producers: Seq) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error, Seq.Iterator.Element == S
{
return SignalProducer(producers).flatten(.merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
public static func merge<S: SignalProducerProtocol>(_ producers: S...) -> SignalProducer<Value, Error>
where S.Value == Value, S.Error == Error
{
return SignalProducer.merge(producers)
}
}
extension SignalProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
fileprivate func observeSwitchToLatest(_ observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .value(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents
// the generated Interrupted event from doing any work.
$0.replacingInnerSignal = true
}
latestInnerDisposable.inner = innerDisposable
state.modify {
$0.replacingInnerSignal = false
$0.innerSignalComplete = false
}
innerSignal.observe { event in
switch event {
case .interrupted:
// If interruption occurred as a result of a new
// producer arriving, we don't want to notify our
// observer.
let shouldComplete: Bool = state.modify { state in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return !state.replacingInnerSignal && state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.innerSignalComplete = true
return $0.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.outerSignalComplete = true
return $0.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable += latestInnerDisposable
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: Swift.Error> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalProtocol {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new property, then flattens the
/// resulting properties (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> Signal<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new property, then flattens the
/// resulting properties (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> SignalProducer<P.Value, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerProtocol where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
public func flatMap<U, E>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
public func flatMap<U>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProtocol {
/// Catches any failure that may occur on the input signal, mapping to a new
/// producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
observer.send(value: value)
case let .failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.inner = disposable
signal.observe(observer)
}
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerProtocol {
/// Catches any failure that may occur on the input producer, mapping to a
/// new producer that starts in its place.
public func flatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable += serialDisposable
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
_ = signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| mit |
gabek/GitYourFeedback | Example/Pods/GRMustache.swift/Sources/ExpressionParser.swift | 2 | 19007 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
final class ExpressionParser {
func parse(_ string: String, empty outEmpty: inout Bool) throws -> Expression {
enum State {
// error
case error(String)
// Any expression can start
case waitingForAnyExpression
// Expression has started with a dot
case leadingDot
// Expression has started with an identifier
case identifier(identifierStart: String.Index)
// Parsing a scoping identifier
case scopingIdentifier(identifierStart: String.Index, baseExpression: Expression)
// Waiting for a scoping identifier
case waitingForScopingIdentifier(baseExpression: Expression)
// Parsed an expression
case doneExpression(expression: Expression)
// Parsed white space after an expression
case doneExpressionPlusWhiteSpace(expression: Expression)
}
var state: State = .waitingForAnyExpression
var filterExpressionStack: [Expression] = []
var i = string.startIndex
let end = string.endIndex
stringLoop: while i < end {
let c = string[i]
switch state {
case .error:
break stringLoop
case .waitingForAnyExpression:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
state = .leadingDot
case "(", ")", ",", "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .identifier(identifierStart: i)
}
case .leadingDot:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: Expression.implicitIterator)
case ".":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
filterExpressionStack.append(Expression.implicitIterator)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.implicitIterator, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: Expression.implicitIterator)
}
case .identifier(identifierStart: let identifierStart):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substring(with: identifierStart..<i)
state = .doneExpressionPlusWhiteSpace(expression: Expression.identifier(identifier: identifier))
case ".":
let identifier = string.substring(with: identifierStart..<i)
state = .waitingForScopingIdentifier(baseExpression: Expression.identifier(identifier: identifier))
case "(":
let identifier = string.substring(with: identifierStart..<i)
filterExpressionStack.append(Expression.identifier(identifier: identifier))
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: Expression.identifier(identifier: identifier), partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .doneExpressionPlusWhiteSpace(expression: scopedExpression)
case ".":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
state = .waitingForScopingIdentifier(baseExpression: scopedExpression)
case "(":
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(scopedExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substring(with: identifierStart..<i)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
break
}
case .waitingForScopingIdentifier(let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .error("Unexpected white space character at index \(string.characters.distance(from: string.startIndex, to: i))")
case ".":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case ")":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case ",":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
default:
state = .scopingIdentifier(identifierStart: i, baseExpression: baseExpression)
}
case .doneExpression(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .doneExpressionPlusWhiteSpace(expression: doneExpression)
case ".":
state = .waitingForScopingIdentifier(baseExpression: doneExpression)
case "(":
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
// Prevent "a .b"
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
case "(":
// Accept "a (b)"
filterExpressionStack.append(doneExpression)
state = .waitingForAnyExpression
case ")":
// Accept "a(b )"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .doneExpression(expression: expression)
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
case ",":
// Accept "a(b ,c)"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .waitingForAnyExpression
} else {
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
default:
state = .error("Unexpected character `\(c)` at index \(string.characters.distance(from: string.startIndex, to: i))")
}
}
i = string.index(after: i)
}
// Parsing done
enum FinalState {
case error(String)
case empty
case valid(expression: Expression)
}
let finalState: FinalState
switch state {
case .waitingForAnyExpression:
if filterExpressionStack.isEmpty {
finalState = .empty
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .leadingDot:
if filterExpressionStack.isEmpty {
finalState = .valid(expression: Expression.implicitIterator)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .identifier(identifierStart: let identifierStart):
if filterExpressionStack.isEmpty {
let identifier = string.substring(from: identifierStart)
finalState = .valid(expression: Expression.identifier(identifier: identifier))
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .scopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
if filterExpressionStack.isEmpty {
let identifier = string.substring(from: identifierStart)
let scopedExpression = Expression.scoped(baseExpression: baseExpression, identifier: identifier)
finalState = .valid(expression: scopedExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .waitingForScopingIdentifier:
finalState = .error("Missing identifier at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
case .doneExpression(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .doneExpressionPlusWhiteSpace(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .valid(expression: doneExpression)
} else {
finalState = .error("Missing `)` character at index \(string.characters.distance(from: string.startIndex, to: string.endIndex))")
}
case .error(let message):
finalState = .error(message)
}
// End
switch finalState {
case .empty:
outEmpty = true
throw MustacheError(kind: .parseError, message: "Missing expression")
case .error(let description):
outEmpty = false
throw MustacheError(kind: .parseError, message: "Invalid expression `\(string)`: \(description)")
case .valid(expression: let expression):
return expression
}
}
}
| mit |
moozzyk/SignalR-Client-Swift | Sources/SignalRClient/Connection.swift | 1 | 477 | //
// Connection.swift
// SignalRClient
//
// Created by Pawel Kadluczka on 3/4/17.
// Copyright © 2017 Pawel Kadluczka. All rights reserved.
//
import Foundation
public protocol Connection {
var delegate: ConnectionDelegate? {get set}
var inherentKeepAlive: Bool {get}
var connectionId: String? {get}
func start() -> Void
func send(data: Data, sendDidComplete: @escaping (_ error: Error?) -> Void) -> Void
func stop(stopError: Error?) -> Void
}
| mit |
benlangmuir/swift | test/Sema/availability_enum_case.swift | 13 | 880 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-module %S/Inputs/availability_enum_case_other.swift -emit-module-interface-path %t/availability_enum_case_other.swiftinterface -swift-version 5 -enable-library-evolution
// RUN: %target-typecheck-verify-swift -I %t
// RUN: %target-build-swift -emit-module %S/Inputs/availability_enum_case_other.swift -emit-module-interface-path %t/availability_enum_case_other.swiftinterface -swift-version 5 -enable-library-evolution -whole-module-optimization
// RUN: %target-typecheck-verify-swift -I %t
// REQUIRES: OS=macosx
import availability_enum_case_other
func ride(horse: Horse) {
// expected-note@-1 {{add @available attribute to enclosing global function}}
_ = Horse.kevin
// expected-error@-1 {{'kevin' is only available in macOS 100 or newer}}
// expected-note@-2 {{add 'if #available' version check}}
}
| apache-2.0 |
benlangmuir/swift | test/SymbolGraph/Symbols/Mixins/Availability/Inherited/RenamedFilled.swift | 20 | 828 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name RenamedFilled -emit-module -emit-module-path %t/
// RUN: %target-swift-symbolgraph-extract -module-name RenamedFilled -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/RenamedFilled.symbols.json
// REQUIRES: OS=macosx
@available(macOS, deprecated, renamed: "S.bar")
public struct S {
public func foo() {}
}
@available(macOS, deprecated, renamed: "Other")
public struct Outer {
public struct Inner {
public func foo() {}
}
}
// A parent's `renamed` field should never replace a child's.
// It wouldn't make sense for a parent and child to both be renamed to the same thing.
// This will definitely be on the parents, so this is enough to check that it wasn't
// applied to the child.
// CHECK-COUNT-2: "availability":
| apache-2.0 |
artemkin/sandbox | closure/closure.swift | 1 | 466 |
// Closures are reference types in Swift.
// They automatically capture variables by reference if they are mutated
func generate() -> [() -> Int] {
var result:[() -> Int] = []
var counter = 0
for _ in 1...10 {
func increment() -> Int {
return counter++;
}
result.append(increment)
}
return result;
}
let seq = generate()
let seq2 = seq
for s in seq {
print(s())
}
for s in seq2 {
print(s())
}
| bsd-2-clause |
robertofrontado/RxSocialConnect-iOS | RxSocialConnectExample/RxSocialConnectExample/Pods/OAuthSwift/Sources/OAuthSwiftError.swift | 4 | 4208 | //
// OAuthSwiftError.swift
// OAuthSwift
//
// Created by phimage on 02/10/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
// MARK: - OAuthSwift errors
public enum OAuthSwiftError: Error {
// Configuration problem with oauth provider.
case configurationError(message: String)
// The provided token is expired, retrieve new token by using the refresh token
case tokenExpired(error: Error?)
// State missing from request (you can set allowMissingStateCheck = true to ignore)
case missingState
// Returned state value is wrong
case stateNotEqual(state: String, responseState: String)
// Error from server
case serverError(message: String)
// Failed to create URL \(urlString) not convertible to URL, please encode
case encodingError(urlString: String)
case authorizationPending
// Failed to create request with \(urlString)
case requestCreation(message: String)
// Authentification failed. No token
case missingToken
// Please retain OAuthSwift object or handle
case retain
// Request error
case requestError(error: Error)
// Request cancelled
case cancelled
public static let Domain = "OAuthSwiftError"
public static let ResponseDataKey = "OAuthSwiftError.response.data"
public static let ResponseKey = "OAuthSwiftError.response"
fileprivate enum Code : Int {
case configurationError = -1
case tokenExpired = -2
case missingState = -3
case stateNotEqual = -4
case serverError = -5
case encodingError = -6
case authorizationPending = -7
case requestCreation = -8
case missingToken = -9
case retain = -10
case requestError = -11
case cancelled = -12
}
fileprivate var code: Code {
switch self {
case .configurationError: return Code.configurationError
case .tokenExpired: return Code.tokenExpired
case .missingState: return Code.missingState
case .stateNotEqual: return Code.stateNotEqual
case .serverError: return Code.serverError
case .encodingError: return Code.encodingError
case .authorizationPending: return Code.authorizationPending
case .requestCreation: return Code.requestCreation
case .missingToken: return Code.missingToken
case .retain: return Code.retain
case .requestError: return Code.requestError
case .cancelled : return Code.cancelled
}
}
// For NSError
public var _code: Int {
return self.code.rawValue
}
public var _domain: String {
return OAuthSwiftError.Domain
}
}
extension OAuthSwiftError: CustomStringConvertible {
public var description: String {
switch self {
case .configurationError(let m): return "configurationError[\(m)]"
case .tokenExpired(let e): return "tokenExpired[\(e)]"
case .missingState: return "missingState"
case .stateNotEqual(let s, let e): return "stateNotEqual[\(s)<>\(e)]"
case .serverError(let m): return "serverError[\(m)]"
case .encodingError(let urlString): return "encodingError[\(urlString)]"
case .authorizationPending: return "authorizationPending"
case .requestCreation(let m): return "requestCreation[\(m)]"
case .missingToken: return "missingToken"
case .retain: return "retain"
case .requestError(let e): return "requestError[\(e)]"
case .cancelled : return "cancelled"
}
}
}
extension NSError {
fileprivate convenience init(code: OAuthSwiftError.Code, message: String, errorKey: String = NSLocalizedFailureReasonErrorKey) {
let userInfo = [errorKey: message]
self.init(domain: OAuthSwiftError.Domain, code: code.rawValue, userInfo: userInfo)
}
}
extension OAuthSwiftError {
var nsError: NSError {
return NSError(code: self.code, message: "")
}
}
extension OAuthSwift {
static func retainError(_ failureHandler: FailureHandler?) {
#if !OAUTH_NO_RETAIN_ERROR
failureHandler?(OAuthSwiftError.retain)
#endif
}
}
| apache-2.0 |
red-spotted-newts-2014/rest-less-ios | Rest Less/http_post.playground/section-1.swift | 1 | 1321 | import Foundation
import XCPlayground
func HTTPostJSON(url: String,
jsonObj: AnyObject)
{
var request = NSMutableURLRequest(URL: NSURL(string: url))
var session = NSURLSession.sharedSession()
var jsonError:NSError?
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject( jsonObj, options: nil, error: &jsonError)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var subTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var jsonRError: NSError?
var json_response = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &jsonRError) as? NSDictionary
println(jsonRError)
jsonRError?
if jsonRError? != nil {
println(jsonRError!.localizedDescription)
}
else {
json_response
}
})
subTask.resume()
}
var params = ["workout_type":"weights"] as Dictionary
HTTPostJSON("http://secret-stream-5880.herokuapp.com/exercises", params)
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) | mit |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/ConversationList/UIViewControllerTransitioningDelegate+Present.swift | 1 | 1116 | // Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
extension UIViewControllerTransitioningDelegate where Self: UIViewController {
func show(_ viewController: UIViewController,
animated: Bool, completion: (() -> Void)?) {
viewController.transitioningDelegate = self
viewController.modalPresentationStyle = .currentContext
present(viewController, animated: animated, completion: completion)
}
}
| gpl-3.0 |
inacioferrarini/StoryboardFlowCoordinator | StoryboardFlowCoordinator/User/ViewController/UserPJDetails/UserPJDetailsViewController.swift | 1 | 1619 | //
// UserPJDetailsViewController.swift
// StoryboardFlowCoordinator
//
// Created by Inácio on 27/11/16.
// Copyright © 2016 com.inacioferrarini.gh. All rights reserved.
//
import UIKit
class UserPJDetailsViewController: UIViewController {
var delegate: UserPJDetailsViewControllerDelegate?
var userDetailsData: UserPJData?
@IBOutlet weak var name: UITextField!
@IBOutlet weak var cnpj: UITextField!
@IBOutlet weak var email: UITextField!
override func viewWillAppear(_ animated: Bool) {
self.setData(userDetailsData)
}
func setData(_ data: UserPJData?) {
self.name.text = data?.name ?? ""
self.cnpj.text = data?.cnpj ?? ""
self.email.text = data?.email ?? ""
}
func getUserData() -> UserPJData {
let data = UserPJData()
data.name = self.name.text ?? ""
data.cnpj = self.cnpj.text ?? ""
data.email = self.email.text ?? ""
return data
}
// MARK: - Actions
@IBAction func next() {
let userDetailsData = self.getUserData()
self.userDetailsData = userDetailsData
self.delegate?.didInformedPJUserData(userDetailsData)
}
}
extension UserPJDetailsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.name {
self.cnpj.becomeFirstResponder()
} else if textField == self.cnpj {
self.email.becomeFirstResponder()
} else {
next()
}
return true
}
}
| mit |
gregomni/swift | test/SILGen/exclusivityattr.swift | 9 | 2202 | // RUN: %target-swift-emit-silgen -parse-as-library -module-name=test %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-ON
// RUN: %target-swift-emit-silgen -parse-as-library -module-name=test -enforce-exclusivity=none %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-OFF
@exclusivity(checked)
var globalCheckedVar = 1
@exclusivity(unchecked)
var globalUncheckedVar = 1
// CHECK-LABEL: sil [ossa] @$s4test13getCheckedVarSiyF
// CHECK-ON: begin_access [read] [dynamic]
// CHECK-OFF: begin_access [read] [dynamic]
// CHECK: } // end sil function '$s4test13getCheckedVarSiyF'
public func getCheckedVar() -> Int {
return globalCheckedVar
}
// CHECK-LABEL: sil [ossa] @$s4test15getUncheckedVarSiyF
// CHECK-ON: begin_access [read] [unsafe]
// CHECK-OFF-NOT: begin_access
// CHECK: } // end sil function '$s4test15getUncheckedVarSiyF'
public func getUncheckedVar() -> Int {
return globalUncheckedVar
}
public class ExclusivityAttrStruct {
// CHECK-LABEL: sil {{.*}}@$s4test21ExclusivityAttrStructC9staticVarSivsZ
// CHECK-ON: begin_access [modify] [unsafe]
// CHECK: } // end sil function '$s4test21ExclusivityAttrStructC9staticVarSivsZ'
@exclusivity(unchecked)
public static var staticVar: Int = 27
}
public class ExclusivityAttrClass {
// CHECK-LABEL: sil {{.*}}@$s4test20ExclusivityAttrClassC11instanceVarSivs
// CHECK-ON: begin_access [modify] [unsafe]
// CHECK: } // end sil function '$s4test20ExclusivityAttrClassC11instanceVarSivs'
@exclusivity(unchecked)
public var instanceVar: Int = 27
// CHECK-LABEL: sil {{.*}}@$s4test20ExclusivityAttrClassC18checkedInstanceVarSivs
// CHECK-ON: begin_access [modify] [dynamic]
// CHECK-OFF: begin_access [modify] [dynamic]
// CHECK: } // end sil function '$s4test20ExclusivityAttrClassC18checkedInstanceVarSivs'
@exclusivity(checked)
public var checkedInstanceVar: Int = 27
// CHECK-LABEL: sil {{.*}}@$s4test20ExclusivityAttrClassC9staticVarSivsZ
// CHECK-ON: begin_access [modify] [unsafe]
// CHECK: } // end sil function '$s4test20ExclusivityAttrClassC9staticVarSivsZ'
@exclusivity(unchecked)
public static var staticVar: Int = 27
}
| apache-2.0 |
xiaoxinghu/swift-org | Sources/Lexer.swift | 1 | 1242 | //
// Lexer.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 14/08/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
public enum LexerErrors: Error {
case tokenizeFailed(Int, String)
}
open class Lexer {
let lines: [String]
public init(lines theLines: [String]) {
lines = theLines
}
/// Tokenize one line, without considering the context
///
/// - Parameter line: the target line
/// - Returns: the token
class func tokenize(line: String) -> Token? {
defineTokens()
for td in tokenDescriptors {
guard let m = line.match(td.pattern, options: td.options) else { continue }
return td.generator(m)
}
return nil
}
func tokenize(cursor: Int = 0, tokens: [TokenInfo] = []) throws -> [TokenInfo] {
if lines.count == cursor { return tokens }
let line = lines[cursor]
guard let token = Lexer.tokenize(line: line) else {
throw LexerErrors.tokenizeFailed(cursor, line)
}
return try tokenize(
cursor: cursor + 1,
tokens: tokens + [(TokenMeta(raw: line, lineNumber: cursor), token)])
}
}
| mit |
ronlisle/XcodeViperTemplate | viperTests.xctemplate/___FILEBASENAME___InteractorTests.swift | 1 | 972 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
import XCTest
class ___FILEBASENAME___InteractorTests: XCTestCase {
let numTestItems = 0
var interactor: ___FILEBASENAME___Interactor!
var dataManager: ___FILEBASENAME___DataManager!
var mockPresenter: Mock___FILEBASENAME___Presenter!
override func setUp() {
super.setUp()
dataManager = ___FILEBASENAME___DataManager()
interactor = ___FILEBASENAME___Interactor(dataManager: dataManager)
mockPresenter = Mock___FILEBASENAME___Presenter()
interactor.output = mockPresenter
}
func testGetDisplayData() {
let displayData = interactor.getDisplayData()
XCTAssert(displayData.count == numTestItems)
}
func testRefreshData() {
interactor.refreshData()
XCTAssertTrue(mockPresenter.wasSetDisplayDataCalled)
}
// Add additional tests ...
}
| mit |
chriswunsch00/CWCoreData | CWCoreData/Classes/CoreDataExtensions.swift | 1 | 6990 | //
// ManagedObjectHelpers.swift
// CoreDataHelper
//
// Created by Chris Wunsch on 17/10/2016.
// Copyright © 2016 Minty Water Ltd. All rights reserved.
//
import Foundation
import CoreData
public extension NSManagedObjectContext
{
/// Delete more than one managed object quickly and easily.
///
/// - Parameter objects: the objects to delete
func delete(allObjects objects : [NSManagedObject]) {
for object in objects {
delete(object)
}
}
}
public extension NSManagedObject
{
/// Insert a new record into the database. This will return the newly created managed object
///
/// - Parameter context: the context in which to insert the record
/// - Returns: a new NSManagedObject
class func insertNewInstance(withContext context : NSManagedObjectContext) -> NSManagedObject
{
return NSEntityDescription.insertNewObject(forEntityName: self.className, into: context)
}
/// The entity description for the object in the database
///
/// - Parameter context: the context in whch the entity exists
/// - Returns: the NSEntityDescription for the object
class func entityDescription(withContext context : NSManagedObjectContext) -> NSEntityDescription
{
return NSEntityDescription.entity(forEntityName: self.className, in: context)!
}
/// Create a fetch request with the provided context
///
/// - Parameter context: the context for which the fetch request should be created
/// - Returns: the NSFetchRequest
class func fetchRequest(withContext context : NSManagedObjectContext) -> NSFetchRequest<NSManagedObject>
{
let request : NSFetchRequest<NSManagedObject> = NSFetchRequest()
request.entity = entityDescription(withContext: context)
return request
}
/// Create a fetch request with a batch size and an offset.
///
/// - Parameters:
/// - context: the context for which the fetch request should be created
/// - batch: the size of the batch of objects to fetch
/// - offsetSize: the offset to use
/// - Returns: the NSFetchRequest
class func fetchRequest(withContext context : NSManagedObjectContext, batchSize batch : Int, offset offsetSize : Int = 0) -> NSFetchRequest<NSManagedObject>
{
let request = fetchRequest(withContext: context)
request.fetchBatchSize = batch
if offsetSize > 0
{
request.fetchOffset = offsetSize
}
return request;
}
/// Fetch a single object from the database using a predciate. Throws if more than one object is found with that predicate.
///
/// - Parameters:
/// - predicate: the predicate to use in the fetch
/// - managedContext: the context in which to execute the fetch request
/// - pendingChanges: whether to include pending changes
/// - Returns: a new NSManagedObject - nil if no object was found
/// - Throws: throws is the fetch request fails or if more than one object is found
class func fetchSingleObject(withPredicate predicate : NSPredicate, context managedContext : NSManagedObjectContext, includesPendingChanges pendingChanges : Bool) throws -> NSManagedObject?
{
let request = fetchRequest(withContext: managedContext)
request.includesPendingChanges = pendingChanges
request.predicate = predicate
request.sortDescriptors = []
var results : [NSManagedObject]
do
{
results = try managedContext.fetch(request)
}
catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
if results.count > 0
{
guard results.count == 1 else {
let error = NSError(domain: "CoreDataStackDomain", code: 9000, userInfo: ["Reason" : "Fetch single object with predicate found more than one. This is considered fatal as we now do not know which one should be returned..."])
throw error
}
return results.first
}
return nil
}
/// Fetch all the objects that match the predicate and sort them using the sort descriptor.
///
/// - Parameters:
/// - predicate: the predicate to use in the fetch
/// - sortDescriptors: the sort desciptor by which to sort the fetched objects
/// - managedContext: the context in which to execute the fetch request
/// - Returns: an array of NSManagedObjects
/// - Throws: Throws errors relating to executing the fetch request
class func fetchObjects(withPredicate predicate : NSPredicate?, descriptors sortDescriptors : [NSSortDescriptor], context managedContext : NSManagedObjectContext) throws -> [NSManagedObject]
{
let request = fetchRequest(withContext: managedContext)
request.sortDescriptors = sortDescriptors
if predicate != nil
{
request.predicate = predicate;
}
var results = [NSManagedObject]()
do
{
results = try managedContext.fetch(request)
} catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
return results
}
/// Fetch all the objects that match the predicate and sort them using the descriptor. This API has an extra parameter to limit the number of objects returned as well as to set the offset.
///
/// - Parameters:
/// - offset: the offset to use in the request
/// - requestPredicate: the predicate for the request
/// - fetchLimit: the maximum nunmber of objects to return
/// - sortDescriptiors: the sort decriptor to use when sorting the objects
/// - managedContext: the context in which to execute the fetch request
/// - Returns: an array of NSManagedObjects
/// - Throws: Throws errors relating to executing the fetch request
class func fetchObjects(withOffset offset : Int, predicate requestPredicate : NSPredicate?, limit fetchLimit : Int, descriptors sortDescriptiors : [NSSortDescriptor], context managedContext : NSManagedObjectContext) throws -> [NSManagedObject]
{
let request = fetchRequest(withContext: managedContext)
request.fetchOffset = offset
request.fetchLimit = fetchLimit
request.sortDescriptors = sortDescriptiors
if requestPredicate != nil
{
request.predicate = requestPredicate
}
var results = [NSManagedObject]()
do
{
results = try managedContext.fetch(request)
}
catch
{
print("error executing request: \(error.localizedDescription)")
throw error
}
return results
}
}
| mit |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewCell/Buttom/CSYButtomLine.swift | 1 | 427 | //
// CSYButtomLine.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/15.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
class CSYButtomLine: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit |
phatblat/realm-cocoa | RealmSwift/Object.swift | 1 | 24182 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
`Object` is a class used to define Realm model objects.
In Realm you define your model classes by subclassing `Object` and adding properties to be managed.
You then instantiate and use your custom subclasses instead of using the `Object` class directly.
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var adopted: Bool
@Persisted var siblings: List<Dog>
}
```
### Supported property types
- `String`
- `Int`, `Int8`, `Int16`, `Int32`, `Int64`
- `Float`
- `Double`
- `Bool`
- `Date`
- `Data`
- `Decimal128`
- `ObjectId`
- `UUID`
- `AnyRealmValue`
- Any RawRepresentable enum whose raw type is a legal property type. Enums
must explicitly be marked as conforming to `PersistableEnum`.
- `Object` subclasses, to model many-to-one relationships
- `EmbeddedObject` subclasses, to model owning one-to-one relationships
All of the types above may also be `Optional`, with the exception of
`AnyRealmValue`. `Object` and `EmbeddedObject` subclasses *must* be Optional.
In addition to individual values, three different collection types are supported:
- `List<Element>`: an ordered mutable collection similar to `Array`.
- `MutableSet<Element>`: an unordered uniquing collection similar to `Set`.
- `Map<String, Element>`: an unordered key-value collection similar to `Dictionary`.
The Element type of collections may be any of the supported non-collection
property types listed above. Collections themselves may not be Optional, but
the values inside them may be, except for lists and sets of `Object` or
`EmbeddedObject` subclasses.
Finally, `LinkingObjects` properties can be used to track which objects link
to this one.
All properties which should be stored by Realm must be explicitly marked with
`@Persisted`. Any properties not marked with `@Persisted` will be ignored
entirely by Realm, and may be of any type.
### Querying
You can retrieve all objects of a given type from a Realm by calling the `objects(_:)` instance method.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public typealias Object = RealmSwiftObject
extension Object: RealmCollectionValue {
// MARK: Initializers
/**
Creates an unmanaged instance of a Realm object.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm.
- parameter value: The value used to populate the object.
*/
public convenience init(value: Any) {
self.init()
RLMInitializeWithValue(self, value, .partialPrivateShared())
}
// MARK: Properties
/// The Realm which manages the object, or `nil` if the object is unmanaged.
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The object schema which lists the managed properties for the object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self)!)
}
/// Indicates if the object can no longer be accessed because it is now invalid.
///
/// An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if
/// `invalidate()` is called on that Realm. This property is key-value observable.
@objc dynamic open override var isInvalidated: Bool { return super.isInvalidated }
/// A human-readable description of the object.
open override var description: String { return super.description }
/**
WARNING: This is an internal helper method not intended for public use.
It is not considered part of the public API.
:nodoc:
*/
public override final class func _getProperties() -> [RLMProperty] {
return ObjectUtil.getSwiftProperties(self)
}
// MARK: Object Customization
/**
Override this method to specify the name of a property to be used as the primary key.
Only properties of types `String`, `Int`, `ObjectId` and `UUID` can be
designated as the primary key. Primary key properties enforce uniqueness
for each value whenever the property is set, which incurs minor overhead.
Indexes are created automatically for primary key properties.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, use
`@Persisted(primaryKey: true)` instead.
- returns: The name of the property designated as the primary key, or
`nil` if the model has no primary key.
*/
@objc open class func primaryKey() -> String? { return nil }
/**
Override this method to specify the names of properties to ignore. These
properties will not be managed by the Realm that manages the object.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, any properties not
marked with `@Persisted` are automatically ignored.
- returns: An array of property names to ignore.
*/
@objc open class func ignoredProperties() -> [String] { return [] }
/**
Returns an array of property names for properties which should be indexed.
Only string, integer, boolean, `Date`, and `NSDate` properties are supported.
- warning: This function is only applicable to legacy property declarations
using `@objc`. When using `@Persisted`, use
`@Persisted(indexed: true)` instead.
- returns: An array of property names.
*/
@objc open class func indexedProperties() -> [String] { return [] }
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
@objc open subscript(key: String) -> Any? {
get {
RLMDynamicGetByName(self, key)
}
set {
dynamicSet(object: self, key: key, value: newValue)
}
}
// MARK: Notifications
/**
Registers a block to be called each time the object changes.
The block will be asynchronously called after each write transaction which
deletes the object or modifies any of the managed properties of the object,
including self-assignments that set a property to its existing value.
For write transactions performed on different threads or in different
processes, the block will be called when the managing Realm is
(auto)refreshed to a version including the changes, while for local write
transactions it will be called at some point in the future after the write
transaction is committed.
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var adopted: Bool
@Persisted var siblings: List<Dog>
}
// ... where `dog` is a managed Dog object.
dog.observe(keyPaths: ["adopted"], { changes in
// ...
})
```
- The above notification block fires for changes to the
`adopted` property, but not for any changes made to `name`.
- If the observed key path were `["siblings"]`, then any insertion,
deletion, or modification to the `siblings` list will trigger the block. A change to
`someSibling.name` would not trigger the block (where `someSibling`
is an element contained in `siblings`)
- If the observed key path were `["siblings.name"]`, then any insertion or
deletion to the `siblings` list would trigger the block. For objects
contained in the `siblings` list, only modifications to their `name` property
will trigger the block.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
If no queue is given, notifications are delivered via the standard run
loop, and so can't be delivered while the run loop is blocked by other
activity. If a queue is given, notifications are delivered to that queue
instead. When notifications can't be delivered instantly, multiple
notifications may be coalesced into a single notification.
Unlike with `List` and `Results`, there is no "initial" callback made after
you add a new notification block.
Only objects which are managed by a Realm can be observed in this way. You
must retain the returned token for as long as you want updates to be sent
to the block. To stop receiving updates, call `invalidate()` on the token.
It is safe to capture a strong reference to the observed object within the
callback block. There is no retain cycle due to that the callback is
retained by the returned token and not by the object itself.
- warning: This method cannot be called during a write transaction, or when
the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to call with information about changes to the object.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe<T: RLMObjectBase>(keyPaths: [String]? = nil,
on queue: DispatchQueue? = nil,
_ block: @escaping (ObjectChange<T>) -> Void) -> NotificationToken {
return _observe(keyPaths: keyPaths, on: queue, block)
}
// MARK: Dynamic list
/**
Returns a list of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A list of `DynamicObject`s.
:nodoc:
*/
public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! List<DynamicObject>
}
let list = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return List<DynamicObject>(objc: list._rlmCollection as! RLMArray<AnyObject>)
}
// MARK: Dynamic set
/**
Returns a set of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A set of `DynamicObject`s.
:nodoc:
*/
public func dynamicMutableSet(_ propertyName: String) -> MutableSet<DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! MutableSet<DynamicObject>
}
let set = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return MutableSet<DynamicObject>(objc: set._rlmCollection as! RLMSet<AnyObject>)
}
// MARK: Dynamic map
/**
Returns a map of `DynamicObject`s for a given property name.
- warning: This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the values returned from key-value coding.
- parameter propertyName: The name of the property.
- returns: A map with a given key type with `DynamicObject` as the value.
:nodoc:
*/
public func dynamicMap<Key: _MapKey>(_ propertyName: String) -> Map<Key, DynamicObject> {
if let dynamic = self as? DynamicObject {
return dynamic[propertyName] as! Map<Key, DynamicObject>
}
let base = RLMDynamicGetByName(self, propertyName) as! RLMSwiftCollectionBase
return Map<Key, DynamicObject>(objc: base._rlmCollection as! RLMDictionary<AnyObject, AnyObject>)
}
// MARK: Comparison
/**
Returns whether two Realm objects are the same.
Objects are considered the same if and only if they are both managed by the same
Realm and point to the same underlying object in the database.
- note: Equality comparison is implemented by `isEqual(_:)`. If the object type
is defined with a primary key, `isEqual(_:)` behaves identically to this
method. If the object type is not defined with a primary key,
`isEqual(_:)` uses the `NSObject` behavior of comparing object identity.
This method can be used to compare two objects for database equality
whether or not their object type defines a primary key.
- parameter object: The object to compare the receiver to.
*/
public func isSameObject(as object: Object?) -> Bool {
return RLMObjectBaseAreEqual(self, object)
}
}
extension Object: ThreadConfined {
/**
Indicates if this object is frozen.
- see: `Object.freeze()`
*/
public var isFrozen: Bool { return realm?.isFrozen ?? false }
/**
Returns a frozen (immutable) snapshot of this object.
The frozen copy is an immutable object which contains the same data as this
object currently contains, but will not update when writes are made to the
containing Realm. Unlike live objects, frozen objects can be accessed from any
thread.
- warning: Holding onto a frozen object for an extended period while performing write
transaction on the Realm may result in the Realm file growing to large sizes. See
`Realm.Configuration.maximumNumberOfActiveVersions` for more information.
- warning: This method can only be called on a managed object.
*/
public func freeze() -> Self {
guard let realm = realm else { throwRealmException("Unmanaged objects cannot be frozen.") }
return realm.freeze(self)
}
/**
Returns a live (mutable) reference of this object.
This method creates a managed accessor to a live copy of the same frozen object.
Will return self if called on an already live object.
*/
public func thaw() -> Self? {
guard let realm = realm else { throwRealmException("Unmanaged objects cannot be thawed.") }
return realm.thaw(self)
}
}
/**
Information about a specific property which changed in an `Object` change notification.
*/
@frozen public struct PropertyChange {
/**
The name of the property which changed.
*/
public let name: String
/**
Value of the property before the change occurred. This is not supplied if
the change happened on the same thread as the notification and for `List`
properties.
For object properties this will give the object which was previously
linked to, but that object will have its new values and not the values it
had before the changes. This means that `previousValue` may be a deleted
object, and you will need to check `isInvalidated` before accessing any
of its properties.
*/
public let oldValue: Any?
/**
The value of the property after the change occurred. This is not supplied
for `List` properties and will always be nil.
*/
public let newValue: Any?
}
/**
Information about the changes made to an object which is passed to `Object`'s
notification blocks.
*/
@frozen public enum ObjectChange<T: ObjectBase> {
/**
If an error occurs, notification blocks are called one time with a `.error`
result and an `NSError` containing details about the error. Currently the
only errors which can occur are when opening the Realm on a background
worker thread to calculate the change set. The callback will never be
called again after `.error` is delivered.
*/
case error(_ error: NSError)
/**
One or more of the properties of the object have been changed.
*/
case change(_: T, _: [PropertyChange])
/// The object has been deleted from the Realm.
case deleted
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
@objc(RealmSwiftDynamicObject)
@dynamicMemberLookup
public final class DynamicObject: Object {
public override subscript(key: String) -> Any? {
get {
let value = RLMDynamicGetByName(self, key).flatMap(coerceToNil)
if let array = value as? RLMArray<AnyObject> {
return List<DynamicObject>(objc: array)
}
if let set = value as? RLMSet<AnyObject> {
return MutableSet<DynamicObject>(objc: set)
}
if let dictionary = value as? RLMDictionary<AnyObject, AnyObject> {
return Map<String, DynamicObject>(objc: dictionary)
}
return value
}
set(value) {
RLMDynamicValidatedSet(self, key, value)
}
}
public subscript(dynamicMember member: String) -> Any? {
get {
self[member]
}
set(value) {
self[member] = value
}
}
/// :nodoc:
public override func value(forUndefinedKey key: String) -> Any? {
return self[key]
}
/// :nodoc:
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
override public class func sharedSchema() -> RLMObjectSchema? {
nil
}
}
/**
An enum type which can be stored on a Realm Object.
Only `@objc` enums backed by an Int can be stored on a Realm object, and the
enum type must explicitly conform to this protocol. For example:
```
@objc enum MyEnum: Int, RealmEnum {
case first = 1
case second = 2
case third = 7
}
class MyModel: Object {
@objc dynamic enumProperty = MyEnum.first
let optionalEnumProperty = RealmOptional<MyEnum>()
}
```
*/
public protocol RealmEnum: RealmOptionalType, _RealmSchemaDiscoverable {
/// :nodoc:
static func _rlmToRawValue(_ value: Any) -> Any
/// :nodoc:
static func _rlmFromRawValue(_ value: Any) -> Any?
}
// MARK: - Implementation
/// :nodoc:
public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _RealmSchemaDiscoverable {
static func _rlmToRawValue(_ value: Any) -> Any {
return (value as! Self).rawValue
}
static func _rlmFromRawValue(_ value: Any) -> Any? {
return Self(rawValue: value as! RawValue)
}
static func _rlmPopulateProperty(_ prop: RLMProperty) {
RawValue._rlmPopulateProperty(prop)
}
static var _rlmType: PropertyType { RawValue._rlmType }
}
internal func dynamicSet(object: ObjectBase, key: String, value: Any?) {
let bridgedValue: Any?
if let v1 = value, let v2 = v1 as? CustomObjectiveCBridgeable {
bridgedValue = v2.objCValue
} else if let v1 = value, let v2 = v1 as? RealmEnum {
bridgedValue = type(of: v2)._rlmToRawValue(v2)
} else {
bridgedValue = value
}
if RLMObjectBaseRealm(object) == nil {
object.setValue(bridgedValue, forKey: key)
} else {
RLMDynamicValidatedSet(object, key, bridgedValue)
}
}
// MARK: AssistedObjectiveCBridgeable
// FIXME: Remove when `as! Self` can be written
private func forceCastToInferred<T, V>(_ x: T) -> V {
return x as! V
}
extension Object: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self {
return forceCastToInferred(objectiveCValue)
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil)
}
}
// MARK: Key Path Strings
extension ObjectBase {
internal func prepareForRecording() {
let objectSchema = ObjectSchema(RLMObjectBaseObjectSchema(self)!)
(objectSchema.rlmObjectSchema.properties + objectSchema.rlmObjectSchema.computedProperties)
.map { (prop: $0, accessor: $0.swiftAccessor) }
.forEach { $0.accessor?.observe($0.prop, on: self) }
}
}
/**
Gets the components of a given key path as a string.
- warning: Objects that declare properties with the old `@objc dynamic` syntax are not fully supported
by this function, and it is recommened that you use `@Persisted` to declare your properties if you wish to use
this function to its full benefit.
Example:
```
let name = ObjectBase._name(for: \Person.dogs[0].name) // "dogs.name"
// Note that the above KeyPath expression is only supported with properties declared
// with `@Persisted`.
let nested = ObjectBase._name(for: \Person.address.city.zip) // "address.city.zip"
```
*/
public func _name<T: ObjectBase>(for keyPath: PartialKeyPath<T>) -> String {
if let name = keyPath._kvcKeyPathString {
return name
}
let traceObject = T()
traceObject.lastAccessedNames = NSMutableArray()
traceObject.prepareForRecording()
let value = traceObject[keyPath: keyPath]
if let collection = value as? PropertyNameConvertible,
let propertyInfo = collection.propertyInformation,
propertyInfo.isLegacy {
traceObject.lastAccessedNames?.add(propertyInfo.key)
}
if let storage = value as? RLMSwiftValueStorage {
traceObject.lastAccessedNames?.add(RLMSwiftValueStorageGetPropertyName(storage))
}
return traceObject.lastAccessedNames!.componentsJoined(by: ".")
}
| apache-2.0 |
hejunbinlan/Operations | Operations/Conditions/Permissions/CalendarCondition.swift | 1 | 3120 | //
// CalendarCondition.swift
// Operations
//
// Created by Daniel Thorpe on 09/08/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import EventKit
public protocol EventKitAuthorizationManagerType {
func authorizationStatusForEntityType(entityType: EKEntityType) -> EKAuthorizationStatus
func requestAccessToEntityType(entityType: EKEntityType, completion: EKEventStoreRequestAccessCompletionHandler)
}
private struct EventKitAuthorizationManager: EventKitAuthorizationManagerType {
var store = EKEventStore()
func authorizationStatusForEntityType(entityType: EKEntityType) -> EKAuthorizationStatus {
return EKEventStore.authorizationStatusForEntityType(entityType)
}
func requestAccessToEntityType(entityType: EKEntityType, completion: EKEventStoreRequestAccessCompletionHandler) {
store.requestAccessToEntityType(entityType, completion: completion)
}
}
public struct CalendarCondition: OperationCondition {
public enum Error: ErrorType {
case AuthorizationFailed(status: EKAuthorizationStatus)
}
public let name = "Calendar"
public let isMutuallyExclusive = false
let entityType: EKEntityType
let manager: EventKitAuthorizationManagerType
public init(type: EKEntityType) {
self.init(type: type, authorizationManager: EventKitAuthorizationManager())
}
/**
Testing Interface
Instead use
init(type: EKEntityType)
*/
init(type: EKEntityType, authorizationManager: EventKitAuthorizationManagerType) {
entityType = type
manager = authorizationManager
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return CalendarPermissionOperation(type: entityType, authorizationManager: manager)
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
let status = manager.authorizationStatusForEntityType(entityType)
switch status {
case .Authorized:
completion(.Satisfied)
default:
completion(.Failed(Error.AuthorizationFailed(status: status)))
}
}
}
public func ==(a: CalendarCondition.Error, b: CalendarCondition.Error) -> Bool {
switch (a, b) {
case let (.AuthorizationFailed(aStatus), .AuthorizationFailed(bStatus)):
return aStatus == bStatus
}
}
class CalendarPermissionOperation: Operation {
let entityType: EKEntityType
let manager: EventKitAuthorizationManagerType
init(type: EKEntityType, authorizationManager: EventKitAuthorizationManagerType = EventKitAuthorizationManager()) {
entityType = type
manager = authorizationManager
}
override func execute() {
switch manager.authorizationStatusForEntityType(entityType) {
case .NotDetermined:
dispatch_async(Queue.Main.queue, request)
default:
finish()
}
}
func request() {
manager.requestAccessToEntityType(entityType) { (granted, error) in
self.finish()
}
}
}
| mit |
BellAppLab/Defines | Sources/Defines/Defines+OS.swift | 1 | 2554 | /*
Copyright (c) 2018 Bell App Lab <apps@bellapplab.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(iOS) || os(tvOS)
import UIKit
#endif
#if os(watchOS)
import WatchKit
#endif
#if os(macOS)
import AppKit
#endif
//MARK: - Main
public extension Defines.OS
{
/// The version of the OS currently running your app (aka `UIDevice.current.systemVersion`)
public static let version: Defines.Version = {
#if os(iOS) || os(tvOS)
return Defines.Version(versionString: UIDevice.current.systemVersion)
#endif
#if os(watchOS)
return Defines.Version(versionString: WKInterfaceDevice.current().systemVersion)
#endif
#if os(macOS)
return Defines.Version(operatingSystemVersion: ProcessInfo.processInfo.operatingSystemVersion)
#endif
}()
/// Returns true when running on iOS.
public static let isiOS: Bool = {
#if os(iOS)
return true
#else
return false
#endif
}()
/// Returns true when running on watchOS.
public static let isWatchOS: Bool = {
#if os(watchOS)
return true
#else
return false
#endif
}()
/// Returns true when running on tvOS.
public static let istvOS: Bool = {
#if os(tvOS)
return true
#else
return false
#endif
}()
/// Returns true when running on macOS.
public static let isMacOS: Bool = {
#if os(macOS)
return true
#else
return false
#endif
}()
}
| mit |
OscarSwanros/swift | test/IRGen/objc_generic_class_debug_info.swift | 28 | 243 |
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -emit-ir -g -verify
// REQUIRES: objc_interop
import Swift
import Foundation
import objc_generics
extension GenericClass {
func method() {}
class func classMethod() {}
}
| apache-2.0 |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/UILibrary/DataManagers/SFTableManager.swift | 1 | 13608 | //
// SFTableManager.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 30/04/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
import DeepDiff
public protocol SFTableAdapterDelegate: class {
func didSelectCell<DataType: SFDataType>(with item: DataType, at indexPath: IndexPath, tableView: SFTableView)
func heightForRow(at indexPath: IndexPath, tableView: SFTableView) -> CGFloat?
func prepareCell<DataType: SFDataType>(_ cell: SFTableViewCell, at indexPath: IndexPath, with item: DataType)
var useCustomHeader: Bool { get }
func prepareHeader<DataType: SFDataType>(_ view: SFTableViewHeaderView, with section: SFDataSection<DataType>, at index: Int)
var useCustomFooter: Bool { get }
func prepareFooter<DataType: SFDataType>(_ view: SFTableViewFooterView, with section: SFDataSection<DataType>, at index: Int)
func prefetch<DataType: SFDataType>(item: DataType, at indexPath: IndexPath)
func deleted<DataType: SFDataType>(item: DataType, at indexPath: IndexPath)
}
public extension SFTableAdapterDelegate {
func didSelectCell<DataType: SFDataType>(with item: DataType, at indexPath: IndexPath, tableView: SFTableView) {}
func heightForRow(at indexPath: IndexPath, tableView: SFTableView) -> CGFloat? { return nil }
var useCustomHeader: Bool { return false }
func prepareHeader<DataType: SFDataType>(_ view: SFTableViewHeaderView, with section: SFDataSection<DataType>, at index: Int) {}
var useCustomFooter: Bool { return false }
func prepareFooter<DataType: SFDataType>(_ view: SFTableViewFooterView, with section: SFDataSection<DataType>, at index: Int) {}
func prefetch<DataType: SFDataType>(item: DataType, at indexPath: IndexPath) {}
func deleted<DataType: SFDataType>(item: DataType, at indexPath: IndexPath) {}
}
public final class SFTableAdapter
<DataType: SFDataType, CellType: SFTableViewCell, HeaderType: SFTableViewHeaderView, FooterType: SFTableViewFooterView>
: NSObject, UITableViewDataSource, UITableViewDelegate, UITableViewDataSourcePrefetching {
// MARK: - Instance Properties
public weak var delegate: SFTableAdapterDelegate? {
didSet {
registerHeightForViews()
}
}
public weak var tableView: SFTableView?
public weak var dataManager: SFDataManager<DataType>?
public var insertAnimation: UITableView.RowAnimation = .automatic
public var deleteAnimation: UITableView.RowAnimation = .automatic
public var updateAnimation: UITableView.RowAnimation = .automatic
public var addIndexList: Bool = false
public var enableEditing: Bool = false
public func configure(tableView: SFTableView, dataManager: SFDataManager<DataType>) {
self.dataManager = dataManager
self.tableView = tableView
dataManager.delegate = self
tableView.dataSource = self
tableView.delegate = self
tableView.prefetchDataSource = self
registerViews()
registerHeightForViews()
}
private func registerViews() {
tableView?.register(CellType.self, forCellReuseIdentifier: CellType.identifier)
tableView?.register(HeaderType.self, forHeaderFooterViewReuseIdentifier: HeaderType.identifier)
tableView?.register(FooterType.self, forHeaderFooterViewReuseIdentifier: FooterType.identifier)
}
private func registerHeightForViews() {
tableView?.rowHeight = CellType.height
if let delegate = delegate {
tableView?.sectionHeaderHeight = delegate.useCustomHeader ? HeaderType.height : 0.0
tableView?.sectionFooterHeight = delegate.useCustomFooter ? FooterType.height : 0.0
}
if tableView?.style == .grouped {
// Create a frame close to zero, but no 0 because there is a bug in UITableView(or feature?)
let frame = CGRect(x: 0, y: 0, width: CGFloat.leastNonzeroMagnitude, height: CGFloat.leastNonzeroMagnitude)
tableView?.tableHeaderView = UIView(frame: frame)
tableView?.tableFooterView = UIView(frame: frame)
tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -20, right: 0)
}
}
private var temporarySearchData: [DataType]?
public func search(_ isIncluded: (DataType) -> Bool) {
temporarySearchData = dataManager?.flatData.filter(isIncluded)
tableView?.reloadData()
}
public func clearSearch() {
temporarySearchData = nil
tableView?.reloadData()
}
// MARK: - UITableViewDataSource
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if temporarySearchData != nil { return nil }
if addIndexList {
return dataManager?.compactMap({ $0.identifier })
} else {
return nil
}
}
public func numberOfSections(in tableView: UITableView) -> Int {
guard let dataManager = dataManager else { return 0 }
return temporarySearchData == nil ? dataManager.count : 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let dataManager = dataManager else { return 0 }
return temporarySearchData?.count ?? dataManager[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CellType.identifier, for: indexPath) as? CellType else {
return UITableViewCell()
}
guard let dataManager = dataManager else { return UITableViewCell() }
if let temporarySearchData = temporarySearchData {
delegate?.prepareCell(cell, at: indexPath, with: temporarySearchData[indexPath.row])
} else {
delegate?.prepareCell(cell, at: indexPath, with: dataManager.getItem(at: indexPath))
}
return cell
}
// MARK: - UITableViewDelegate
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return temporarySearchData != nil ? false : enableEditing
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let item = dataManager?.getItem(at: indexPath) else { return }
dataManager?.deleteItem(at: indexPath)
delegate?.deleted(item: item, at: indexPath)
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let tableView = tableView as? SFTableView,
let dataManager = dataManager
else { return }
if let temporarySearchData = temporarySearchData {
let item = temporarySearchData[indexPath.row]
delegate?.didSelectCell(with: item, at: indexPath, tableView: tableView)
} else {
let item = dataManager[indexPath.section].content[indexPath.row]
delegate?.didSelectCell(with: item, at: indexPath, tableView: tableView)
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let tableView = self.tableView else { return 0 }
return delegate?.heightForRow(at: indexPath, tableView: tableView) ?? tableView.rowHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if temporarySearchData != nil { return 0.0 }
if let delegate = delegate {
return delegate.useCustomHeader ? HeaderType.height : 0.0
} else {
return 0.0
}
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let delegate = delegate else { return nil }
if temporarySearchData != nil { return nil }
if delegate.useCustomHeader {
guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderType.identifier) as? HeaderType else {
return nil
}
guard let dataManager = dataManager else { return nil }
delegate.prepareHeader(view, with: dataManager[section], at: section)
view.updateColors()
return view
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if temporarySearchData != nil { return 0.0 }
if let delegate = delegate {
return delegate.useCustomFooter ? FooterType.height : 0.0
} else {
return 0.0
}
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let delegate = delegate else { return nil }
if temporarySearchData != nil { return nil }
if delegate.useCustomFooter {
guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: FooterType.identifier) as? FooterType else {
return nil
}
guard let dataManager = dataManager else { return nil }
delegate.prepareFooter(view, with: dataManager[section], at: section)
view.updateColors()
return view
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let view = view as? HeaderType
view?.updateColors()
}
public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let view = view as? FooterType
view?.updateColors()
}
// MARK: - UITableViewDataSourcePrefetching
public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
guard let dataManager = dataManager else { return }
indexPaths.forEach { (indexPath) in
delegate?.prefetch(item: dataManager.getItem(at: indexPath), at: indexPath)
}
}
}
extension SFTableAdapter: SFDataManagerDelegate {
public func updateSection<DataType>(with changes: [Change<DataType>], index: Int) where DataType: SFDataType {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.reload(changes: changes, section: index, insertionAnimation: insertAnimation, deletionAnimation: deleteAnimation, replacementAnimation: updateAnimation, updateData: {
}, completion: nil)
}
}
public func forceUpdate() {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.reloadData()
}
}
// MARK: - Sections
public func insertSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.insertSections(IndexSet(integer: index), with: insertAnimation)
}, completion: nil)
}
}
public func moveSection(from: Int, to: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.moveSection(from, toSection: to)
}, completion: nil)
}
}
public func deleteSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.deleteSections(IndexSet(integer: index), with: deleteAnimation)
}, completion: nil)
}
}
public func updateSection(at index: Int) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.reloadSections(IndexSet(integer: index), with: updateAnimation)
}, completion: nil)
}
}
// MARK: - Items
public func insertItem(at indexPath: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.insertRows(at: [indexPath], with: insertAnimation)
}, completion: nil)
}
}
public func moveItem(from: IndexPath, to: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.moveRow(at: from, to: to)
}, completion: nil)
}
}
public func deleteItem(at indexPath: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.deleteRows(at: [indexPath], with: deleteAnimation)
}, completion: nil)
}
}
public func updateItem(at index: IndexPath) {
if temporarySearchData != nil {
clearSearch()
} else {
tableView?.performBatchUpdates({
tableView?.reloadRows(at: [index], with: updateAnimation)
}, completion: nil)
}
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/04547-swift-sourcemanager-getmessage.swift | 11 | 272 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return m() {
let end = [[Void{
enum A {
struct A {
deinit {
i> Void{
}
case c,
{
Void{
}
class
case c,
| mit |
sumnerevans/wireless-debugging | mobile/ios/WirelessDebug/WirelessDebugger/WebSocket.swift | 2 | 68930 | /*
* SwiftWebSocket (websocket.swift)
*
* Copyright (C) Josh Baker. All Rights Reserved.
* Contact: @tidwall, joshbaker77@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import Foundation
private let windowBufferSize = 0x2000
private class Payload {
var ptr : UnsafeMutableRawPointer
var cap : Int
var len : Int
init(){
len = 0
cap = windowBufferSize
ptr = malloc(cap)
}
deinit{
free(ptr)
}
var count : Int {
get {
return len
}
set {
if newValue > cap {
while cap < newValue {
cap *= 2
}
ptr = realloc(ptr, cap)
}
len = newValue
}
}
func append(_ bytes: UnsafePointer<UInt8>, length: Int){
let prevLen = len
count = len+length
memcpy(ptr+prevLen, bytes, length)
}
var array : [UInt8] {
get {
var array = [UInt8](repeating: 0, count: count)
memcpy(&array, ptr, count)
return array
}
set {
count = 0
append(newValue, length: newValue.count)
}
}
var nsdata : Data {
get {
return Data(bytes: ptr.assumingMemoryBound(to: UInt8.self), count: count)
}
set {
count = 0
append((newValue as NSData).bytes.bindMemory(to: UInt8.self, capacity: newValue.count), length: newValue.count)
}
}
var buffer : UnsafeBufferPointer<UInt8> {
get {
return UnsafeBufferPointer<UInt8>(start: ptr.assumingMemoryBound(to: UInt8.self), count: count)
}
set {
count = 0
append(newValue.baseAddress!, length: newValue.count)
}
}
}
private enum OpCode : UInt8, CustomStringConvertible {
case `continue` = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xA
var isControl : Bool {
switch self {
case .close, .ping, .pong:
return true
default:
return false
}
}
var description : String {
switch self {
case .`continue`: return "Continue"
case .text: return "Text"
case .binary: return "Binary"
case .close: return "Close"
case .ping: return "Ping"
case .pong: return "Pong"
}
}
}
/// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection.
public struct WebSocketEvents {
/// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
public var open : ()->() = {}
/// An event to be called when the WebSocket connection's readyState changes to .Closed.
public var close : (_ code : Int, _ reason : String, _ wasClean : Bool)->() = {(code, reason, wasClean) in}
/// An event to be called when an error occurs.
public var error : (_ error : Error)->() = {(error) in}
/// An event to be called when a message is received from the server.
public var message : (_ data : Any)->() = {(data) in}
/// An event to be called when a pong is received from the server.
public var pong : (_ data : Any)->() = {(data) in}
/// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
public var end : (_ code : Int, _ reason : String, _ wasClean : Bool, _ error : Error?)->() = {(code, reason, wasClean, error) in}
}
/// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection.
public enum WebSocketBinaryType : CustomStringConvertible {
/// The WebSocket should transmit [UInt8] objects.
case uInt8Array
/// The WebSocket should transmit NSData objects.
case nsData
/// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk.
case uInt8UnsafeBufferPointer
public var description : String {
switch self {
case .uInt8Array: return "UInt8Array"
case .nsData: return "NSData"
case .uInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer"
}
}
}
/// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection.
@objc public enum WebSocketReadyState : Int, CustomStringConvertible {
/// The connection is not yet open.
case connecting = 0
/// The connection is open and ready to communicate.
case open = 1
/// The connection is in the process of closing.
case closing = 2
/// The connection is closed or couldn't be opened.
case closed = 3
fileprivate var isClosed : Bool {
switch self {
case .closing, .closed:
return true
default:
return false
}
}
/// Returns a string that represents the ReadyState value.
public var description : String {
switch self {
case .connecting: return "Connecting"
case .open: return "Open"
case .closing: return "Closing"
case .closed: return "Closed"
}
}
}
private let defaultMaxWindowBits = 15
/// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection.
public struct WebSocketCompression {
/// Used to accept compressed messages from the server. Default is true.
public var on = false
/// request no context takeover.
public var noContextTakeover = false
/// request max window bits.
public var maxWindowBits = defaultMaxWindowBits
}
/// The WebSocketService options are used by the services property and manages the underlying socket services.
public struct WebSocketService : OptionSet {
public typealias RawValue = UInt
var value: UInt = 0
init(_ value: UInt) { self.value = value }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: WebSocketService { return self.init(0) }
static func fromMask(_ raw: UInt) -> WebSocketService { return self.init(raw) }
public var rawValue: UInt { return self.value }
/// No services.
public static var None: WebSocketService { return self.init(0) }
/// Allow socket to handle VoIP.
public static var VoIP: WebSocketService { return self.init(1 << 0) }
/// Allow socket to handle video.
public static var Video: WebSocketService { return self.init(1 << 1) }
/// Allow socket to run in background.
public static var Background: WebSocketService { return self.init(1 << 2) }
/// Allow socket to handle voice.
public static var Voice: WebSocketService { return self.init(1 << 3) }
}
private let atEndDetails = "streamStatus.atEnd"
private let timeoutDetails = "The operation couldn’t be completed. Operation timed out"
private let timeoutDuration : CFTimeInterval = 30
public enum WebSocketError : Error, CustomStringConvertible {
case memory
case needMoreInput
case invalidHeader
case invalidAddress
case network(String)
case libraryError(String)
case payloadError(String)
case protocolError(String)
case invalidResponse(String)
case invalidCompressionOptions(String)
public var description : String {
switch self {
case .memory: return "Memory"
case .needMoreInput: return "NeedMoreInput"
case .invalidAddress: return "InvalidAddress"
case .invalidHeader: return "InvalidHeader"
case let .invalidResponse(details): return "InvalidResponse(\(details))"
case let .invalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))"
case let .libraryError(details): return "LibraryError(\(details))"
case let .protocolError(details): return "ProtocolError(\(details))"
case let .payloadError(details): return "PayloadError(\(details))"
case let .network(details): return "Network(\(details))"
}
}
public var details : String {
switch self {
case .invalidResponse(let details): return details
case .invalidCompressionOptions(let details): return details
case .libraryError(let details): return details
case .protocolError(let details): return details
case .payloadError(let details): return details
case .network(let details): return details
default: return ""
}
}
}
private class UTF8 {
var text : String = ""
var count : UInt32 = 0 // number of bytes
var procd : UInt32 = 0 // number of bytes processed
var codepoint : UInt32 = 0 // the actual codepoint
var bcount = 0
init() { text = "" }
func append(_ byte : UInt8) throws {
if count == 0 {
if byte <= 0x7F {
text.append(String(UnicodeScalar(byte)))
return
}
if byte == 0xC0 || byte == 0xC1 {
throw WebSocketError.payloadError("invalid codepoint: invalid byte")
}
if byte >> 5 & 0x7 == 0x6 {
count = 2
} else if byte >> 4 & 0xF == 0xE {
count = 3
} else if byte >> 3 & 0x1F == 0x1E {
count = 4
} else {
throw WebSocketError.payloadError("invalid codepoint: frames")
}
procd = 1
codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6)
return
}
if byte >> 6 & 0x3 != 0x2 {
throw WebSocketError.payloadError("invalid codepoint: signature")
}
codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6)
if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) {
throw WebSocketError.payloadError("invalid codepoint: out of bounds")
}
procd += 1
if procd == count {
if codepoint <= 0x7FF && count > 2 {
throw WebSocketError.payloadError("invalid codepoint: overlong")
}
if codepoint <= 0xFFFF && count > 3 {
throw WebSocketError.payloadError("invalid codepoint: overlong")
}
procd = 0
count = 0
text.append(String.init(describing: UnicodeScalar(codepoint)!))
}
return
}
func append(_ bytes : UnsafePointer<UInt8>, length : Int) throws {
if length == 0 {
return
}
if count == 0 {
var ascii = true
for i in 0 ..< length {
if bytes[i] > 0x7F {
ascii = false
break
}
}
if ascii {
text += NSString(bytes: bytes, length: length, encoding: String.Encoding.ascii.rawValue)! as String
bcount += length
return
}
}
for i in 0 ..< length {
try append(bytes[i])
}
bcount += length
}
var completed : Bool {
return count == 0
}
static func bytes(_ string : String) -> [UInt8]{
let data = string.data(using: String.Encoding.utf8)!
return [UInt8](UnsafeBufferPointer<UInt8>(start: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), count: data.count))
}
static func string(_ bytes : [UInt8]) -> String{
if let str = NSString(bytes: bytes, length: bytes.count, encoding: String.Encoding.utf8.rawValue) {
return str as String
}
return ""
}
}
private class Frame {
var inflate = false
var code = OpCode.continue
var utf8 = UTF8()
var payload = Payload()
var statusCode = UInt16(0)
var finished = true
static func makeClose(_ statusCode: UInt16, reason: String) -> Frame {
let f = Frame()
f.code = .close
f.statusCode = statusCode
f.utf8.text = reason
return f
}
func copy() -> Frame {
let f = Frame()
f.code = code
f.utf8.text = utf8.text
f.payload.buffer = payload.buffer
f.statusCode = statusCode
f.finished = finished
f.inflate = inflate
return f
}
}
private class Delegate : NSObject, StreamDelegate {
@objc func stream(_ aStream: Stream, handle eventCode: Stream.Event){
manager.signal()
}
}
@_silgen_name("zlibVersion") private func zlibVersion() -> OpaquePointer
@_silgen_name("deflateInit2_") private func deflateInit2(_ strm : UnsafeMutableRawPointer, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateInit_") private func deflateInit(_ strm : UnsafeMutableRawPointer, level : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateEnd") private func deflateEnd(_ strm : UnsafeMutableRawPointer) -> CInt
@_silgen_name("deflate") private func deflate(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt
@_silgen_name("inflateInit2_") private func inflateInit2(_ strm : UnsafeMutableRawPointer, windowBits : CInt, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflateInit_") private func inflateInit(_ strm : UnsafeMutableRawPointer, version : OpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflate") private func inflateG(_ strm : UnsafeMutableRawPointer, flush : CInt) -> CInt
@_silgen_name("inflateEnd") private func inflateEndG(_ strm : UnsafeMutableRawPointer) -> CInt
private func zerror(_ res : CInt) -> Error? {
var err = ""
switch res {
case 0: return nil
case 1: err = "stream end"
case 2: err = "need dict"
case -1: err = "errno"
case -2: err = "stream error"
case -3: err = "data error"
case -4: err = "mem error"
case -5: err = "buf error"
case -6: err = "version error"
default: err = "undefined error"
}
return WebSocketError.payloadError("zlib: \(err): \(res)")
}
private struct z_stream {
var next_in : UnsafePointer<UInt8>? = nil
var avail_in : CUnsignedInt = 0
var total_in : CUnsignedLong = 0
var next_out : UnsafeMutablePointer<UInt8>? = nil
var avail_out : CUnsignedInt = 0
var total_out : CUnsignedLong = 0
var msg : UnsafePointer<CChar>? = nil
var state : OpaquePointer? = nil
var zalloc : OpaquePointer? = nil
var zfree : OpaquePointer? = nil
var opaque : OpaquePointer? = nil
var data_type : CInt = 0
var adler : CUnsignedLong = 0
var reserved : CUnsignedLong = 0
}
private class Inflater {
var windowBits = 0
var strm = z_stream()
var tInput = [[UInt8]]()
var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF]
var bufferSize = windowBufferSize
var buffer = malloc(windowBufferSize)
init?(windowBits : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size))
if ret != 0 {
return nil
}
}
deinit{
_ = inflateEndG(&strm)
free(buffer)
}
func inflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){
var buf = buffer
var bufsiz = bufferSize
var buflen = 0
for i in 0 ..< 2{
if i == 0 {
strm.avail_in = CUnsignedInt(length)
strm.next_in = UnsafePointer<UInt8>(bufin)
} else {
if !final {
break
}
strm.avail_in = CUnsignedInt(inflateEnd.count)
strm.next_in = UnsafePointer<UInt8>(inflateEnd)
}
while true {
strm.avail_out = CUnsignedInt(bufsiz)
strm.next_out = buf?.assumingMemoryBound(to: UInt8.self)
_ = inflateG(&strm, flush: 0)
let have = bufsiz - Int(strm.avail_out)
bufsiz -= have
buflen += have
if strm.avail_out != 0{
break
}
if bufsiz == 0 {
bufferSize *= 2
let nbuf = realloc(buffer, bufferSize)
if nbuf == nil {
throw WebSocketError.payloadError("memory")
}
buffer = nbuf
buf = buffer?.advanced(by: Int(buflen))
bufsiz = bufferSize - buflen
}
}
}
return (buffer!.assumingMemoryBound(to: UInt8.self), buflen)
}
}
private class Deflater {
var windowBits = 0
var memLevel = 0
var strm = z_stream()
var bufferSize = windowBufferSize
var buffer = malloc(windowBufferSize)
init?(windowBits : Int, memLevel : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
self.memLevel = memLevel
let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(MemoryLayout<z_stream>.size))
if ret != 0 {
return nil
}
}
deinit{
_ = deflateEnd(&strm)
free(buffer)
}
/*func deflate(_ bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){
return (nil, 0, nil)
}*/
}
/// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection.
@objc public protocol WebSocketDelegate {
/// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
func webSocketOpen()
/// A function to be called when the WebSocket connection's readyState changes to .Closed.
func webSocketClose(_ code: Int, reason: String, wasClean: Bool)
/// A function to be called when an error occurs.
func webSocketError(_ error: NSError)
/// A function to be called when a message (string) is received from the server.
@objc optional func webSocketMessageText(_ text: String)
/// A function to be called when a message (binary) is received from the server.
@objc optional func webSocketMessageData(_ data: Data)
/// A function to be called when a pong is received from the server.
@objc optional func webSocketPong()
/// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
@objc optional func webSocketEnd(_ code: Int, reason: String, wasClean: Bool, error: NSError?)
}
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
private class InnerWebSocket: Hashable {
var id : Int
var mutex = pthread_mutex_t()
let request : URLRequest!
let subProtocols : [String]!
var frames : [Frame] = []
var delegate : Delegate
var inflater : Inflater!
var deflater : Deflater!
var outputBytes : UnsafeMutablePointer<UInt8>?
var outputBytesSize : Int = 0
var outputBytesStart : Int = 0
var outputBytesLength : Int = 0
var inputBytes : UnsafeMutablePointer<UInt8>?
var inputBytesSize : Int = 0
var inputBytesStart : Int = 0
var inputBytesLength : Int = 0
var createdAt = CFAbsoluteTimeGetCurrent()
var connectionTimeout = false
var eclose : ()->() = {}
var _eventQueue : DispatchQueue? = DispatchQueue.main
var _subProtocol = ""
var _compression = WebSocketCompression()
var _allowSelfSignedSSL = false
var _services = WebSocketService.None
var _event = WebSocketEvents()
var _eventDelegate: WebSocketDelegate?
var _binaryType = WebSocketBinaryType.uInt8Array
var _readyState = WebSocketReadyState.connecting
var _networkTimeout = TimeInterval(-1)
var url : String {
return request.url!.description
}
var subProtocol : String {
get { return privateSubProtocol }
}
var privateSubProtocol : String {
get { lock(); defer { unlock() }; return _subProtocol }
set { lock(); defer { unlock() }; _subProtocol = newValue }
}
var compression : WebSocketCompression {
get { lock(); defer { unlock() }; return _compression }
set { lock(); defer { unlock() }; _compression = newValue }
}
var allowSelfSignedSSL : Bool {
get { lock(); defer { unlock() }; return _allowSelfSignedSSL }
set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue }
}
var services : WebSocketService {
get { lock(); defer { unlock() }; return _services }
set { lock(); defer { unlock() }; _services = newValue }
}
var event : WebSocketEvents {
get { lock(); defer { unlock() }; return _event }
set { lock(); defer { unlock() }; _event = newValue }
}
var eventDelegate : WebSocketDelegate? {
get { lock(); defer { unlock() }; return _eventDelegate }
set { lock(); defer { unlock() }; _eventDelegate = newValue }
}
var eventQueue : DispatchQueue? {
get { lock(); defer { unlock() }; return _eventQueue; }
set { lock(); defer { unlock() }; _eventQueue = newValue }
}
var binaryType : WebSocketBinaryType {
get { lock(); defer { unlock() }; return _binaryType }
set { lock(); defer { unlock() }; _binaryType = newValue }
}
var readyState : WebSocketReadyState {
get { return privateReadyState }
}
var privateReadyState : WebSocketReadyState {
get { lock(); defer { unlock() }; return _readyState }
set { lock(); defer { unlock() }; _readyState = newValue }
}
func copyOpen(_ request: URLRequest, subProtocols : [String] = []) -> InnerWebSocket{
let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
ws.eclose = eclose
ws.compression = compression
ws.allowSelfSignedSSL = allowSelfSignedSSL
ws.services = services
ws.event = event
ws.eventQueue = eventQueue
ws.binaryType = binaryType
return ws
}
var hashValue: Int { return id }
init(request: URLRequest, subProtocols : [String] = [], stub : Bool = false){
pthread_mutex_init(&mutex, nil)
self.id = manager.nextId()
self.request = request
self.subProtocols = subProtocols
self.outputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize)
self.outputBytesSize = windowBufferSize
self.inputBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: windowBufferSize)
self.inputBytesSize = windowBufferSize
self.delegate = Delegate()
if stub{
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
_ = self
}
} else {
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
manager.add(self)
}
}
}
deinit{
if outputBytes != nil {
free(outputBytes)
}
if inputBytes != nil {
free(inputBytes)
}
pthread_mutex_init(&mutex, nil)
}
@inline(__always) fileprivate func lock(){
pthread_mutex_lock(&mutex)
}
@inline(__always) fileprivate func unlock(){
pthread_mutex_unlock(&mutex)
}
fileprivate var dirty : Bool {
lock()
defer { unlock() }
if exit {
return false
}
if connectionTimeout {
return true
}
if stage != .readResponse && stage != .handleFrames {
return true
}
if rd.streamStatus == .opening && wr.streamStatus == .opening {
return false;
}
if rd.streamStatus != .open || wr.streamStatus != .open {
return true
}
if rd.streamError != nil || wr.streamError != nil {
return true
}
if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 {
return true
}
if outputBytesLength > 0 && wr.hasSpaceAvailable{
return true
}
return false
}
enum Stage : Int {
case openConn
case readResponse
case handleFrames
case closeConn
case end
}
var stage = Stage.openConn
var rd : InputStream!
var wr : OutputStream!
var atEnd = false
var closeCode = UInt16(0)
var closeReason = ""
var closeClean = false
var closeFinal = false
var finalError : Error?
var exit = false
var more = true
func step(){
if exit {
return
}
do {
try stepBuffers(more)
try stepStreamErrors()
more = false
switch stage {
case .openConn:
try openConn()
stage = .readResponse
case .readResponse:
try readResponse()
privateReadyState = .open
fire {
self.event.open()
self.eventDelegate?.webSocketOpen()
}
stage = .handleFrames
case .handleFrames:
try stepOutputFrames()
if closeFinal {
privateReadyState = .closing
stage = .closeConn
return
}
let frame = try readFrame()
switch frame.code {
case .text:
fire {
self.event.message(data: frame.utf8.text)
self.eventDelegate?.webSocketMessageText?(frame.utf8.text)
}
case .binary:
fire {
switch self.binaryType {
case .uInt8Array:
self.event.message(data: frame.payload.array)
case .nsData:
self.event.message(data: frame.payload.nsdata)
// The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData.
self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata)
case .uInt8UnsafeBufferPointer:
self.event.message(data: frame.payload.buffer)
}
}
case .ping:
let nframe = frame.copy()
nframe.code = .pong
lock()
frames += [nframe]
unlock()
case .pong:
fire {
switch self.binaryType {
case .uInt8Array:
self.event.pong(data: frame.payload.array)
case .nsData:
self.event.pong(data: frame.payload.nsdata)
case .uInt8UnsafeBufferPointer:
self.event.pong(data: frame.payload.buffer)
}
self.eventDelegate?.webSocketPong?()
}
case .close:
lock()
frames += [frame]
unlock()
default:
break
}
case .closeConn:
if let error = finalError {
self.event.error(error)
self.eventDelegate?.webSocketError(error as NSError)
}
privateReadyState = .closed
if rd != nil {
closeConn()
fire {
self.eclose()
self.event.close(Int(self.closeCode), self.closeReason, self.closeFinal)
self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
}
}
stage = .end
case .end:
fire {
self.event.end(Int(self.closeCode), self.closeReason, self.closeClean, self.finalError)
self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as NSError?)
}
exit = true
manager.remove(self)
}
} catch WebSocketError.needMoreInput {
more = true
} catch {
if finalError != nil {
return
}
finalError = error
if stage == .openConn || stage == .readResponse {
stage = .closeConn
} else {
var frame : Frame?
if let error = error as? WebSocketError{
switch error {
case .network(let details):
if details == atEndDetails{
stage = .closeConn
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
atEnd = true
finalError = nil
}
case .protocolError:
frame = Frame.makeClose(1002, reason: "Protocol error")
case .payloadError:
frame = Frame.makeClose(1007, reason: "Payload error")
default:
break
}
}
if frame == nil {
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
}
if let frame = frame {
if frame.statusCode == 1007 {
self.lock()
self.frames = [frame]
self.unlock()
manager.signal()
} else {
manager.queue.asyncAfter(deadline: DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)){
self.lock()
self.frames += [frame]
self.unlock()
manager.signal()
}
}
}
}
}
}
func stepBuffers(_ more: Bool) throws {
if rd != nil {
if stage != .closeConn && rd.streamStatus == Stream.Status.atEnd {
if atEnd {
return;
}
throw WebSocketError.network(atEndDetails)
}
if more {
while rd.hasBytesAvailable {
var size = inputBytesSize
while size-(inputBytesStart+inputBytesLength) < windowBufferSize {
size *= 2
}
if size > inputBytesSize {
let ptr = realloc(inputBytes, size)
if ptr == nil {
throw WebSocketError.memory
}
inputBytes = ptr?.assumingMemoryBound(to: UInt8.self)
inputBytesSize = size
}
let n = rd.read(inputBytes!+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength)
if n > 0 {
inputBytesLength += n
}
}
}
}
if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 {
let n = wr.write(outputBytes!+outputBytesStart, maxLength: outputBytesLength)
if n > 0 {
outputBytesLength -= n
if outputBytesLength == 0 {
outputBytesStart = 0
} else {
outputBytesStart += n
}
}
}
}
func stepStreamErrors() throws {
if finalError == nil {
if connectionTimeout {
throw WebSocketError.network(timeoutDetails)
}
if let error = rd?.streamError {
throw WebSocketError.network(error.localizedDescription)
}
if let error = wr?.streamError {
throw WebSocketError.network(error.localizedDescription)
}
}
}
func stepOutputFrames() throws {
lock()
defer {
frames = []
unlock()
}
if !closeFinal {
for frame in frames {
try writeFrame(frame)
if frame.code == .close {
closeCode = frame.statusCode
closeReason = frame.utf8.text
closeFinal = true
return
}
}
}
}
@inline(__always) func fire(_ block: ()->()){
if let queue = eventQueue {
queue.sync {
block()
}
} else {
block()
}
}
var readStateSaved = false
var readStateFrame : Frame?
var readStateFinished = false
var leaderFrame : Frame?
func readFrame() throws -> Frame {
var frame : Frame
var finished : Bool
if !readStateSaved {
if leaderFrame != nil {
frame = leaderFrame!
finished = false
leaderFrame = nil
} else {
frame = try readFrameFragment(nil)
finished = frame.finished
}
if frame.code == .continue{
throw WebSocketError.protocolError("leader frame cannot be a continue frame")
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.needMoreInput
}
} else {
frame = readStateFrame!
finished = readStateFinished
if !finished {
let cf = try readFrameFragment(frame)
finished = cf.finished
if cf.code != .continue {
if !cf.code.isControl {
throw WebSocketError.protocolError("only ping frames can be interlaced with fragments")
}
leaderFrame = frame
return cf
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.needMoreInput
}
}
}
if !frame.utf8.completed {
throw WebSocketError.payloadError("incomplete utf8")
}
readStateSaved = false
readStateFrame = nil
readStateFinished = false
return frame
}
func closeConn() {
rd.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
wr.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
rd.delegate = nil
wr.delegate = nil
rd.close()
wr.close()
}
func openConn() throws {
var req = request!
req.setValue("websocket", forHTTPHeaderField: "Upgrade")
req.setValue("Upgrade", forHTTPHeaderField: "Connection")
if req.value(forHTTPHeaderField: "User-Agent") == nil {
req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent")
}
req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version")
if req.url == nil || req.url!.host == nil{
throw WebSocketError.invalidAddress
}
if req.url!.port == nil || req.url!.port! == 80 || req.url!.port! == 443 {
req.setValue(req.url!.host!, forHTTPHeaderField: "Host")
} else {
req.setValue("\(req.url!.host!):\(req.url!.port!)", forHTTPHeaderField: "Host")
}
let origin = req.value(forHTTPHeaderField: "Origin")
if origin == nil || origin! == ""{
req.setValue(req.url!.absoluteString, forHTTPHeaderField: "Origin")
}
if subProtocols.count > 0 {
req.setValue(subProtocols.joined(separator: ","), forHTTPHeaderField: "Sec-WebSocket-Protocol")
}
if req.url!.scheme != "wss" && req.url!.scheme != "ws" {
throw WebSocketError.invalidAddress
}
if compression.on {
var val = "permessage-deflate"
if compression.noContextTakeover {
val += "; client_no_context_takeover; server_no_context_takeover"
}
val += "; client_max_window_bits"
if compression.maxWindowBits != 0 {
val += "; server_max_window_bits=\(compression.maxWindowBits)"
}
req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions")
}
let security: TCPConnSecurity
let port : Int
if req.url!.scheme == "wss" {
port = req.url!.port ?? 443
security = .negoticatedSSL
} else {
port = req.url!.port ?? 80
security = .none
}
var path = CFURLCopyPath(req.url! as CFURL!) as String
if path == "" {
path = "/"
}
if let q = req.url!.query {
if q != "" {
path += "?" + q
}
}
var reqs = "GET \(path) HTTP/1.1\r\n"
for key in req.allHTTPHeaderFields!.keys {
if let val = req.value(forHTTPHeaderField: key) {
reqs += "\(key): \(val)\r\n"
}
}
var keyb = [UInt32](repeating: 0, count: 4)
for i in 0 ..< 4 {
keyb[i] = arc4random()
}
let rkey = Data(bytes: UnsafePointer(keyb), count: 16).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
reqs += "Sec-WebSocket-Key: \(rkey)\r\n"
reqs += "\r\n"
var header = [UInt8]()
for b in reqs.utf8 {
header += [b]
}
let addr = ["\(req.url!.host!)", "\(port)"]
if addr.count != 2 || Int(addr[1]) == nil {
throw WebSocketError.invalidAddress
}
var (rdo, wro) : (InputStream?, OutputStream?)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, addr[0] as CFString!, UInt32(Int(addr[1])!), &readStream, &writeStream);
rdo = readStream!.takeRetainedValue()
wro = writeStream!.takeRetainedValue()
(rd, wr) = (rdo!, wro!)
rd.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey)
wr.setProperty(security.level, forKey: Stream.PropertyKey.socketSecurityLevelKey)
if services.contains(.VoIP) {
rd.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.voIP.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Video) {
rd.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.video.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Background) {
rd.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.background.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if services.contains(.Voice) {
rd.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType)
wr.setProperty(StreamNetworkServiceTypeValue.voice.rawValue, forKey: Stream.PropertyKey.networkServiceType)
}
if allowSelfSignedSSL {
let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(value: false)]
rd.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String))
wr.setProperty(prop, forKey: Stream.PropertyKey(rawValue: kCFStreamPropertySSLSettings as String as String))
}
rd.delegate = delegate
wr.delegate = delegate
rd.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
wr.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
rd.open()
wr.open()
try write(header, length: header.count)
}
func write(_ bytes: UnsafePointer<UInt8>, length: Int) throws {
if outputBytesStart+outputBytesLength+length > outputBytesSize {
var size = outputBytesSize
while outputBytesStart+outputBytesLength+length > size {
size *= 2
}
let ptr = realloc(outputBytes, size)
if ptr == nil {
throw WebSocketError.memory
}
outputBytes = ptr?.assumingMemoryBound(to: UInt8.self)
outputBytesSize = size
}
memcpy(outputBytes!+outputBytesStart+outputBytesLength, bytes, length)
outputBytesLength += length
}
func readResponse() throws {
let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ]
let ptr = memmem(inputBytes!+inputBytesStart, inputBytesLength, end, 4)
if ptr == nil {
throw WebSocketError.needMoreInput
}
let buffer = inputBytes!+inputBytesStart
let bufferCount = ptr!.assumingMemoryBound(to: UInt8.self)-(inputBytes!+inputBytesStart)
let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: String.Encoding.utf8.rawValue, freeWhenDone: false) as String?
if string == nil {
throw WebSocketError.invalidHeader
}
let header = string!
var needsCompression = false
var serverMaxWindowBits = 15
let clientMaxWindowBits = 15
var key = ""
let trim : (String)->(String) = { (text) in return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)}
let eqval : (String,String)->(String) = { (line, del) in return trim(line.components(separatedBy: del)[1]) }
let lines = header.components(separatedBy: "\r\n")
for i in 0 ..< lines.count {
let line = trim(lines[i])
if i == 0 {
if !line.hasPrefix("HTTP/1.1 101"){
throw WebSocketError.invalidResponse(line)
}
} else if line != "" {
var value = ""
if line.hasPrefix("\t") || line.hasPrefix(" ") {
value = trim(line)
} else {
key = ""
if let r = line.range(of: ":") {
key = trim(line.substring(to: r.lowerBound))
value = trim(line.substring(from: r.upperBound))
}
}
switch key.lowercased() {
case "sec-websocket-subprotocol":
privateSubProtocol = value
case "sec-websocket-extensions":
let parts = value.components(separatedBy: ";")
for p in parts {
let part = trim(p)
if part == "permessage-deflate" {
needsCompression = true
} else if part.hasPrefix("server_max_window_bits="){
if let i = Int(eqval(line, "=")) {
serverMaxWindowBits = i
}
}
}
default:
break
}
}
}
if needsCompression {
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.invalidCompressionOptions("server_max_window_bits")
}
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.invalidCompressionOptions("client_max_window_bits")
}
inflater = Inflater(windowBits: serverMaxWindowBits)
if inflater == nil {
throw WebSocketError.invalidCompressionOptions("inflater init")
}
deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8)
if deflater == nil {
throw WebSocketError.invalidCompressionOptions("deflater init")
}
}
inputBytesLength -= bufferCount+4
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += bufferCount+4
}
}
class ByteReader {
var start : UnsafePointer<UInt8>
var end : UnsafePointer<UInt8>
var bytes : UnsafePointer<UInt8>
init(bytes: UnsafePointer<UInt8>, length: Int){
self.bytes = bytes
start = bytes
end = bytes+length
}
func readByte() throws -> UInt8 {
if bytes >= end {
throw WebSocketError.needMoreInput
}
let b = bytes.pointee
bytes += 1
return b
}
var length : Int {
return end - bytes
}
var position : Int {
get {
return bytes - start
}
set {
bytes = start + newValue
}
}
}
var fragStateSaved = false
var fragStatePosition = 0
var fragStateInflate = false
var fragStateLen = 0
var fragStateFin = false
var fragStateCode = OpCode.continue
var fragStateLeaderCode = OpCode.continue
var fragStateUTF8 = UTF8()
var fragStatePayload = Payload()
var fragStateStatusCode = UInt16(0)
var fragStateHeaderLen = 0
var buffer = [UInt8](repeating: 0, count: windowBufferSize)
var reusedPayload = Payload()
func readFrameFragment(_ leader : Frame?) throws -> Frame {
var inflate : Bool
var len : Int
var fin = false
var code : OpCode
var leaderCode : OpCode
var utf8 : UTF8
var payload : Payload
var statusCode : UInt16
var headerLen : Int
var leader = leader
let reader = ByteReader(bytes: inputBytes!+inputBytesStart, length: inputBytesLength)
if fragStateSaved {
// load state
reader.position += fragStatePosition
inflate = fragStateInflate
len = fragStateLen
fin = fragStateFin
code = fragStateCode
leaderCode = fragStateLeaderCode
utf8 = fragStateUTF8
payload = fragStatePayload
statusCode = fragStateStatusCode
headerLen = fragStateHeaderLen
fragStateSaved = false
} else {
var b = try reader.readByte()
fin = b >> 7 & 0x1 == 0x1
let rsv1 = b >> 6 & 0x1 == 0x1
let rsv2 = b >> 5 & 0x1 == 0x1
let rsv3 = b >> 4 & 0x1 == 0x1
if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) {
inflate = true
} else if rsv1 || rsv2 || rsv3 {
throw WebSocketError.protocolError("invalid extension")
} else {
inflate = false
}
code = OpCode.binary
if let c = OpCode(rawValue: (b & 0xF)){
code = c
} else {
throw WebSocketError.protocolError("invalid opcode")
}
if !fin && code.isControl {
throw WebSocketError.protocolError("unfinished control frame")
}
b = try reader.readByte()
if b >> 7 & 0x1 == 0x1 {
throw WebSocketError.protocolError("server sent masked frame")
}
var len64 = Int64(b & 0x7F)
var bcount = 0
if b & 0x7F == 126 {
bcount = 2
} else if len64 == 127 {
bcount = 8
}
if bcount != 0 {
if code.isControl {
throw WebSocketError.protocolError("invalid payload size for control frame")
}
len64 = 0
var i = bcount-1
while i >= 0 {
b = try reader.readByte()
len64 += Int64(b) << Int64(i*8)
i -= 1
}
}
len = Int(len64)
if code == .continue {
if code.isControl {
throw WebSocketError.protocolError("control frame cannot have the 'continue' opcode")
}
if leader == nil {
throw WebSocketError.protocolError("continue frame is missing it's leader")
}
}
if code.isControl {
if leader != nil {
leader = nil
}
if inflate {
throw WebSocketError.protocolError("control frame cannot be compressed")
}
}
statusCode = 0
if leader != nil {
leaderCode = leader!.code
utf8 = leader!.utf8
payload = leader!.payload
} else {
leaderCode = code
utf8 = UTF8()
payload = reusedPayload
payload.count = 0
}
if leaderCode == .close {
if len == 1 {
throw WebSocketError.protocolError("invalid payload size for close frame")
}
if len >= 2 {
let b1 = try reader.readByte()
let b2 = try reader.readByte()
statusCode = (UInt16(b1) << 8) + UInt16(b2)
len -= 2
if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) {
throw WebSocketError.protocolError("invalid status code for close frame")
}
}
}
headerLen = reader.position
}
let rlen : Int
let rfin : Bool
let chopped : Bool
if reader.length+reader.position-headerLen < len {
rlen = reader.length
rfin = false
chopped = true
} else {
rlen = len-reader.position+headerLen
rfin = fin
chopped = false
}
let bytes : UnsafeMutablePointer<UInt8>
let bytesLen : Int
if inflate {
(bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin)
} else {
(bytes, bytesLen) = (UnsafeMutablePointer<UInt8>.init(mutating: reader.bytes), rlen)
}
reader.bytes += rlen
if leaderCode == .text || leaderCode == .close {
try utf8.append(bytes, length: bytesLen)
} else {
payload.append(bytes, length: bytesLen)
}
if chopped {
// save state
fragStateHeaderLen = headerLen
fragStateStatusCode = statusCode
fragStatePayload = payload
fragStateUTF8 = utf8
fragStateLeaderCode = leaderCode
fragStateCode = code
fragStateFin = fin
fragStateLen = len
fragStateInflate = inflate
fragStatePosition = reader.position
fragStateSaved = true
throw WebSocketError.needMoreInput
}
inputBytesLength -= reader.position
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += reader.position
}
let f = Frame()
(f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin)
return f
}
var head = [UInt8](repeating: 0, count: 0xFF)
func writeFrame(_ f : Frame) throws {
if !f.finished{
throw WebSocketError.libraryError("cannot send unfinished frames")
}
var hlen = 0
let b : UInt8 = 0x80
var deflate = false
if deflater != nil {
if f.code == .binary || f.code == .text {
deflate = true
// b |= 0x40
}
}
head[hlen] = b | f.code.rawValue
hlen += 1
var payloadBytes : [UInt8]
var payloadLen = 0
if f.utf8.text != "" {
payloadBytes = UTF8.bytes(f.utf8.text)
} else {
payloadBytes = f.payload.array
}
payloadLen += payloadBytes.count
if deflate {
}
var usingStatusCode = false
if f.statusCode != 0 && payloadLen != 0 {
payloadLen += 2
usingStatusCode = true
}
if payloadLen < 126 {
head[hlen] = 0x80 | UInt8(payloadLen)
hlen += 1
} else if payloadLen <= 0xFFFF {
head[hlen] = 0x80 | 126
hlen += 1
var i = 1
while i >= 0 {
head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF)
hlen += 1
i -= 1
}
} else {
head[hlen] = UInt8((0x1 << 7) + 127)
hlen += 1
var i = 7
while i >= 0 {
head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF)
hlen += 1
i -= 1
}
}
let r = arc4random()
var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)]
for i in 0 ..< 4 {
head[hlen] = maskBytes[i]
hlen += 1
}
if payloadLen > 0 {
if usingStatusCode {
var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)]
for i in 0 ..< 2 {
sc[i] ^= maskBytes[i % 4]
}
head[hlen] = sc[0]
hlen += 1
head[hlen] = sc[1]
hlen += 1
for i in 2 ..< payloadLen {
payloadBytes[i-2] ^= maskBytes[i % 4]
}
} else {
for i in 0 ..< payloadLen {
payloadBytes[i] ^= maskBytes[i % 4]
}
}
}
try write(head, length: hlen)
try write(payloadBytes, length: payloadBytes.count)
}
func close(_ code : Int = 1000, reason : String = "Normal Closure") {
let f = Frame()
f.code = .close
f.statusCode = UInt16(truncatingBitPattern: code)
f.utf8.text = reason
sendFrame(f)
}
func sendFrame(_ f : Frame) {
lock()
frames += [f]
unlock()
manager.signal()
}
func send(_ message : Any) {
let f = Frame()
if let message = message as? String {
f.code = .text
f.utf8.text = message
} else if let message = message as? [UInt8] {
f.code = .binary
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.code = .binary
f.payload.append(message.baseAddress!, length: message.count)
} else if let message = message as? Data {
f.code = .binary
f.payload.nsdata = message
} else {
f.code = .text
f.utf8.text = "\(message)"
}
sendFrame(f)
}
func ping() {
let f = Frame()
f.code = .ping
sendFrame(f)
}
func ping(_ message : Any){
let f = Frame()
f.code = .ping
if let message = message as? String {
f.payload.array = UTF8.bytes(message)
} else if let message = message as? [UInt8] {
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.payload.append(message.baseAddress!, length: message.count)
} else if let message = message as? Data {
f.payload.nsdata = message
} else {
f.utf8.text = "\(message)"
}
sendFrame(f)
}
}
private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool {
return lhs.id == rhs.id
}
private enum TCPConnSecurity {
case none
case negoticatedSSL
var level: String {
switch self {
case .none: return StreamSocketSecurityLevel.none.rawValue
case .negoticatedSSL: return StreamSocketSecurityLevel.negotiatedSSL.rawValue
}
}
}
// Manager class is used to minimize the number of dispatches and cycle through network events
// using fewers threads. Helps tremendously with lowing system resources when many conncurrent
// sockets are opened.
private class Manager {
var queue = DispatchQueue(label: "SwiftWebSocketInstance", attributes: [])
var once = Int()
var mutex = pthread_mutex_t()
var cond = pthread_cond_t()
var websockets = Set<InnerWebSocket>()
var _nextId = 0
init(){
pthread_mutex_init(&mutex, nil)
pthread_cond_init(&cond, nil)
DispatchQueue(label: "SwiftWebSocket", attributes: []).async {
var wss : [InnerWebSocket] = []
while true {
var wait = true
wss.removeAll()
pthread_mutex_lock(&self.mutex)
for ws in self.websockets {
wss.append(ws)
}
for ws in wss {
self.checkForConnectionTimeout(ws)
if ws.dirty {
pthread_mutex_unlock(&self.mutex)
ws.step()
pthread_mutex_lock(&self.mutex)
wait = false
}
}
if wait {
_ = self.wait(250)
}
pthread_mutex_unlock(&self.mutex)
}
}
}
func checkForConnectionTimeout(_ ws : InnerWebSocket) {
if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .opening || ws.wr.streamStatus == .opening) {
let age = CFAbsoluteTimeGetCurrent() - ws.createdAt
if age >= timeoutDuration {
ws.connectionTimeout = true
}
}
}
func wait(_ timeInMs : Int) -> Int32 {
var ts = timespec()
var tv = timeval()
gettimeofday(&tv, nil)
ts.tv_sec = time(nil) + timeInMs / 1000;
let v1 = Int(tv.tv_usec * 1000)
let v2 = Int(1000 * 1000 * Int(timeInMs % 1000))
ts.tv_nsec = v1 + v2;
ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
ts.tv_nsec %= (1000 * 1000 * 1000);
return pthread_cond_timedwait(&self.cond, &self.mutex, &ts)
}
func signal(){
pthread_mutex_lock(&mutex)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func add(_ websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.insert(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func remove(_ websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.remove(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func nextId() -> Int {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
_nextId += 1
return _nextId
}
}
private let manager = Manager()
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
open class WebSocket: NSObject {
fileprivate var ws: InnerWebSocket
fileprivate var id = manager.nextId()
fileprivate var opened: Bool
open override var hashValue: Int { return id }
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(_ url: String){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(url: URL){
self.init(request: URLRequest(url: url), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public convenience init(_ url: String, subProtocols : [String]){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols)
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public convenience init(_ url: String, subProtocol : String){
self.init(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol])
}
/// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols.
public init(request: URLRequest, subProtocols : [String] = []){
let hasURL = request.url != nil
opened = hasURL
ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: !hasURL)
super.init()
// weak/strong pattern from:
// http://stackoverflow.com/a/17105368/424124
// https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/
ws.eclose = { [weak self] in
if let strongSelf = self {
strongSelf.opened = false
}
}
}
/// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called.
public convenience override init(){
var request = URLRequest(url: URL(string: "http://apple.com")!)
request.url = nil
self.init(request: request, subProtocols: [])
}
/// The URL as resolved by the constructor. This is always an absolute URL. Read only.
open var url : String{ return ws.url }
/// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
open var subProtocol : String{ return ws.subProtocol }
/// The compression options of the WebSocket.
open var compression : WebSocketCompression{
get { return ws.compression }
set { ws.compression = newValue }
}
/// Allow for Self-Signed SSL Certificates. Default is false.
open var allowSelfSignedSSL : Bool{
get { return ws.allowSelfSignedSSL }
set { ws.allowSelfSignedSSL = newValue }
}
/// The services of the WebSocket.
open var services : WebSocketService{
get { return ws.services }
set { ws.services = newValue }
}
/// The events of the WebSocket.
open var event : WebSocketEvents{
get { return ws.event }
set { ws.event = newValue }
}
/// The queue for firing off events. default is main_queue
open var eventQueue : DispatchQueue?{
get { return ws.eventQueue }
set { ws.eventQueue = newValue }
}
/// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array.
open var binaryType : WebSocketBinaryType{
get { return ws.binaryType }
set { ws.binaryType = newValue }
}
/// The current state of the connection; this is one of the WebSocketReadyState constants. Read only.
open var readyState : WebSocketReadyState{
return ws.readyState
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
open func open(_ url: String){
open(request: URLRequest(url: URL(string: url)!), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
open func open(nsurl url: URL){
open(request: URLRequest(url: url), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
open func open(_ url: String, subProtocols : [String]){
open(request: URLRequest(url: URL(string: url)!), subProtocols: subProtocols)
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
open func open(_ url: String, subProtocol : String){
open(request: URLRequest(url: URL(string: url)!), subProtocols: [subProtocol])
}
/// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols.
open func open(request: URLRequest, subProtocols : [String] = []){
if opened{
return
}
opened = true
ws = ws.copyOpen(request, subProtocols: subProtocols)
}
/// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket
open func open(){
open(request: ws.request, subProtocols: ws.subProtocols)
}
/**
Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing.
:param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed.
:param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).
*/
open func close(_ code : Int = 1000, reason : String = "Normal Closure"){
if !opened{
return
}
opened = false
ws.close(code, reason: reason)
}
/**
Transmits message to the server over the WebSocket connection.
:param: message The message to be sent to the server.
*/
open func send(_ message : Any){
if !opened{
return
}
ws.send(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
:param: optional message The data to be sent to the server.
*/
open func ping(_ message : Any){
if !opened{
return
}
ws.ping(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
*/
open func ping(){
if !opened{
return
}
ws.ping()
}
}
public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool {
return lhs.id == rhs.id
}
extension WebSocket {
/// The events of the WebSocket using a delegate.
public var delegate : WebSocketDelegate? {
get { return ws.eventDelegate }
set { ws.eventDelegate = newValue }
}
/**
Transmits message to the server over the WebSocket connection.
:param: text The message (string) to be sent to the server.
*/
@objc
public func send(text: String){
send(text)
}
/**
Transmits message to the server over the WebSocket connection.
:param: data The message (binary) to be sent to the server.
*/
@objc
public func send(data: Data){
send(data)
}
}
| apache-2.0 |
gottesmm/swift | test/Serialization/function.swift | 2 | 5297 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
// RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT
// CHECK-NOT: UnknownCode
import def_func
func useEq<T: EqualOperator>(_ x: T, y: T) -> Bool {
return x == y
}
// SIL: sil @main
// SIL: [[RAW:%.+]] = global_addr @_T08function3rawSiv : $*Int
// SIL: [[ZERO:%.+]] = function_ref @_T08def_func7getZeroSiyF : $@convention(thin) () -> Int
// SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Int
var raw = getZero()
// Check that 'raw' is an Int
var cooked : Int = raw
// SIL: [[GET_INPUT:%.+]] = function_ref @_T08def_func8getInputSiSi1x_tF : $@convention(thin) (Int) -> Int
// SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
var raw2 = getInput(x: raw)
// SIL: [[GET_SECOND:%.+]] = function_ref @_T08def_func9getSecondSiSi_Si1ytF : $@convention(thin) (Int, Int) -> Int
// SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
var raw3 = getSecond(raw, y: raw2)
// SIL: [[USE_NESTED:%.+]] = function_ref @_T08def_func9useNestedySi1x_Si1yt_Si1ntF : $@convention(thin) (Int, Int, Int) -> ()
// SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
useNested((raw, raw2), n: raw3)
// SIL: [[VARIADIC:%.+]] = function_ref @_T08def_func8variadicySd1x_SaySiGdtF : $@convention(thin) (Double, @owned Array<Int>) -> ()
// SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
// SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
// SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @owned Array<Int>) -> ()
variadic(x: 2.5, 4, 5)
// SIL: [[VARIADIC:%.+]] = function_ref @_T08def_func9variadic2ySaySiG_Sd1xtF : $@convention(thin) (@owned Array<Int>, Double) -> ()
variadic2(1, 2, 3, x: 5.0)
// SIL: [[SLICE:%.+]] = function_ref @_T08def_func5sliceySaySiG1x_tF : $@convention(thin) (@owned Array<Int>) -> ()
// SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
// SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
// SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@owned Array<Int>) -> ()
slice(x: [2, 4, 5])
optional(x: .some(23))
optional(x: .none)
// SIL: [[MAKE_PAIR:%.+]] = function_ref @_T08def_func8makePair{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @in τ_0_1) -> (@out τ_0_0, @out τ_0_1)
// SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}})
var pair : (Int, Double) = makePair(a: 1, b: 2.5)
// SIL: [[DIFFERENT_A:%.+]] = function_ref @_T08def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT_B:%.+]] = function_ref @_T08def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
_ = different(a: 1, b: 2)
_ = different(a: false, b: false)
// SIL: [[DIFFERENT2_A:%.+]] = function_ref @_T08def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
// SIL: [[DIFFERENT2_B:%.+]] = function_ref @_T08def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
_ = different2(a: 1, b: 2)
_ = different2(a: false, b: false)
struct IntWrapper1 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 1 }
}
struct IntWrapper2 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 2 }
}
// SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @_T08def_func16differentWrappedSbx1a_q_1btAA0D0RzAaER_5ValueQzAFRt_r0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_1.Value == τ_0_0.Value> (@in τ_0_0, @in τ_0_1) -> Bool
_ = differentWrapped(a: IntWrapper1(), b: IntWrapper2())
// SIL: {{%.+}} = function_ref @_T08def_func10overloadedySi1x_tF : $@convention(thin) (Int) -> ()
// SIL: {{%.+}} = function_ref @_T08def_func10overloadedySb1x_tF : $@convention(thin) (Bool) -> ()
overloaded(x: 1)
overloaded(x: false)
// SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> ()
primitive()
if raw == 5 {
testNoReturnAttr()
testNoReturnAttrPoly(x: 5)
}
// SIL: {{%.+}} = function_ref @_T08def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: {{%.+}} = function_ref @_T08def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Never
// SIL: sil @_T08def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: sil @_T08def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Never
do {
try throws1()
_ = try throws2(1)
} catch _ {}
// SIL: sil @_T08def_func7throws1yyKF : $@convention(thin) () -> @error Error
// SIL: sil @_T08def_func7throws2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error)
// LLVM: }
| apache-2.0 |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/OldModels/MovieCreditsMDB.swift | 1 | 1282 | //
// MovieCreditsMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-03-08.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public class MovieCreditsMDB: Decodable {
public var cast: [MovieCastMDB]?
public var crew: [CrewMDB]?
enum CodingKeys: String, CodingKey {
case cast
case crew
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
cast = try? container.decode([MovieCastMDB]?.self, forKey: .cast)
crew = try? container.decode([CrewMDB]?.self, forKey: .crew)
}
}
public class MovieCastMDB: CastCrewCommonMDB {
public var cast_id: Int!
public var character: String!
public var order: Int!
enum CodingKeys: String, CodingKey {
case cast_id
case character
case order
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
cast_id = try? container.decode(Int?.self, forKey: .cast_id)
character = try? container.decode(String?.self, forKey: .character)
order = try? container.decode(Int?.self, forKey: .order)
try super.init(from: decoder)
}
}
| mit |
VBVMI/VerseByVerse-iOS | Pods/XCGLogger/Sources/XCGLogger/Destinations/AutoRotatingFileDestination.swift | 1 | 12632 | //
// AutoRotatingFileDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-03-31.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
// MARK: - AutoRotatingFileDestination
/// A destination that outputs log details to files in a log folder, with auto-rotate options (by size or by time)
open class AutoRotatingFileDestination: FileDestination {
// MARK: - Constants
public static let autoRotatingFileDefaultMaxFileSize: UInt64 = 1_048_576
public static let autoRotatingFileDefaultMaxTimeInterval: TimeInterval = 600
// MARK: - Properties
/// Option: desired maximum size of a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize {
didSet {
if targetMaxFileSize < 1 {
targetMaxFileSize = .max
}
}
}
/// Option: desired maximum time in seconds stored in a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval {
didSet {
if targetMaxTimeInterval < 1 {
targetMaxTimeInterval = 0
}
}
}
/// Option: the desired number of archived log files to keep (number of log files may exceed this, it's a guideline only)
open var targetMaxLogFiles: UInt8 = 10 {
didSet {
cleanUpLogFiles()
}
}
/// Option: the URL of the folder to store archived log files (defaults to the same folder as the initial log file)
open var archiveFolderURL: URL? = nil {
didSet {
guard let archiveFolderURL = archiveFolderURL else { return }
try? FileManager.default.createDirectory(at: archiveFolderURL, withIntermediateDirectories: true)
}
}
/// Option: an optional closure to execute whenever the log is auto rotated
open var autoRotationCompletion: ((_ success: Bool) -> Void)? = nil
/// A custom date formatter object to use as the suffix of archived log files
internal var _customArchiveSuffixDateFormatter: DateFormatter? = nil
/// The date formatter object to use as the suffix of archived log files
open var archiveSuffixDateFormatter: DateFormatter! {
get {
guard _customArchiveSuffixDateFormatter == nil else { return _customArchiveSuffixDateFormatter }
struct Statics {
static var archiveSuffixDateFormatter: DateFormatter = {
let defaultArchiveSuffixDateFormatter = DateFormatter()
defaultArchiveSuffixDateFormatter.locale = NSLocale.current
defaultArchiveSuffixDateFormatter.dateFormat = "_yyyy-MM-dd_HHmmss"
return defaultArchiveSuffixDateFormatter
}()
}
return Statics.archiveSuffixDateFormatter
}
set {
_customArchiveSuffixDateFormatter = newValue
}
}
/// Size of the current log file
internal var currentLogFileSize: UInt64 = 0
/// Start time of the current log file
internal var currentLogStartTimeInterval: TimeInterval = 0
/// The base file name of the log file
internal var baseFileName: String = "xcglogger"
/// The extension of the log file name
internal var fileExtension: String = "log"
// MARK: - Class Properties
/// A default folder for storing archived logs if one isn't supplied
open class var defaultLogFolderURL: URL {
#if os(OSX)
let defaultLogFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#elseif os(iOS) || os(tvOS) || os(watchOS)
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let defaultLogFolderURL = urls[urls.endIndex - 1].appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#endif
}
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [FileAttributeKey: Any]? = nil, maxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize, maxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval, archiveSuffixDateFormatter: DateFormatter? = nil) {
super.init(owner: owner, writeToFile: writeToFile, identifier: identifier, shouldAppend: true, appendMarker: shouldAppend ? appendMarker : nil, attributes: attributes)
currentLogStartTimeInterval = Date().timeIntervalSince1970
self.archiveSuffixDateFormatter = archiveSuffixDateFormatter
self.shouldAppend = shouldAppend
self.targetMaxFileSize = maxFileSize
self.targetMaxTimeInterval = maxTimeInterval
guard let writeToFileURL = writeToFileURL else { return }
// Calculate some details for naming archived logs based on the current log file path/name
fileExtension = writeToFileURL.pathExtension
baseFileName = writeToFileURL.lastPathComponent
if let fileExtensionRange: Range = baseFileName.range(of: ".\(fileExtension)", options: .backwards),
fileExtensionRange.upperBound >= baseFileName.endIndex {
baseFileName = String(baseFileName[baseFileName.startIndex ..< fileExtensionRange.lowerBound])
}
let filePath: String = writeToFileURL.path
let logFileName: String = "\(baseFileName).\(fileExtension)"
if let logFileNameRange: Range = filePath.range(of: logFileName, options: .backwards),
logFileNameRange.upperBound >= filePath.endIndex {
let archiveFolderPath: String = String(filePath[filePath.startIndex ..< logFileNameRange.lowerBound])
archiveFolderURL = URL(fileURLWithPath: "\(archiveFolderPath)")
}
if archiveFolderURL == nil {
archiveFolderURL = type(of: self).defaultLogFolderURL
}
do {
// Initialize starting values for file size and start time so shouldRotate calculations are valid
let fileAttributes: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
currentLogFileSize = fileAttributes[.size] as? UInt64 ?? 0
currentLogStartTimeInterval = (fileAttributes[.creationDate] as? Date ?? Date()).timeIntervalSince1970
}
catch let error as NSError {
owner?._logln("Unable to determine current file attributes of log file: \(error.localizedDescription)", level: .warning)
}
// Because we always start by appending, regardless of the shouldAppend setting, we now need to handle the cases where we don't want to append or that we have now reached the rotation threshold for our current log file
if !shouldAppend || shouldRotate() {
rotateFile()
}
}
/// Scan the log folder and delete log files that are no longer relevant.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func cleanUpLogFiles() {
var archivedFileURLs: [URL] = self.archivedFileURLs()
guard archivedFileURLs.count > Int(targetMaxLogFiles) else { return }
archivedFileURLs.removeFirst(Int(targetMaxLogFiles))
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Delete all archived log files.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func purgeArchivedLogFiles() {
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs() {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Get the URLs of the archived log files.
///
/// - Parameters: None.
///
/// - Returns: An array of file URLs pointing to previously archived log files, sorted with the most recent logs first.
///
open func archivedFileURLs() -> [URL] {
let archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: archiveFolderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) else { return [] }
guard let identifierData: Data = identifier.data(using: .utf8) else { return [] }
var archivedDetails: [(url: URL, timestamp: String)] = []
for fileURL in fileURLs {
guard let archivedLogIdentifierOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey) else { continue }
guard let archivedLogIdentifierData = archivedLogIdentifierOptionalData else { continue }
guard archivedLogIdentifierData == identifierData else { continue }
guard let timestampOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey) else { continue }
guard let timestampData = timestampOptionalData else { continue }
guard let timestamp = String(data: timestampData, encoding: .utf8) else { continue }
archivedDetails.append((fileURL, timestamp))
}
archivedDetails.sort(by: { (lhs, rhs) -> Bool in lhs.timestamp > rhs.timestamp })
var archivedFileURLs: [URL] = []
for archivedDetail in archivedDetails {
archivedFileURLs.append(archivedDetail.url)
}
return archivedFileURLs
}
/// Rotate the current log file.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func rotateFile() {
var archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
archiveFolderURL = archiveFolderURL.appendingPathComponent("\(baseFileName)\(archiveSuffixDateFormatter.string(from: Date()))")
archiveFolderURL = archiveFolderURL.appendingPathExtension(fileExtension)
rotateFile(to: archiveFolderURL, closure: autoRotationCompletion)
currentLogStartTimeInterval = Date().timeIntervalSince1970
currentLogFileSize = 0
cleanUpLogFiles()
}
/// Determine if the log file should be rotated.
///
/// - Parameters: None.
///
/// - Returns:
/// - true: The log file should be rotated.
/// - false: The log file doesn't have to be rotated.
///
open func shouldRotate() -> Bool {
// Do not rotate until critical setup has been completed so that we do not accidentally rotate once to the defaultLogFolderURL before determining the desired log location
guard archiveFolderURL != nil else { return false }
// File Size
guard currentLogFileSize < targetMaxFileSize else { return true }
// Time Interval, zero = never rotate
guard targetMaxTimeInterval > 0 else { return false }
// Time Interval, else check time
guard Date().timeIntervalSince1970 - currentLogStartTimeInterval < targetMaxTimeInterval else { return true }
return false
}
// MARK: - Overridden Methods
/// Write the log to the log file.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func write(message: String) {
currentLogFileSize += UInt64(message.characters.count)
super.write(message: message)
if shouldRotate() {
rotateFile()
}
}
}
| mit |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Models/OneTap/PXOfflinePaymentType.swift | 1 | 472 | import Foundation
public struct PXOfflinePaymentType: Codable {
let id: String
let name: PXText?
let paymentMethods: [PXOfflinePaymentMethod]
enum CodingKeys: String, CodingKey {
case id
case name
case paymentMethods = "payment_methods"
}
public init(id: String, name: PXText?, paymentMethods: [PXOfflinePaymentMethod]) {
self.id = id
self.name = name
self.paymentMethods = paymentMethods
}
}
| mit |
alexkater/OrganizerSport_IOS | OrganizerSport/Modules/Login/LoginContract.swift | 1 | 562 | //
// LoginContract.swift
// OrganizerSport
//
// Created by Alejandro Arjonilla Garcia on 22.08.17.
// Copyright © 2017 ArjonillaInk. All rights reserved.
//
import Foundation
protocol LoginView: BaseView {
// Declare view methods
}
protocol LoginPresentation: class {
// Declare presentation methods
func viewDidLoad()
}
protocol LoginUseCase: class {
// Declare use case methods
}
protocol LoginInteractorOutput: class {
// Declare interactor output methods
}
protocol LoginWireframe: class {
// Declare wireframe methods
}
| mit |
juliangrosshauser/PercentAge | PercentAgeKitTests/Classes/AgeViewModelSpec.swift | 1 | 8286 | //
// AgeViewModelSpec.swift
// PercentAgeKitTests
//
// Created by Julian Grosshauser on 14/03/15.
// Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//
import Quick
import Nimble
import PercentAgeKit
class AgeViewModelSpec: QuickSpec {
override func spec() {
var dateFormatter: NSDateFormatter!
beforeSuite {
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
}
describe("AgeViewModel") {
var ageViewModel: AgeViewModel!
beforeEach {
ageViewModel = AgeViewModel()
}
//MARK: ageInPercent
describe("ageInPercent") {
var birthday: NSDate!
var today: NSDate!
context("when birthday is today") {
beforeEach {
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("06-03-2015")
}
it("returns whole number") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("24.00"))
}
}
context("when birthday hasn't happened this year yet") {
beforeEach {
// difference of 31 days
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("03-02-2015")
}
it("returns correct age in percent") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("23.92"))
}
}
context("when birthday has happened this year already") {
beforeEach {
// difference of 31 days
birthday = dateFormatter.dateFromString("06-03-1991")
today = dateFormatter.dateFromString("06-04-2015")
}
it("returns correct age in percent") {
let ageInPercent = ageViewModel.ageInPercent(birthday: birthday, today: today)
let ageInPercentRoundedString = NSString(format: "%.2f", ageInPercent)
expect(ageInPercentRoundedString).to(equal("24.08"))
}
}
}
//MARK: dayDifference
describe("dayDifference") {
var before: NSDate!
var after: NSDate!
context("dates are in same year") {
context("dates are in same month") {
context("dates are on same day") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-03-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(0))
}
}
context("dates are on different days") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("27-03-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(21))
}
}
}
context("dates are in different months") {
context("dates are on same day") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-05-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(61))
}
}
context("dates are on different days") {
it("returns correct number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("18-04-1991")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(43))
}
}
}
}
context("dates are in different years") {
context("dates are in same month") {
context("dates are on same day") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-03-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(731))
}
}
context("dates are on different days") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("11-03-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(736))
}
}
}
context("dates are in different months") {
context("dates are on same day") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("06-04-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(762))
}
}
context("dates are on different days") {
it("returns correct number of days") {
// 1992 is a leap year
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("14-05-1993")
let days = ageViewModel.dayDifference(before: before, after: after)
expect(days).to(equal(800))
}
}
}
}
context("before and after dates are switched") {
it("returns negative number of days") {
before = dateFormatter.dateFromString("06-03-1991")
after = dateFormatter.dateFromString("07-03-1991")
let days = ageViewModel.dayDifference(before: after, after: before)
expect(days).to(equal(-1))
}
}
}
}
}
}
| mit |
nickfalk/BSImagePicker | Pod/Classes/View/AlbumTitleView.swift | 2 | 3021 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
The navigation title view with album name and a button for activating the drop down.
*/
final class AlbumTitleView: UIView {
@IBOutlet weak var albumButton: UIButton!
fileprivate var context = 0
var albumTitle = "" {
didSet {
if let imageView = self.albumButton?.imageView, let titleLabel = self.albumButton?.titleLabel {
// Set title on button
albumButton?.setTitle(self.albumTitle, for: UIControlState())
// Also set title directly to label, since it isn't done right away when setting button title
// And we need to know its width to calculate insets
titleLabel.text = self.albumTitle
titleLabel.sizeToFit()
// Adjust insets to right align image
albumButton?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.bounds.size.width, bottom: 0, right: imageView.bounds.size.width)
albumButton?.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.bounds.size.width + 4, bottom: 0, right: -(titleLabel.bounds.size.width + 4))
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Set image
albumButton?.setImage(arrowDownImage, for: UIControlState())
}
lazy var arrowDownImage: UIImage? = {
// Get path for BSImagePicker bundle
let bundlePath = Bundle(for: PhotosViewController.self).path(forResource: "BSImagePicker", ofType: "bundle")
let bundle: Bundle?
// Load bundle
if let bundlePath = bundlePath {
bundle = Bundle(path: bundlePath)
} else {
bundle = nil
}
return UIImage(named: "arrow_down", in: bundle, compatibleWith: nil)
}()
}
| mit |
Clipy/Magnet | Lib/Magnet/HotKeyCenter.swift | 1 | 6368 | //
// HotKeyCenter.swift
//
// Magnet
// GitHub: https://github.com/clipy
// HP: https://clipy-app.com
//
// Copyright © 2015-2020 Clipy Project.
//
import Cocoa
import Carbon
public final class HotKeyCenter {
// MARK: - Properties
public static let shared = HotKeyCenter()
private var hotKeys = [String: HotKey]()
private var hotKeyCount: UInt32 = 0
private let modifierEventHandler: ModifierEventHandler
private let notificationCenter: NotificationCenter
// MARK: - Initialize
init(modifierEventHandler: ModifierEventHandler = .init(), notificationCenter: NotificationCenter = .default) {
self.modifierEventHandler = modifierEventHandler
self.notificationCenter = notificationCenter
installHotKeyPressedEventHandler()
installModifiersChangedEventHandlerIfNeeded()
observeApplicationTerminate()
}
deinit {
notificationCenter.removeObserver(self)
}
}
// MARK: - Register & Unregister
public extension HotKeyCenter {
@discardableResult
func register(with hotKey: HotKey) -> Bool {
guard !hotKeys.keys.contains(hotKey.identifier) else { return false }
guard !hotKeys.values.contains(hotKey) else { return false }
hotKeys[hotKey.identifier] = hotKey
guard !hotKey.keyCombo.doubledModifiers else { return true }
/*
* Normal macOS shortcut
*
* Discussion:
* When registering a hotkey, a KeyCode that conforms to the
* keyboard layout at the time of registration is registered.
* To register a `v` on the QWERTY keyboard, `9` is registered,
* and to register a `v` on the Dvorak keyboard, `47` is registered.
* Therefore, if you change the keyboard layout after registering
* a hot key, the hot key is not assigned to the correct key.
* To solve this problem, you need to re-register the hotkeys
* when you change the layout, but it's not supported by the
* Apple Genuine app either, so it's not supported now.
*/
let hotKeyId = EventHotKeyID(signature: UTGetOSTypeFromString("Magnet" as CFString), id: hotKeyCount)
var carbonHotKey: EventHotKeyRef?
let error = RegisterEventHotKey(UInt32(hotKey.keyCombo.currentKeyCode),
UInt32(hotKey.keyCombo.modifiers),
hotKeyId,
GetEventDispatcherTarget(),
0,
&carbonHotKey)
guard error == noErr else {
unregister(with: hotKey)
return false
}
hotKey.hotKeyId = hotKeyId.id
hotKey.hotKeyRef = carbonHotKey
hotKeyCount += 1
return true
}
func unregister(with hotKey: HotKey) {
if let carbonHotKey = hotKey.hotKeyRef {
UnregisterEventHotKey(carbonHotKey)
}
hotKeys.removeValue(forKey: hotKey.identifier)
hotKey.hotKeyId = nil
hotKey.hotKeyRef = nil
}
@discardableResult
func unregisterHotKey(with identifier: String) -> Bool {
guard let hotKey = hotKeys[identifier] else { return false }
unregister(with: hotKey)
return true
}
func unregisterAll() {
hotKeys.forEach { unregister(with: $1) }
}
}
// MARK: - Terminate
extension HotKeyCenter {
private func observeApplicationTerminate() {
notificationCenter.addObserver(self,
selector: #selector(HotKeyCenter.applicationWillTerminate),
name: NSApplication.willTerminateNotification,
object: nil)
}
@objc func applicationWillTerminate() {
unregisterAll()
}
}
// MARK: - HotKey Events
private extension HotKeyCenter {
func installHotKeyPressedEventHandler() {
var pressedEventType = EventTypeSpec()
pressedEventType.eventClass = OSType(kEventClassKeyboard)
pressedEventType.eventKind = OSType(kEventHotKeyPressed)
InstallEventHandler(GetEventDispatcherTarget(), { _, inEvent, _ -> OSStatus in
return HotKeyCenter.shared.sendPressedKeyboardEvent(inEvent!)
}, 1, &pressedEventType, nil, nil)
}
func sendPressedKeyboardEvent(_ event: EventRef) -> OSStatus {
assert(Int(GetEventClass(event)) == kEventClassKeyboard, "Unknown event class")
var hotKeyId = EventHotKeyID()
let error = GetEventParameter(event,
EventParamName(kEventParamDirectObject),
EventParamName(typeEventHotKeyID),
nil,
MemoryLayout<EventHotKeyID>.size,
nil,
&hotKeyId)
guard error == noErr else { return error }
assert(hotKeyId.signature == UTGetOSTypeFromString("Magnet" as CFString), "Invalid hot key id")
let hotKey = hotKeys.values.first(where: { $0.hotKeyId == hotKeyId.id })
switch GetEventKind(event) {
case EventParamName(kEventHotKeyPressed):
hotKey?.invoke()
default:
assert(false, "Unknown event kind")
}
return noErr
}
}
// MARK: - Double Tap Modifier Event
private extension HotKeyCenter {
func installModifiersChangedEventHandlerIfNeeded() {
NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { [weak self] event in
self?.modifierEventHandler.handleModifiersEvent(with: event.modifierFlags, timestamp: event.timestamp)
}
NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event -> NSEvent? in
self?.modifierEventHandler.handleModifiersEvent(with: event.modifierFlags, timestamp: event.timestamp)
return event
}
modifierEventHandler.doubleTapped = { [weak self] tappedModifierFlags in
self?.hotKeys.values
.filter { $0.keyCombo.doubledModifiers }
.filter { $0.keyCombo.modifiers == tappedModifierFlags.carbonModifiers() }
.forEach { $0.invoke() }
}
}
}
| mit |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/classes/Home/Model/ZXStatusFrame.swift | 1 | 10155 | //
// ZXStatusFrame.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/15.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ZXStatusFrame: NSObject {
// 微博数据模型
var status : ZXStatus? {
// 根据数据计算子控件的frame
didSet {
// 计算顶部控件的frame
setupTopViewFrame();
// 计算底部工具条的frame
setupToolbarFrame();
// 计算cell的高度
cellHeight = CGRectGetMaxY(toolbarF!);
}
};
// 顶部的view的frame
var topViewF : CGRect?;
// 原创微博的view的frame
var originalViewF : CGRect?;
// 头像的父视图
var iconSupViewF : CGRect?;
// 头像的frame
var iconViewF : CGRect?;
// 会员图标的frame
var vipViewF : CGRect?;
var vRankViewF : CGRect?
// 昵称的frame
var nameLabelF : CGRect?;
// 内容的frame
var contentLabelF : CGRect?;
// 配图的frame
var photosViewF : CGRect?;
// 底部的工具条
var toolbarF : CGRect?;
// 被转发微博View的frame
var repostedViewF : CGRect?;
// 被转发微博昵称的frame
var repostedNameLabelF : CGRect?;
// 被转发微博内容的frame
var repostedContentLabelF : CGRect?;
// 被转发微博配图的frame
var repostedPhotosViewF : CGRect?;
// cell的高度
var cellHeight : CGFloat?;
// 设置顶部View的frame
func setupTopViewFrame() -> Void {
// 计算原创微博的frame
setupOriginalViewFrame();
// 计算转发微博的frame
setupRepostedViewFrame();
// 计算顶部控件的frame
let repostedStatus = self.status?.retweeted_status;
var topViewH = CGFloat(0);
// 有转发微博
if (repostedStatus != nil) {
topViewH = CGRectGetMaxY(repostedViewF!);
}
// 无转发微博
else {
topViewH = CGRectGetMaxY(originalViewF!);
}
let topViewX = CGFloat(0);
let topViewY = kCellMargin;
let topViewW = kScreenWidth;
topViewF = CGRectMake(topViewX, topViewY, topViewW, topViewH);
}
// 计算底部工具条的frame
func setupToolbarFrame() -> Void {
let toolbarX = CGFloat(0);
let toolbarY = CGRectGetMaxY(topViewF!);
let toolbarW = kScreenWidth;
let toolbarH = CGFloat(35);
toolbarF = CGRectMake(toolbarX, toolbarY, toolbarW, toolbarH);
}
// 计算原创微博的frame
func setupOriginalViewFrame() -> Void {
// 头像父视图
let iconSupViewX = kCellPadding;
let iconSupViewY = kCellPadding;
let iconSupViewW = CGFloat(35);
let iconSupViewH = CGFloat(35);
iconSupViewF = CGRectMake(iconSupViewX, iconSupViewY, iconSupViewW, iconSupViewH);
// 头像
let iconViewX = CGFloat(0);
let iconViewY = CGFloat(0);
let iconViewW = CGFloat(35);
let iconViewH = CGFloat(35);
iconViewF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);
// 会员等级图标
let image = UIImage(named: "avatar_vip");
let vRankViewX = iconSupViewW - (image?.size.width)! * 0.8;
let vRankViewY = iconSupViewH - (image?.size.height)! * 0.8;
let vRankViewW = (image?.size.width)! * 0.8;
let vRankViewH = (image?.size.height)! * 0.8;
vRankViewF = CGRectMake(vRankViewX, vRankViewY, vRankViewW, vRankViewH);
// 昵称
let nameLabelX = CGRectGetMaxX(iconSupViewF!) + kCellPadding;
let nameLabelY = iconSupViewY;
var attrs = [String : AnyObject]();
attrs[NSFontAttributeName] = UIFont.systemFontOfSize(16);
let nameLabelSize = ((status?.user?.name)! as NSString).sizeWithAttributes(attrs);
nameLabelF = CGRectMake(nameLabelX, nameLabelY, nameLabelSize.width, nameLabelSize.height);
// 会员图标
let vipViewX = CGRectGetMaxX(nameLabelF!) + kCellPadding;
let vipViewY = nameLabelY;
let vipViewW = CGFloat(14);
let vipViewH = nameLabelSize.height;
vipViewF = CGRectMake(vipViewX, vipViewY, vipViewW, vipViewH);
// 正文内容
let contentLabelX = iconSupViewX;
let contentLabelY = CGRectGetMaxY(iconSupViewF!) + kCellPadding;
let contentLabelMaxW = kScreenWidth - 2 * kCellPadding;
let contentLabelMaxSize = CGSizeMake(contentLabelMaxW, CGFloat(MAXFLOAT));
var contentLabelAttrs = [String : AnyObject]();
contentLabelAttrs[NSFontAttributeName] = UIFont.systemFontOfSize(16.0);
let contentLabelRect = ((status?.text!)! as NSString).boundingRectWithSize(contentLabelMaxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: contentLabelAttrs, context: nil);
contentLabelF = CGRectMake(contentLabelX, contentLabelY, contentLabelRect.width, contentLabelRect.height);
// 配图
let photosCount = status?.pic_urls?.count;
var originalViewH = CGFloat(0);
// 有配图
if photosCount != nil {
let photosViewX = contentLabelX;
let photosViewY = CGRectGetMaxY(contentLabelF!) + kCellPadding;
// 计算配图的尺寸
let photosViewSize = photosSizeWithCount(photosCount);
photosViewF = CGRectMake(photosViewX, photosViewY, photosViewSize!.width, photosViewSize!.height);
originalViewH = CGRectGetMaxY(photosViewF!) + kCellPadding;
}
// 没有配图
else {
originalViewH = CGRectGetMaxY(contentLabelF!) + kCellPadding;
}
// 原创微博的整体
let originalViewX = CGFloat(0);
let originalViewY = CGFloat(0);
let originalViewW = kScreenWidth;
originalViewF = CGRectMake(originalViewX, originalViewY, originalViewW, originalViewH);
}
// 根据配图的个数计算配图的frame
func photosSizeWithCount(photosCount : NSInteger?) -> CGSize? {
// 一行最多的列数
let maxCols = photosMaxCols(photosCount);
// 列数
var cols = 0;
if photosCount >= maxCols {
cols = maxCols!;
} else {
cols = photosCount!;
}
// 行数
var rows = 0;
rows = photosCount! / maxCols!;
if photosCount! % maxCols! != 0 {
rows = rows + 1;
}
// 配图的宽度取决于图片的列数
let photosViewW = CGFloat(cols) * kPhotoW + (CGFloat(cols) - 1) * kPhotoMargin;
let photosViewH = CGFloat(rows) * kPhotoH + CGFloat(rows - 1) * kPhotoMargin;
return CGSizeMake(photosViewW, photosViewH);
}
// 计算转发微博的frame
func setupRepostedViewFrame() -> Void {
let repostedStatus = status?.retweeted_status;
if (repostedStatus == nil) {
return;
}
// 昵称
let repostedNameLabelX = kCellPadding;
let repostedNameLabelY = kCellPadding;
let name = String(format: "@%@" , (repostedStatus?.user?.name)!);
var repostedNameLabelAttrs = [String : AnyObject]();
repostedNameLabelAttrs[NSFontAttributeName] = UIFont.systemFontOfSize(15);
let repostedNameLabelSize = (name as NSString).sizeWithAttributes(repostedNameLabelAttrs);
repostedNameLabelF = CGRectMake(repostedNameLabelX, repostedNameLabelY, repostedNameLabelSize.width, repostedNameLabelSize.height);
// 正文内容
let repostedContentLabelX = repostedNameLabelX;
let repostedContentLabelY = CGRectGetMaxY(repostedNameLabelF!) + kCellPadding;
let repostedContentLabelMaxW = kScreenWidth - 2 * kCellPadding;
let repostedContentLabelMaxSize = CGSizeMake(repostedContentLabelMaxW, CGFloat(MAXFLOAT));
var repostedContentLabelAttrs = [String : AnyObject]();
repostedContentLabelAttrs[NSFontAttributeName] = kRepostedContentLabelFont;
print(repostedStatus);
let repostedContentLabelRect = ((repostedStatus?.text)! as NSString).boundingRectWithSize(repostedContentLabelMaxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: repostedContentLabelAttrs, context: nil);
repostedContentLabelF = CGRectMake(repostedContentLabelX, repostedContentLabelY, repostedContentLabelRect.width, repostedContentLabelRect.height);
// 配图
let photosCount = status?.retweeted_status?.pic_urls?.count;
var repostedViewH = CGFloat(0);
if (photosCount != nil) {
// 有配图
let repostedPhotosViewX = repostedContentLabelX;
let repostedPhotosViewY = CGRectGetMaxY(repostedContentLabelF!) + kCellPadding;
// 计算配图的尺寸
let repostedPhotosViewSize = photosSizeWithCount(photosCount);
repostedPhotosViewF = CGRectMake(repostedPhotosViewX, repostedPhotosViewY, (repostedPhotosViewSize?.width)!, (repostedPhotosViewSize?.height)!);
repostedViewH = CGRectGetMaxY(repostedPhotosViewF!) + kCellPadding;
}
// 没有配图
else {
repostedViewH = CGRectGetMaxY(repostedContentLabelF!) + kCellPadding;
}
// 整体
let repostedViewX = CGFloat(0);
let repostedViewY = CGRectGetMaxY(originalViewF!);
let repostedViewW = kScreenWidth;
repostedViewF = CGRectMake(repostedViewX, repostedViewY, repostedViewW, repostedViewH);
}
override init() {
super.init();
}
}
| apache-2.0 |
vikas4goyal/IAPHelper | Example/Pods/SwiftyStoreKit/SwiftyStoreKit/PaymentQueueController.swift | 1 | 8336 | //
// PaymentQueueController.swift
// SwiftyStoreKit
//
// Copyright (c) 2017 Andrea Bizzotto (bizz84@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import StoreKit
protocol TransactionController {
/**
* - param transactions: transactions to process
* - param paymentQueue: payment queue for finishing transactions
* - return: array of unhandled transactions
*/
func processTransactions(_ transactions: [SKPaymentTransaction], on paymentQueue: PaymentQueue) -> [SKPaymentTransaction]
}
public enum TransactionResult {
case purchased(product: Product)
case restored(product: Product)
case failed(error: SKError)
}
public protocol PaymentQueue: class {
func add(_ observer: SKPaymentTransactionObserver)
func remove(_ observer: SKPaymentTransactionObserver)
func add(_ payment: SKPayment)
func restoreCompletedTransactions(withApplicationUsername username: String?)
func finishTransaction(_ transaction: SKPaymentTransaction)
}
extension SKPaymentQueue: PaymentQueue { }
extension SKPaymentTransaction {
open override var debugDescription: String {
let transactionId = transactionIdentifier ?? "null"
return "productId: \(payment.productIdentifier), transactionId: \(transactionId), state: \(transactionState), date: \(String(describing: transactionDate))"
}
}
extension SKPaymentTransactionState: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .purchasing: return "purchasing"
case .purchased: return "purchased"
case .failed: return "failed"
case .restored: return "restored"
case .deferred: return "deferred"
}
}
}
class PaymentQueueController: NSObject, SKPaymentTransactionObserver {
private let paymentsController: PaymentsController
private let restorePurchasesController: RestorePurchasesController
private let completeTransactionsController: CompleteTransactionsController
unowned let paymentQueue: PaymentQueue
deinit {
paymentQueue.remove(self)
}
init(paymentQueue: PaymentQueue = SKPaymentQueue.default(),
paymentsController: PaymentsController = PaymentsController(),
restorePurchasesController: RestorePurchasesController = RestorePurchasesController(),
completeTransactionsController: CompleteTransactionsController = CompleteTransactionsController()) {
self.paymentQueue = paymentQueue
self.paymentsController = paymentsController
self.restorePurchasesController = restorePurchasesController
self.completeTransactionsController = completeTransactionsController
super.init()
paymentQueue.add(self)
}
func startPayment(_ payment: Payment) {
let skPayment = SKMutablePayment(product: payment.product)
skPayment.applicationUsername = payment.applicationUsername
paymentQueue.add(skPayment)
paymentsController.append(payment)
}
func restorePurchases(_ restorePurchases: RestorePurchases) {
if restorePurchasesController.restorePurchases != nil {
return
}
paymentQueue.restoreCompletedTransactions(withApplicationUsername: restorePurchases.applicationUsername)
restorePurchasesController.restorePurchases = restorePurchases
}
func completeTransactions(_ completeTransactions: CompleteTransactions) {
guard completeTransactionsController.completeTransactions == nil else {
print("SwiftyStoreKit.completeTransactions() should only be called once when the app launches. Ignoring this call")
return
}
completeTransactionsController.completeTransactions = completeTransactions
}
func finishTransaction(_ transaction: PaymentTransaction) {
guard let skTransaction = transaction as? SKPaymentTransaction else {
print("Object is not a SKPaymentTransaction: \(transaction)")
return
}
paymentQueue.finishTransaction(skTransaction)
}
// MARK: SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
/*
* Some notes about how requests are processed by SKPaymentQueue:
*
* SKPaymentQueue is used to queue payments or restore purchases requests.
* Payments are processed serially and in-order and require user interaction.
* Restore purchases requests don't require user interaction and can jump ahead of the queue.
* SKPaymentQueue rejects multiple restore purchases calls.
* Having one payment queue observer for each request causes extra processing
* Failed transactions only ever belong to queued payment requests.
* restoreCompletedTransactionsFailedWithError is always called when a restore purchases request fails.
* paymentQueueRestoreCompletedTransactionsFinished is always called following 0 or more update transactions when a restore purchases request succeeds.
* A complete transactions handler is require to catch any transactions that are updated when the app is not running.
* Registering a complete transactions handler when the app launches ensures that any pending transactions can be cleared.
* If a complete transactions handler is missing, pending transactions can be mis-attributed to any new incoming payments or restore purchases.
*
* The order in which transaction updates are processed is:
* 1. payments (transactionState: .purchased and .failed for matching product identifiers)
* 2. restore purchases (transactionState: .restored, or restoreCompletedTransactionsFailedWithError, or paymentQueueRestoreCompletedTransactionsFinished)
* 3. complete transactions (transactionState: .purchased, .failed, .restored, .deferred)
* Any transactions where state == .purchasing are ignored.
*/
var unhandledTransactions = paymentsController.processTransactions(transactions, on: paymentQueue)
unhandledTransactions = restorePurchasesController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = completeTransactionsController.processTransactions(unhandledTransactions, on: paymentQueue)
unhandledTransactions = unhandledTransactions.filter { $0.transactionState != .purchasing }
if unhandledTransactions.count > 0 {
let strings = unhandledTransactions.map { $0.debugDescription }.joined(separator: "\n")
print("unhandledTransactions:\n\(strings)")
}
}
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
restorePurchasesController.restoreCompletedTransactionsFailed(withError: error)
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
restorePurchasesController.restoreCompletedTransactionsFinished()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
}
}
| mit |
grm19/quake-spotter | QuakeSpotterTests/QuakeSpotterTests.swift | 2 | 989 | //
// QuakeSpotterTests.swift
// QuakeSpotterTests
//
// Created by Greg McKeon on 10/27/15.
// Copyright © 2015 grm19. All rights reserved.
//
import XCTest
@testable import QuakeSpotter
class QuakeSpotterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/User/UserInfoRequest.swift | 1 | 929 | //
// UserInfoRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/19/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
// DOCS: https://rocket.chat/docs/developer-guides/rest-api/users/info
import SwiftyJSON
final class UserInfoRequest: APIRequest {
typealias APIResourceType = UserInfoResource
let path = "/api/v1/users.info"
let query: String?
let userId: String?
let username: String?
init(userId: String) {
self.userId = userId
self.username = nil
self.query = "userId=\(userId)"
}
init(username: String) {
self.username = username
self.userId = nil
self.query = "username=\(username)"
}
}
final class UserInfoResource: APIResource {
var user: User? {
guard let raw = raw?["user"] else { return nil }
let user = User()
user.map(raw, realm: nil)
return user
}
}
| mit |
BelledonneCommunications/linphone-iphone | Classes/Swift/Conference/Data/TimeZoneData.swift | 1 | 1725 | /*
* Copyright (c) 2010-2021 Belledonne Communications SARL.
*
* This file is part of linphone-android
* (see https://www.linphone.org).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import linphonesw
struct TimeZoneData : Comparable {
let timeZone: TimeZone
static func == (lhs: TimeZoneData, rhs: TimeZoneData) -> Bool {
return lhs.timeZone.identifier == rhs.timeZone.identifier
}
static func < (lhs: TimeZoneData, rhs: TimeZoneData) -> Bool {
return lhs.timeZone.secondsFromGMT() < rhs.timeZone.secondsFromGMT()
}
func descWithOffset() -> String {
return "\(timeZone.identifier) - GMT\(timeZone.offsetInHours())"
}
}
extension TimeZone {
func offsetFromUTC() -> String
{
let localTimeZoneFormatter = DateFormatter()
localTimeZoneFormatter.timeZone = self
localTimeZoneFormatter.dateFormat = "Z"
return localTimeZoneFormatter.string(from: Date())
}
func offsetInHours() -> String
{
let hours = secondsFromGMT()/3600
let minutes = abs(secondsFromGMT()/60) % 60
let tz_hr = String(format: "%+.2d:%.2d", hours, minutes) // "+hh:mm"
return tz_hr
}
}
| gpl-3.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01766-swift-typechecker-validatedecl.swift | 1 | 472 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol a {
protocol A {
}
}
protocol b : a {
protocol c : A {
}
}
for b
| apache-2.0 |
ben-ng/swift | test/Sema/enum_equatable_hashable.swift | 5 | 3300 | // RUN: rm -rf %t && mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift
enum Foo {
case A, B
}
if Foo.A == .B { }
var aHash: Int = Foo.A.hashValue
enum Generic<T> {
case A, B
static func method() -> Int {
// Test synthesis of == without any member lookup being done
if A == B { }
return Generic.A.hashValue
}
}
if Generic<Foo>.A == .B { }
var gaHash: Int = Generic<Foo>.A.hashValue
func localEnum() -> Bool {
enum Local {
case A, B
}
return Local.A == .B
}
enum CustomHashable {
case A, B
var hashValue: Int { return 0 }
}
func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note{{non-matching type}}
return true
}
if CustomHashable.A == .B { }
var custHash: Int = CustomHashable.A.hashValue
// We still synthesize conforming overloads of '==' and 'hashValue' if
// explicit definitions don't satisfy the protocol requirements. Probably
// not what we actually want.
enum InvalidCustomHashable {
case A, B
var hashValue: String { return "" } // expected-note{{previously declared here}}
}
func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note{{non-matching type}}
return ""
}
if InvalidCustomHashable.A == .B { }
var s: String = InvalidCustomHashable.A == .B
s = InvalidCustomHashable.A.hashValue
var i: Int = InvalidCustomHashable.A.hashValue
// Check use of an enum's synthesized members before the enum is actually declared.
struct UseEnumBeforeDeclaration {
let eqValue = EnumToUseBeforeDeclaration.A == .A
let hashValue = EnumToUseBeforeDeclaration.A.hashValue
}
enum EnumToUseBeforeDeclaration {
case A
}
// Check enums from another file in the same module.
if FromOtherFile.A == .A {}
let _: Int = FromOtherFile.A.hashValue
func getFromOtherFile() -> AlsoFromOtherFile { return .A }
if .A == getFromOtherFile() {}
// FIXME: This should work.
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A }
func overloadFromOtherFile() -> Bool { return false }
if .A == overloadFromOtherFile() {}
// Complex enums are not implicitly Equatable or Hashable.
enum Complex {
case A(Int)
case B
}
if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }}
// rdar://19773050
private enum Bar<T> {
case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}}
mutating func value() -> T {
switch self {
// FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point
case E(let x):
return x.value
}
}
}
// Equatable extension -- rdar://20981254
enum Instrument {
case Piano
case Violin
case Guitar
}
extension Instrument : Equatable {}
// Explicit conformance should work too
public enum Medicine {
case Antibiotic
case Antihistamine
}
extension Medicine : Equatable {}
public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note{{non-matching type}}
return true
}
// No explicit conformance and cannot be derived
extension Complex : Hashable {} // expected-error 2 {{does not conform}}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers/28193-swift-typechecker-lookupmembertype.swift | 3 | 276 | // RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d:CollectionType{for c d in
| apache-2.0 |
adrfer/swift | validation-test/IDE/crashers/039-swift-typechecker-checkconformance.swift | 10 | 176 | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
protocol P
struct A<I:P{var d={enum S<T{case#^A^#
| apache-2.0 |
VladimirDinic/WDFlashCard | WDFlashCard/ViewController.swift | 1 | 1683 | //
// ViewController.swift
// WDFlashCard
//
// Created by Vladimir Dinic on 7/22/17.
// Copyright © 2017 Vladimir Dinic. All rights reserved.
//
import UIKit
class ViewController: UIViewController, WDFlashCardDelegate {
@IBOutlet weak var toggleTapToFlipButton: UIButton!
@IBOutlet weak var backView: UIView!
@IBOutlet weak var frontView: UIView!
@IBOutlet weak var flashCard: WDFlashCard!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
flashCard.duration = 2.0
flashCard.flipAnimation = .flipFromLeft
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func flipPressed(_ sender: Any)
{
flashCard.flip()
}
@IBAction func disableTapToFlipPressed(_ sender: Any)
{
flashCard.disableTouchToFlipFesture = !flashCard.disableTouchToFlipFesture
toggleTapToFlipButton.setTitle("\(flashCard.disableTouchToFlipFesture ? "Enable" : "Disable") tap to flip", for: .normal)
}
//MARK: WDFlashCardDelegate methods
func flipBackView(forFlashCard flashCardView: WDFlashCard) -> UIView {
return backView
}
func flipFrontView(forFlashCard flashCardView: WDFlashCard) -> UIView {
return frontView
}
func flashCardWillFlip(forFlashCard flashCardView: WDFlashCard) {
print("Flash card will flip")
}
func flashCardFlipped(forFlashCard flashCardView: WDFlashCard) {
print("Flash card flipped")
}
}
| mit |
SebastianBoldt/Jelly | Jelly/Classes/public/Models/Configuration/Presentation/PresentationTiming.swift | 1 | 535 | import UIKit
public struct PresentationTiming: PresentationTimingProtocol {
public var duration: Duration
public var presentationCurve: UIView.AnimationCurve
public var dismissCurve: UIView.AnimationCurve
public init(duration: Duration = .medium,
presentationCurve: UIView.AnimationCurve = .linear,
dismissCurve: UIView.AnimationCurve = .linear) {
self.duration = duration
self.presentationCurve = presentationCurve
self.dismissCurve = dismissCurve
}
}
| mit |
rlasante/Swift-Trip-Tracker | LocationTracker/ViewController.swift | 1 | 1776 | //
// ViewController.swift
// LocationTracker
//
// Created by Ryan LaSante on 11/1/15.
// Copyright © 2015 rlasante. All rights reserved.
//
import UIKit
import ReactiveCocoa
class ViewController: UIViewController {
@IBOutlet weak var startButton: UIButton?
@IBOutlet weak var stopButton: UIButton?
@IBOutlet weak var speedLabel: UILabel?
var tracking = false
override func viewDidLoad() {
super.viewDidLoad()
listenForSpeedChanges()
listenForTripCompleted()
}
private func listenForSpeedChanges() {
TripManager.sharedInstance.currentSpeedSignal()
.map { (metersPerSecond) -> Double in
metersPerSecond * 2.23694
}.observeNext { [weak self] (speed) -> () in
self?.speedLabel?.text = "\(Int(speed)) MPH"
}
}
private func listenForTripCompleted() {
TripManager.sharedInstance.completedTripSignal().observeNext { [weak self] (trip) -> () in
self?.performSegueWithIdentifier("mapSegue", sender: trip)
self?.stopButton?.hidden = true
self?.speedLabel?.hidden = true
self?.speedLabel?.text = ""
self?.startButton?.hidden = false
}
}
@IBAction func startTracking(sender: UIButton) {
TripManager.sharedInstance.startTracking()
startButton?.hidden = true
stopButton?.hidden = false
speedLabel?.hidden = false
}
@IBAction func stopTracking(sender: UIButton) {
TripManager.sharedInstance.stopTracking()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "mapSegue" {
let mapViewController = segue.destinationViewController as! MapViewController
mapViewController.trip = sender as! Trip
}
}
@IBAction func doneWithMapSegue(segue: UIStoryboardSegue) {
}
}
| mit |
tgsala/HackingWithSwift | project19/project19/Capital.swift | 1 | 456 | //
// Capital.swift
// project19
//
// Created by g5 on 3/14/16.
// Copyright © 2016 tgsala. All rights reserved.
//
import UIKit
import MapKit
class Capital: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D
var info: String
init(title: String, coordinate: CLLocationCoordinate2D, info: String) {
self.title = title
self.coordinate = coordinate
self.info = info
}
}
| unlicense |
KoCMoHaBTa/MHAppKit | MHAppKit/Extensions/UIKit/UIView/UIView+Snapshot.swift | 1 | 2471 | //
// UIView+Snapshot.swift
// MHAppKit
//
// Created by Milen Halachev on 27.11.17.
// Copyright © 2017 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import Foundation
import UIKit
extension UIView {
public enum SnapshotTechnique {
case layerRendering
case drawHierarchy
@available(iOS 10.0, *)
case graphicsImageRenderer
case custom((UIView) -> UIImage?)
}
public func snapshot(using technique: SnapshotTechnique = .layerRendering) -> UIImage? {
switch technique {
case .layerRendering:
return self.layer.snapshot()
case .drawHierarchy:
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
case .graphicsImageRenderer:
if #available(iOS 10.0, *), #available(tvOS 10.0, *) {
let rendererFormat = UIGraphicsImageRendererFormat.preferred()
rendererFormat.opaque = self.isOpaque
let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: rendererFormat)
let snapshotImage = renderer.image { _ in
self.drawHierarchy(in: CGRect(origin: .zero, size: self.bounds.size), afterScreenUpdates: true)
}
return snapshotImage
}
else {
return nil
}
case .custom(let block):
return block(self)
}
}
}
extension CALayer {
public func snapshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
if let context = UIGraphicsGetCurrentContext() {
self.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
return nil
}
}
#endif
| mit |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Conversation/ConversationViewController.swift | 1 | 47866 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MobileCoreServices
import AddressBook
import AddressBookUI
import AVFoundation
//import AGEmojiKeyboard
final public class ConversationViewController:
AAConversationContentController,
UIDocumentMenuDelegate,
UIDocumentPickerDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
AALocationPickerControllerDelegate,
ABPeoplePickerNavigationControllerDelegate,
AAAudioRecorderDelegate,
AAConvActionSheetDelegate,
AAStickersKeyboardDelegate
//,
//AGEmojiKeyboardViewDataSource,
// AGEmojiKeyboardViewDelegate
{
// Data binder
fileprivate let binder = AABinder()
// Internal state
// Members for autocomplete
var filteredMembers = [ACMentionFilterResult]()
let content: ACPage!
var appStyle: ActorStyle { get { return ActorSDK.sharedActor().style } }
//
// Views
//
fileprivate let titleView: UILabel = UILabel()
open let subtitleView: UILabel = UILabel()
fileprivate let navigationView: UIView = UIView()
fileprivate let avatarView = AABarAvatarView()
fileprivate let backgroundView = UIImageView()
fileprivate var audioButton: UIButton = UIButton()
fileprivate var voiceRecorderView : AAVoiceRecorderView!
fileprivate let inputOverlay = UIView()
fileprivate let inputOverlayLabel = UILabel()
//
// Stickers
//
fileprivate var stickersView: AAStickersKeyboard!
open var stickersButton : UIButton!
fileprivate var stickersOpen = false
//fileprivate var emojiKeyboar: AGEmojiKeyboardView!
//
// Audio Recorder
//
open var audioRecorder: AAAudioRecorder!
//
// Mode
//
fileprivate var textMode:Bool!
fileprivate var micOn: Bool! = true
open var removeExcedentControllers = true
////////////////////////////////////////////////////////////
// MARK: - Init
////////////////////////////////////////////////////////////
required override public init(peer: ACPeer) {
// Data
self.content = ACAllEvents_Chat_viewWithACPeer_(peer)
// Create controller
super.init(peer: peer)
//
// Background
//
backgroundView.clipsToBounds = true
backgroundView.contentMode = .scaleAspectFill
backgroundView.backgroundColor = appStyle.chatBgColor
// Custom background if available
if let bg = Actor.getSelectedWallpaper(){
if bg != "default" {
if bg.startsWith("local:") {
backgroundView.image = UIImage.bundled(bg.skip(6))
} else {
let path = CocoaFiles.pathFromDescriptor(bg.skip(5))
backgroundView.image = UIImage(contentsOfFile:path)
}
}
}
view.insertSubview(backgroundView, at: 0)
//
// slk settings
//
self.bounces = false
self.isKeyboardPanningEnabled = true
self.registerPrefixes(forAutoCompletion: ["@"])
//
// Text Input
//
self.textInputbar.backgroundColor = appStyle.chatInputFieldBgColor
self.textInputbar.autoHideRightButton = false;
self.textInputbar.isTranslucent = false
//
// Text view
//
self.textView.placeholder = AALocalized("ChatPlaceholder")
self.textView.keyboardAppearance = ActorSDK.sharedActor().style.isDarkApp ? .dark : .light
//
// Overlay
//
self.inputOverlay.addSubview(inputOverlayLabel)
self.inputOverlayLabel.textAlignment = .center
self.inputOverlayLabel.font = UIFont.systemFont(ofSize: 18)
self.inputOverlayLabel.textColor = ActorSDK.sharedActor().style.vcTintColor
self.inputOverlay.viewDidTap = {
self.onOverlayTap()
}
//
// Add stickers button
//
self.stickersButton = UIButton(type: UIButtonType.system)
self.stickersButton.tintColor = UIColor.lightGray.withAlphaComponent(0.5)
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.stickersButton.addTarget(self, action: #selector(ConversationViewController.changeKeyboard), for: UIControlEvents.touchUpInside)
if(ActorSDK.sharedActor().delegate.showStickersButton()){
self.textInputbar.addSubview(stickersButton)
}
//
// Check text for set right button
//
let checkText = Actor.loadDraft(with: peer)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (checkText.isEmpty) {
self.textMode = false
self.rightButton.tintColor = appStyle.chatSendColor
self.rightButton.setImage(UIImage.tinted("aa_micbutton", color: appStyle.chatAttachColor), for: UIControlState())
self.rightButton.setTitle("", for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
} else {
self.textMode = true
self.stickersButton.isHidden = true
self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled)
self.rightButton.setImage(nil, for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
}
//
// Voice Recorder
//
self.audioRecorder = AAAudioRecorder()
self.audioRecorder.delegate = self
self.leftButton.setImage(UIImage.tinted("conv_attach", color: appStyle.chatAttachColor), for: UIControlState())
//
// Navigation Title
//
navigationView.frame = CGRect(x: 0, y: 0, width: 200, height: 44)
navigationView.autoresizingMask = UIViewAutoresizing.flexibleWidth
titleView.font = UIFont.mediumSystemFontOfSize(17)
titleView.adjustsFontSizeToFitWidth = false
titleView.textAlignment = NSTextAlignment.center
titleView.lineBreakMode = NSLineBreakMode.byTruncatingTail
titleView.autoresizingMask = UIViewAutoresizing.flexibleWidth
titleView.textColor = appStyle.navigationTitleColor
subtitleView.font = UIFont.systemFont(ofSize: 13)
subtitleView.adjustsFontSizeToFitWidth = true
subtitleView.textAlignment = NSTextAlignment.center
subtitleView.lineBreakMode = NSLineBreakMode.byTruncatingTail
subtitleView.autoresizingMask = UIViewAutoresizing.flexibleWidth
navigationView.addSubview(titleView)
navigationView.addSubview(subtitleView)
self.navigationItem.titleView = navigationView
//
// Navigation Avatar
//
avatarView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
avatarView.viewDidTap = onAvatarTap
let barItem = UIBarButtonItem(customView: avatarView)
let isBot: Bool
if (peer.isPrivate) {
isBot = Bool(Actor.getUserWithUid(peer.peerId).isBot())
} else {
isBot = false
}
if (ActorSDK.sharedActor().enableCalls && !isBot && peer.isPrivate) {
if ActorSDK.sharedActor().enableVideoCalls {
let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
callButtonView.viewDidTap = onCallTap
let callButtonItem = UIBarButtonItem(customView: callButtonView)
let videoCallButtonView = AACallButton(image: UIImage.bundled("ic_video_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
videoCallButtonView.viewDidTap = onVideoCallTap
let callVideoButtonItem = UIBarButtonItem(customView: videoCallButtonView)
self.navigationItem.rightBarButtonItems = [barItem, callVideoButtonItem, callButtonItem]
} else {
let callButtonView = AACallButton(image: UIImage.bundled("ic_call_outline_22")?.tintImage(ActorSDK.sharedActor().style.navigationTintColor))
callButtonView.viewDidTap = onCallTap
let callButtonItem = UIBarButtonItem(customView: callButtonView)
self.navigationItem.rightBarButtonItems = [barItem, callButtonItem]
}
} else {
self.navigationItem.rightBarButtonItems = [barItem]
}
}
required public init(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
self.voiceRecorderView = AAVoiceRecorderView(frame: CGRect(x: 0, y: 0, width: view.width - 30, height: 44))
self.voiceRecorderView.isHidden = true
self.voiceRecorderView.binedController = self
self.textInputbar.addSubview(self.voiceRecorderView)
self.inputOverlay.backgroundColor = UIColor.white
self.inputOverlay.isHidden = false
self.textInputbar.addSubview(self.inputOverlay)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
self.stickersView = AAStickersKeyboard(frame: frame)
self.stickersView.delegate = self
//emojiKeyboar.frame = frame
NotificationCenter.default.addObserver(
self,
selector: #selector(ConversationViewController.updateStickersStateOnCloseKeyboard),
name: NSNotification.Name.SLKKeyboardWillHide,
object: nil)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.stickersButton.frame = CGRect(x: self.view.frame.size.width-67, y: 12, width: 20, height: 20)
self.voiceRecorderView.frame = CGRect(x: 0, y: 0, width: view.width - 30, height: 44)
self.inputOverlay.frame = CGRect(x: 0, y: 0, width: view.width, height: 44)
self.inputOverlayLabel.frame = CGRect(x: 0, y: 0, width: view.width, height: 44)
}
////////////////////////////////////////////////////////////
// MARK: - Lifecycle
////////////////////////////////////////////////////////////
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Installing bindings
if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) {
let user = Actor.getUserWithUid(peer.peerId)
let nameModel = user.getNameModel()
let blockStatus = user.isBlockedModel().get().booleanValue()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!)
self.navigationView.sizeToFit()
})
binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(user.getNameModel().get(), id: Int(user.getId()), avatar: value)
})
binder.bind(Actor.getTypingWithUid(peer.peerId), valueModel2: user.getPresenceModel(), closure:{ (typing:JavaLangBoolean?, presence:ACUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = Actor.getFormatter().formatTyping()
self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor
} else {
if (user.isBot()) {
self.subtitleView.text = "bot"
self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor
} else {
let stateText = Actor.getFormatter().formatPresence(presence, with: user.getSex())
self.subtitleView.text = stateText;
let state = presence!.state.ordinal()
if (state == ACUserPresence_State.online().ordinal()) {
self.subtitleView.textColor = self.appStyle.userOnlineNavigationColor
} else {
self.subtitleView.textColor = self.appStyle.userOfflineNavigationColor
}
}
}
})
self.inputOverlay.isHidden = true
} else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) {
let group = Actor.getGroupWithGid(peer.peerId)
let nameModel = group.getNameModel()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(group.getNameModel().get(), id: Int(group.getId()), avatar: value)
})
binder.bind(Actor.getGroupTyping(withGid: group.getId()), valueModel2: group.membersCount, valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, membersCount: JavaLangInteger?, onlineCount:JavaLangInteger?) -> () in
if (!group.isMemberModel().get().booleanValue()) {
self.subtitleView.text = AALocalized("ChatNoGroupAccess")
self.subtitleView.textColor = self.appStyle.navigationSubtitleColor
return
}
if (typingValue != nil && typingValue!.length() > 0) {
self.subtitleView.textColor = self.appStyle.navigationSubtitleActiveColor
if (typingValue!.length() == 1) {
let uid = typingValue!.int(at: 0);
let user = Actor.getUserWithUid(uid)
self.subtitleView.text = Actor.getFormatter().formatTyping(withName: user.getNameModel().get())
} else {
self.subtitleView.text = Actor.getFormatter().formatTyping(withCount: typingValue!.length());
}
} else {
var membersString = Actor.getFormatter().formatGroupMembers(membersCount!.intValue())
self.subtitleView.textColor = self.appStyle.navigationSubtitleColor
if (onlineCount == nil || onlineCount!.intValue == 0) {
self.subtitleView.text = membersString;
} else {
membersString = membersString! + ", ";
let onlineString = Actor.getFormatter().formatGroupOnline(onlineCount!.intValue());
let attributedString = NSMutableAttributedString(string: (membersString! + onlineString!))
attributedString.addAttribute(NSForegroundColorAttributeName, value: self.appStyle.userOnlineNavigationColor, range: NSMakeRange(membersString!.length, onlineString!.length))
self.subtitleView.attributedText = attributedString
}
}
})
binder.bind(group.isMember, valueModel2: group.isCanWriteMessage, valueModel3: group.isCanJoin, closure: { (isMember: JavaLangBoolean?, canWriteMessage: JavaLangBoolean?, canJoin: JavaLangBoolean?) in
if canWriteMessage!.booleanValue() {
self.stickersButton.isHidden = false
self.inputOverlay.isHidden = true
} else {
if !isMember!.booleanValue() {
if canJoin!.booleanValue() {
self.inputOverlayLabel.text = AALocalized("ChatJoin")
} else {
self.inputOverlayLabel.text = AALocalized("ChatNoGroupAccess")
}
} else {
if Actor.isNotificationsEnabled(with: self.peer) {
self.inputOverlayLabel.text = AALocalized("ActionMute")
} else {
self.inputOverlayLabel.text = AALocalized("ActionUnmute")
}
}
self.stickersButton.isHidden = true
self.stopAudioRecording()
self.textInputbar.textView.text = ""
self.inputOverlay.isHidden = false
}
})
binder.bind(group.isDeleted) { (isDeleted: JavaLangBoolean?) in
if isDeleted!.booleanValue() {
self.alertUser(AALocalized("ChatDeleted")) {
self.execute(Actor.deleteChatCommand(with: self.peer), successBlock: { (r) in
self.navigateBack()
})
}
}
}
}
Actor.onConversationOpen(with: peer)
ActorSDK.sharedActor().trackPageVisible(content)
if textView.isFirstResponder == false {
textView.resignFirstResponder()
}
textView.text = Actor.loadDraft(with: peer)
}
open func onOverlayTap() {
if peer.isGroup {
let group = Actor.getGroupWithGid(peer.peerId)
if !group.isMember.get().booleanValue() {
if group.isCanJoin.get().booleanValue() {
executePromise(Actor.joinGroup(withGid: peer.peerId))
} else {
// DO NOTHING
}
} else if !group.isCanWriteMessage.get().booleanValue() {
if Actor.isNotificationsEnabled(with: peer) {
Actor.changeNotificationsEnabled(with: peer, withValue: false)
inputOverlayLabel.text = AALocalized("ActionUnmute")
} else {
Actor.changeNotificationsEnabled(with: peer, withValue: true)
inputOverlayLabel.text = AALocalized("ActionMute")
}
}
} else if peer.isPrivate {
}
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backgroundView.frame = view.bounds
titleView.frame = CGRect(x: 0, y: 4, width: (navigationView.frame.width - 0), height: 20)
subtitleView.frame = CGRect(x: 0, y: 22, width: (navigationView.frame.width - 0), height: 20)
stickersView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
//emojiKeyboar.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.removeExcedentControllers {
if navigationController!.viewControllers.count > 2 {
let firstController = navigationController!.viewControllers[0]
let currentController = navigationController!.viewControllers[navigationController!.viewControllers.count - 1]
navigationController!.setViewControllers([firstController, currentController], animated: false)
}
}
if !AADevice.isiPad {
AANavigationBadge.showBadge()
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Actor.onConversationClosed(with: peer)
ActorSDK.sharedActor().trackPageHidden(content)
if !AADevice.isiPad {
AANavigationBadge.hideBadge()
}
// Closing keyboard
self.textView.resignFirstResponder()
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Actor.saveDraft(with: peer, withDraft: textView.text)
// Releasing bindings
binder.unbindAll()
}
////////////////////////////////////////////////////////////
// MARK: - Chat avatar tap
////////////////////////////////////////////////////////////
func onAvatarTap() {
let id = Int(peer.peerId)
var controller: AAViewController!
if (peer.peerType.ordinal() == ACPeerType.private().ordinal()) {
controller = ActorSDK.sharedActor().delegate.actorControllerForUser(id)
if controller == nil {
controller = AAUserViewController(uid: id)
}
} else if (peer.peerType.ordinal() == ACPeerType.group().ordinal()) {
controller = ActorSDK.sharedActor().delegate.actorControllerForGroup(id)
if controller == nil {
controller = AAGroupViewController(gid: id)
}
} else {
return
}
if (AADevice.isiPad) {
let navigation = AANavigationController()
navigation.viewControllers = [controller]
let popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.present(from: navigationItem.rightBarButtonItem!,
permittedArrowDirections: UIPopoverArrowDirection.up,
animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
func onCallTap() {
if (self.peer.isGroup) {
execute(ActorSDK.sharedActor().messenger.doCall(withGid: self.peer.peerId))
} else if (self.peer.isPrivate) {
execute(ActorSDK.sharedActor().messenger.doCall(withUid: self.peer.peerId))
}
}
func onVideoCallTap() {
if (self.peer.isPrivate) {
execute(ActorSDK.sharedActor().messenger.doVideoCall(withUid: self.peer.peerId))
}
}
////////////////////////////////////////////////////////////
// MARK: - Text bar actions
////////////////////////////////////////////////////////////
override open func textDidUpdate(_ animated: Bool) {
super.textDidUpdate(animated)
Actor.onTyping(with: peer)
checkTextInTextView()
}
func checkTextInTextView() {
let text = self.textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
self.rightButton.isEnabled = true
//change button's
if !text.isEmpty && textMode == false {
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.removeTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
self.rebindRightButton()
self.stickersButton.isHidden = true
self.rightButton.setTitle(AALocalized("ChatSend"), for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendColor, for: UIControlState())
self.rightButton.setTitleColor(appStyle.chatSendDisabledColor, for: UIControlState.disabled)
self.rightButton.setImage(nil, for: UIControlState())
self.rightButton.layoutIfNeeded()
self.textInputbar.layoutIfNeeded()
self.textMode = true
} else if (text.isEmpty && textMode == true) {
self.rightButton.addTarget(self, action: #selector(ConversationViewController.beginRecord(_:event:)), for: UIControlEvents.touchDown)
self.rightButton.addTarget(self, action: #selector(ConversationViewController.mayCancelRecord(_:event:)), for: UIControlEvents.touchDragInside.union(UIControlEvents.touchDragOutside))
self.rightButton.addTarget(self, action: #selector(ConversationViewController.finishRecord(_:event:)), for: UIControlEvents.touchUpInside.union(UIControlEvents.touchCancel).union(UIControlEvents.touchUpOutside))
self.stickersButton.isHidden = false
self.rightButton.tintColor = appStyle.chatAttachColor
self.rightButton.setImage(UIImage.bundled("aa_micbutton"), for: UIControlState())
self.rightButton.setTitle("", for: UIControlState())
self.rightButton.isEnabled = true
self.rightButton.layoutIfNeeded()
self.textInputbar.layoutIfNeeded()
self.textMode = false
}
}
////////////////////////////////////////////////////////////
// MARK: - Right/Left button pressed
////////////////////////////////////////////////////////////
override open func didPressRightButton(_ sender: Any!) {
if !self.textView.text.isEmpty {
Actor.sendMessage(withMentionsDetect: peer, withText: textView.text)
super.didPressRightButton(sender)
}
}
override open func didPressLeftButton(_ sender: Any!) {
super.didPressLeftButton(sender)
self.textInputbar.textView.resignFirstResponder()
self.rightButton.layoutIfNeeded()
if !ActorSDK.sharedActor().delegate.actorConversationCustomAttachMenu(self) {
let actionSheet = AAConvActionSheet()
actionSheet.addCustomButton("SendDocument")
actionSheet.addCustomButton("ShareLocation")
actionSheet.addCustomButton("ShareContact")
actionSheet.delegate = self
actionSheet.presentInController(self)
}
}
////////////////////////////////////////////////////////////
// MARK: - Completition
////////////////////////////////////////////////////////////
override open func didChangeAutoCompletionPrefix(_ prefix: String!, andWord word: String!) {
if self.peer.peerType.ordinal() == ACPeerType.group().ordinal() {
if prefix == "@" {
let oldCount = filteredMembers.count
filteredMembers.removeAll(keepingCapacity: true)
let res = Actor.findMentions(withGid: self.peer.peerId, withQuery: word)!
for index in 0..<res.size() {
filteredMembers.append(res.getWith(index) as! ACMentionFilterResult)
}
if oldCount == filteredMembers.count {
self.autoCompletionView.reloadData()
}
dispatchOnUi { () -> Void in
self.showAutoCompletionView(self.filteredMembers.count > 0)
}
return
}
}
dispatchOnUi { () -> Void in
self.showAutoCompletionView(false)
}
}
////////////////////////////////////////////////////////////
// MARK: - TableView for completition
////////////////////////////////////////////////////////////
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredMembers.count
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let res = AAAutoCompleteCell(style: UITableViewCellStyle.default, reuseIdentifier: "user_name")
res.bindData(filteredMembers[(indexPath as NSIndexPath).row], highlightWord: foundWord)
return res
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = filteredMembers[(indexPath as NSIndexPath).row]
var postfix = " "
if foundPrefixRange.location == 0 {
postfix = ": "
}
acceptAutoCompletion(with: user.mentionString + postfix, keepPrefix: !user.isNickname)
}
override open func heightForAutoCompletionView() -> CGFloat {
let cellHeight: CGFloat = 44.0;
return cellHeight * CGFloat(filteredMembers.count)
}
override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsets.zero
}
////////////////////////////////////////////////////////////
// MARK: - Picker
////////////////////////////////////////////////////////////
open func actionSheetPickedImages(_ images:[(Data,Bool)]) {
for (i,j) in images {
Actor.sendUIImage(i, peer: peer, animated:j)
}
}
open func actionSheetPickCamera() {
pickImage(.camera)
}
open func actionSheetPickGallery() {
pickImage(.photoLibrary)
}
open func actionSheetCustomButton(_ index: Int) {
if index == 0 {
pickDocument()
} else if index == 1 {
pickLocation()
} else if index == 2 {
pickContact()
}
}
open func pickContact() {
let pickerController = ABPeoplePickerNavigationController()
pickerController.peoplePickerDelegate = self
self.present(pickerController, animated: true, completion: nil)
}
open func pickLocation() {
let pickerController = AALocationPickerController()
pickerController.delegate = self
self.present(AANavigationController(rootViewController:pickerController), animated: true, completion: nil)
}
open func pickDocument() {
let documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll as [String], in: UIDocumentPickerMode.import)
documentPicker.view.backgroundColor = UIColor.clear
documentPicker.delegate = self
self.present(documentPicker, animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Document picking
////////////////////////////////////////////////////////////
open func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
self.present(documentPicker, animated: true, completion: nil)
}
open func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
// Loading path and file name
let path = url.path
let fileName = url.lastPathComponent
// Check if file valid or directory
var isDir : ObjCBool = false
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
// Not exists
return
}
// Destination file
let descriptor = "/tmp/\(UUID().uuidString)"
let destPath = CocoaFiles.pathFromDescriptor(descriptor)
if isDir.boolValue {
// Zipping contents and sending
execute(AATools.zipDirectoryCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/zip", withDescriptor: descriptor)
}
} else {
// Sending file itself
execute(AATools.copyFileCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocument(with: self.peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor)
}
}
}
////////////////////////////////////////////////////////////
// MARK: - Image picking
////////////////////////////////////////////////////////////
func pickImage(_ source: UIImagePickerControllerSourceType) {
if(source == .camera && (AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.undetermined || AVAudioSession.sharedInstance().recordPermission() == AVAudioSessionRecordPermission.denied)){
AVAudioSession.sharedInstance().requestRecordPermission({_ in (Bool).self})
}
let pickerController = AAImagePickerController()
pickerController.sourceType = source
pickerController.mediaTypes = [kUTTypeImage as String,kUTTypeMovie as String]
pickerController.delegate = self
self.present(pickerController, animated: true, completion: nil)
}
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
picker.dismiss(animated: true, completion: nil)
let imageData = UIImageJPEGRepresentation(image, 0.8)
Actor.sendUIImage(imageData!, peer: peer, animated:false)
}
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let imageData = UIImageJPEGRepresentation(image, 0.8)
//TODO: Need implement assert fetching here to get images
Actor.sendUIImage(imageData!, peer: peer, animated:false)
} else {
Actor.sendVideo(info[UIImagePickerControllerMediaURL] as! URL, peer: peer)
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Location picking
////////////////////////////////////////////////////////////
open func locationPickerDidCancelled(_ controller: AALocationPickerController) {
controller.dismiss(animated: true, completion: nil)
}
open func locationPickerDidPicked(_ controller: AALocationPickerController, latitude: Double, longitude: Double) {
Actor.sendLocation(with: self.peer, withLongitude: JavaLangDouble(value: longitude), withLatitude: JavaLangDouble(value: latitude), withStreet: nil, withPlace: nil)
controller.dismiss(animated: true, completion: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Contact picking
////////////////////////////////////////////////////////////
open func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
// Dismissing picker
peoplePicker.dismiss(animated: true, completion: nil)
// Names
let name = ABRecordCopyCompositeName(person)?.takeRetainedValue() as String?
// Avatar
var jAvatarImage: String? = nil
let hasAvatarImage = ABPersonHasImageData(person)
if (hasAvatarImage) {
let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue()
let image = UIImage(data: imgData as Data)?.resizeSquare(90, maxH: 90)
if (image != nil) {
let thumbData = UIImageJPEGRepresentation(image!, 0.55)
jAvatarImage = thumbData?.base64EncodedString(options: NSData.Base64EncodingOptions())
}
}
// Phones
let jPhones = JavaUtilArrayList()
let phoneNumbers: ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
let phoneCount = ABMultiValueGetCount(phoneNumbers)
for i in 0 ..< phoneCount {
let phone = (ABMultiValueCopyValueAtIndex(phoneNumbers, i).takeRetainedValue() as! String).trim()
jPhones?.add(withId: phone)
}
// Email
let jEmails = JavaUtilArrayList()
let emails: ABMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty).takeRetainedValue()
let emailsCount = ABMultiValueGetCount(emails)
for i in 0 ..< emailsCount {
let email = (ABMultiValueCopyValueAtIndex(emails, i).takeRetainedValue() as! String).trim()
if (email.length > 0) {
jEmails?.add(withId: email)
}
}
// Sending
Actor.sendContact(with: self.peer, withName: name!, withPhones: jPhones!, withEmails: jEmails!, withPhoto: jAvatarImage)
}
////////////////////////////////////////////////////////////
// MARK: -
// MARK: Audio recording statments + send
////////////////////////////////////////////////////////////
func onAudioRecordingStarted() {
print("onAudioRecordingStarted\n")
stopAudioRecording()
// stop voice player when start recording
if (self.voicePlayer?.playbackPosition() != 0.0) {
self.voicePlayer?.audioPlayerStopAndFinish()
}
audioRecorder.delegate = self
audioRecorder.start()
}
func onAudioRecordingFinished() {
print("onAudioRecordingFinished\n")
audioRecorder.finish { (path: String?, duration: TimeInterval) -> Void in
if (nil == path) {
print("onAudioRecordingFinished: empty path")
return
}
NSLog("onAudioRecordingFinished: %@ [%lfs]", path!, duration)
let range = path!.range(of: "/tmp", options: NSString.CompareOptions(), range: nil, locale: nil)
let descriptor = path!.substring(from: range!.lowerBound)
NSLog("Audio Recording file: \(descriptor)")
Actor.sendAudio(with: self.peer, withName: NSString.localizedStringWithFormat("%@.ogg", UUID().uuidString) as String,
withDuration: jint(duration*1000), withDescriptor: descriptor)
}
audioRecorder.cancel()
}
open func audioRecorderDidStartRecording() {
self.voiceRecorderView.recordingStarted()
}
func onAudioRecordingCancelled() {
stopAudioRecording()
}
func stopAudioRecording() {
if (audioRecorder != nil) {
audioRecorder.delegate = nil
audioRecorder.cancel()
}
}
func beginRecord(_ button:UIButton,event:UIEvent) {
self.voiceRecorderView.startAnimation()
self.voiceRecorderView.isHidden = false
self.stickersButton.isHidden = true
let touches : Set<UITouch> = event.touches(for: button)!
let touch = touches.first!
let location = touch.location(in: button)
self.voiceRecorderView.trackTouchPoint = location
self.voiceRecorderView.firstTouchPoint = location
self.onAudioRecordingStarted()
}
func mayCancelRecord(_ button:UIButton,event:UIEvent) {
let touches : Set<UITouch> = event.touches(for: button)!
let touch = touches.first!
let currentLocation = touch.location(in: button)
if (currentLocation.x < self.rightButton.frame.origin.x) {
if (self.voiceRecorderView.trackTouchPoint.x > currentLocation.x) {
self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: false)
} else {
self.voiceRecorderView.updateLocation(currentLocation.x - self.voiceRecorderView.trackTouchPoint.x,slideToRight: true)
}
}
self.voiceRecorderView.trackTouchPoint = currentLocation
if ((self.voiceRecorderView.firstTouchPoint.x - self.voiceRecorderView.trackTouchPoint.x) > 120) {
//cancel
self.voiceRecorderView.isHidden = true
self.stickersButton.isHidden = false
self.stopAudioRecording()
self.voiceRecorderView.recordingStoped()
button.cancelTracking(with: event)
closeRecorderAnimation()
}
}
func closeRecorderAnimation() {
let leftButtonFrame = self.leftButton.frame
leftButton.frame.origin.x = -100
let textViewFrame = self.textView.frame
textView.frame.origin.x = textView.frame.origin.x + 500
let stickerViewFrame = self.stickersButton.frame
stickersButton.frame.origin.x = self.stickersButton.frame.origin.x + 500
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.leftButton.frame = leftButtonFrame
self.textView.frame = textViewFrame
self.stickersButton.frame = stickerViewFrame
}, completion: { (complite) -> Void in
// animation complite
})
}
func finishRecord(_ button:UIButton,event:UIEvent) {
closeRecorderAnimation()
self.voiceRecorderView.isHidden = true
self.stickersButton.isHidden = false
self.onAudioRecordingFinished()
self.voiceRecorderView.recordingStoped()
}
////////////////////////////////////////////////////////////
// MARK: - Stickers actions
////////////////////////////////////////////////////////////
open func updateStickersStateOnCloseKeyboard() {
self.stickersOpen = false
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.textInputbar.textView.inputView = nil
}
open func changeKeyboard() {
if self.stickersOpen == false {
//self.stickersView.loadStickers()
self.textInputbar.textView.inputView = self.stickersView
//self.textInputbar.textView.inputView = self.emojiKeyboar
self.textInputbar.textView.inputView?.isOpaque = false
self.textInputbar.textView.inputView?.backgroundColor = UIColor.clear
self.textInputbar.textView.refreshFirstResponder()
self.textInputbar.textView.refreshInputViews()
self.textInputbar.textView.becomeFirstResponder()
self.stickersButton.setImage(UIImage.bundled("keyboard_button"), for: UIControlState())
self.stickersOpen = true
} else {
self.textInputbar.textView.inputView = nil
self.textInputbar.textView.refreshFirstResponder()
self.textInputbar.textView.refreshInputViews()
self.textInputbar.textView.becomeFirstResponder()
self.stickersButton.setImage(UIImage.bundled("sticker_button"), for: UIControlState())
self.stickersOpen = false
}
self.textInputbar.layoutIfNeeded()
self.view.layoutIfNeeded()
}
open func stickerDidSelected(_ keyboard: AAStickersKeyboard, sticker: ACSticker) {
Actor.sendSticker(with: self.peer, with: sticker)
}
/*
public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage{
switch category {
case .recent:
return UIImage.bundled("ic_smiles_recent")!
case .face:
return UIImage.bundled("ic_smiles_smile")!
case .car:
return UIImage.bundled("ic_smiles_car")!
case .bell:
return UIImage.bundled("ic_smiles_bell")!
case .flower:
return UIImage.bundled("ic_smiles_flower")!
case .characters:
return UIImage.bundled("ic_smiles_grid")!
}
}
public func emojiKeyboardView(_ emojiKeyboardView: AGEmojiKeyboardView!, imageForNonSelectedCategory category: AGEmojiKeyboardViewCategoryImage) -> UIImage!{
switch category {
case .recent:
return UIImage.bundled("ic_smiles_recent")!
case .face:
return UIImage.bundled("ic_smiles_smile")!
case .car:
return UIImage.bundled("ic_smiles_car")!
case .bell:
return UIImage.bundled("ic_smiles_bell")!
case .flower:
return UIImage.bundled("ic_smiles_flower")!
case .characters:
return UIImage.bundled("ic_smiles_grid")!
}
}
public func backSpaceButtonImage(for emojiKeyboardView: AGEmojiKeyboardView!) -> UIImage!{
return UIImage.bundled("ic_smiles_backspace")!
}
public func emojiKeyBoardView(_ emojiKeyBoardView: AGEmojiKeyboardView!, didUseEmoji emoji: String!){
self.textView.text = self.textView.text.appending(emoji)
}
public func emojiKeyBoardViewDidPressBackSpace(_ emojiKeyBoardView: AGEmojiKeyboardView!){
self.textView.deleteBackward()
}
*/
}
class AABarAvatarView : AAAvatarView {
// override init(frameSize: Int, type: AAAvatarType) {
// super.init(frameSize: frameSize, type: type)
// }
//
// required init(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
override var alignmentRectInsets : UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)
}
}
class AACallButton: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var alignmentRectInsets : UIEdgeInsets {
return UIEdgeInsets(top: 0, left: -2, bottom: 0, right: 0)
}
}
| agpl-3.0 |
AndreasRicci/firebase-continue | samples/ios/Continote/Continote/MyNotesTableViewCell.swift | 2 | 1859 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/**
The TableView within MyNotesViewController is filled with these cells (one per Note).
*/
class MyNotesTableViewCell: UITableViewCell {
// The key from the Firebase Realtime Database for the Note this cell represents.
// This is passed to the EditNoteViewController.
var noteKey: String?
// The Note this cell represents.
var note: Note? {
didSet {
// Populate this cell with the values from the Note.
titleLabel.setText(to: note?.title,
withPlaceholder: "No Title",
using: Constants.Theme.LabelKind.titleText.getFont())
contentLabel.setText(to: note?.content,
withPlaceholder: "No Content",
using: Constants.Theme.LabelKind.normalText.getFont())
}
}
// UI outlets
@IBOutlet var titleLabel: UILabel!
@IBOutlet var contentLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Style all labels.
titleLabel.applyAppTheme(for: .titleText)
contentLabel.applyAppTheme(for: .normalText)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| apache-2.0 |
pavelpark/RoundMedia | roundMedia/roundMedia/SignInViewController.swift | 1 | 3704 | //
// ViewController.swift
// roundMedia
//
// Created by Pavel Parkhomey on 7/11/17.
// Copyright © 2017 Pavel Parkhomey. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import SwiftKeychainWrapper
class SignInViewController: UIViewController {
@IBOutlet weak var emailFeild: CleanText!
@IBOutlet weak var passwordFeild: CleanText!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: KEY_UID){
print("------: ID found in keychain")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
@IBAction func facebookButtonTapped(_ sender: AnyObject) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil {
print("------: Unable to authenticate with Facebook - \(String(describing: error))")
} else if result?.isCancelled == true {
print("------: User cancelled Facebook authentication")
} else {
print("------: Successfully authenticated with Facebook")
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.firebaseAuth(credential)
}
}
}
func firebaseAuth(_ credential: AuthCredential) {
Auth.auth().signIn(with: credential) { (user, error) in
if error != nil {
print("------: Unable to authenticate with Firebase")
} else {
print("------: Susseccfully authenticated with Firebase")
if user != nil {
let userData = ["provider": credential.provider]
self.completeWithSignIn(id: (user?.uid)!, userData: userData)
}
}
}
}
@IBAction func emailSignInTapped(_ sender: AnyObject) {
if let email = emailFeild.text, let password = passwordFeild.text {
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
print("-----: Email user authenticated with Firebase")
let userData = ["provider": user?.providerID]
self.completeWithSignIn(id: (user?.uid)!, userData: userData as! Dictionary<String, String>)
} else {
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print("------: Unable to authenticate with Firebase using email")
} else {
print("------: Successfully authenticated with Firebase")
if let user = user {
let userData = ["provider": user.providerID]
self.completeWithSignIn(id: user.uid, userData: userData)
}
}
})
}
})
}
}
func completeWithSignIn(id: String, userData: Dictionary<String, String>) {
DataService.ds.createFirbaseDBUser(uid: id, userData: userData)
let keychainResult = KeychainWrapper.standard.set(id , forKey: "key uid")
print("------: Data saved to keychain \(keychainResult)")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/10044-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 218 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where B:a{var b{class a{deinit{let a=c | mit |
XiaoChenYung/GitSwift | DomainTests/DomainTests.swift | 1 | 959 | //
// DomainTests.swift
// DomainTests
//
// Created by 杨晓晨 on 2017/7/29.
// Copyright © 2017年 tm. All rights reserved.
//
import XCTest
@testable import Domain
class DomainTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/21693-llvm-errs.swift | 11 | 221 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct g<T where h: e {
var d {
(
class A {
var : e
| mit |
johnno1962e/swift-corelibs-foundation | TestFoundation/TestNSData.swift | 2 | 63748 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSData: XCTestCase {
// MARK: -
// String of course has its own way to get data, but this way tests our own data struct
func dataFrom(_ string : String) -> Data {
// Create a Data out of those bytes
return string.utf8CString.withUnsafeBufferPointer { (ptr) in
ptr.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: ptr.count) {
// Subtract 1 so we don't get the null terminator byte. This matches NSString behavior.
return Data(bytes: $0, count: ptr.count - 1)
}
}
}
static var allTests: [(String, (TestNSData) -> () throws -> Void)] {
return [
("testBasicConstruction", testBasicConstruction),
("test_base64Data_medium", test_base64Data_medium),
("test_base64Data_small", test_base64Data_small),
("test_openingNonExistentFile", test_openingNonExistentFile),
("test_contentsOfFile", test_contentsOfFile),
("test_contentsOfZeroFile", test_contentsOfZeroFile),
("test_basicReadWrite", test_basicReadWrite),
("test_bufferSizeCalculation", test_bufferSizeCalculation),
// ("test_dataHash", test_dataHash), Disabled due to lack of brdiging in swift runtime -- infinite loops
("test_genericBuffers", test_genericBuffers),
// ("test_writeFailure", test_writeFailure), segfaults
("testBasicConstruction", testBasicConstruction),
("testBridgingDefault", testBridgingDefault),
("testBridgingMutable", testBridgingMutable),
("testCopyBytes_oversized", testCopyBytes_oversized),
("testCopyBytes_ranges", testCopyBytes_ranges),
("testCopyBytes_undersized", testCopyBytes_undersized),
("testCopyBytes", testCopyBytes),
("testCustomDeallocator", testCustomDeallocator),
("testDataInSet", testDataInSet),
("testEquality", testEquality),
("testGenericAlgorithms", testGenericAlgorithms),
("testInitializationWithArray", testInitializationWithArray),
("testInsertData", testInsertData),
("testLoops", testLoops),
("testMutableData", testMutableData),
("testRange", testRange),
("testReplaceSubrange", testReplaceSubrange),
("testReplaceSubrange2", testReplaceSubrange2),
("testReplaceSubrange3", testReplaceSubrange3),
("testReplaceSubrange4", testReplaceSubrange4),
("testReplaceSubrange5", testReplaceSubrange5),
("test_description", test_description),
("test_emptyDescription", test_emptyDescription),
("test_longDescription", test_longDescription),
("test_debugDescription", test_debugDescription),
("test_longDebugDescription", test_longDebugDescription),
("test_limitDebugDescription", test_limitDebugDescription),
("test_edgeDebugDescription", test_edgeDebugDescription),
("test_writeToURLOptions", test_writeToURLOptions),
("test_edgeNoCopyDescription", test_edgeNoCopyDescription),
("test_initializeWithBase64EncodedDataGetsDecodedData", test_initializeWithBase64EncodedDataGetsDecodedData),
("test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil", test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil),
("test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter", test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter),
("test_base64EncodedDataGetsEncodedText", test_base64EncodedDataGetsEncodedText),
("test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn", test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn),
("test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed", test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed),
("test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth", test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth),
("test_base64EncodedStringGetsEncodedText", test_base64EncodedStringGetsEncodedText),
("test_initializeWithBase64EncodedStringGetsDecodedData", test_initializeWithBase64EncodedStringGetsDecodedData),
("test_base64DecodeWithPadding1", test_base64DecodeWithPadding1),
("test_base64DecodeWithPadding2", test_base64DecodeWithPadding2),
("test_rangeOfData",test_rangeOfData),
("test_initMutableDataWithLength", test_initMutableDataWithLength),
("test_replaceBytes", test_replaceBytes),
("test_replaceBytesWithNil", test_replaceBytesWithNil),
("test_initDataWithCapacity", test_initDataWithCapacity),
("test_initDataWithCount", test_initDataWithCount),
("test_emptyStringToData", test_emptyStringToData),
("test_repeatingValueInitialization", test_repeatingValueInitialization),
("test_sliceAppending", test_sliceAppending),
("test_replaceSubrange", test_replaceSubrange),
("test_sliceWithUnsafeBytes", test_sliceWithUnsafeBytes),
("test_sliceIteration", test_sliceIteration),
]
}
func test_writeToURLOptions() {
let saveData = try! Data(contentsOf: Bundle.main.url(forResource: "Test", withExtension: "plist")!)
let savePath = URL(fileURLWithPath: "/var/tmp/Test.plist")
do {
try saveData.write(to: savePath, options: .atomic)
let fileManager = FileManager.default
XCTAssertTrue(fileManager.fileExists(atPath: savePath.path))
try! fileManager.removeItem(atPath: savePath.path)
} catch _ {
XCTFail()
}
}
func test_emptyDescription() {
let expected = "<>"
let bytes: [UInt8] = []
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(expected, data.description)
}
func test_description() {
let expected = "<ff4c3e00 55>"
let bytes: [UInt8] = [0xff, 0x4c, 0x3e, 0x00, 0x55]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.description, expected)
}
func test_longDescription() {
// taken directly from Foundation
let expected = "<ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8ff6e 4482d8ff 6e4482d8 ff6e4482 d8ff6e44 82d8>"
let bytes: [UInt8] = [0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, 0xff, 0x6e, 0x44, 0x82, 0xd8, ]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(expected, data.description)
}
func test_debugDescription() {
let expected = "<ff4c3e00 55>"
let bytes: [UInt8] = [0xff, 0x4c, 0x3e, 0x00, 0x55]
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_limitDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff>"
let bytes = [UInt8](repeating: 0xff, count: 1024)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_longDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff>"
let bytes = [UInt8](repeating: 0xff, count: 100_000)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_edgeDebugDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ff>"
let bytes = [UInt8](repeating: 0xff, count: 1025)
let data = NSData(bytes: bytes, length: bytes.count)
XCTAssertEqual(data.debugDescription, expected)
}
func test_edgeNoCopyDescription() {
let expected = "<ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ... ffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ff>"
let bytes = [UInt8](repeating: 0xff, count: 1025)
let data = NSData(bytesNoCopy: UnsafeMutablePointer(mutating: bytes), length: bytes.count, freeWhenDone: false)
XCTAssertEqual(data.debugDescription, expected)
XCTAssertEqual(data.bytes, bytes)
}
func test_initializeWithBase64EncodedDataGetsDecodedData() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHByaW11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
guard let decodedData = Data(base64Encoded: encodedData, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
XCTAssertTrue(decodedData == plainText.data(using: .utf8)!)
}
func test_initializeWithBase64EncodedDataWithNonBase64CharacterIsNil() {
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHBya$W11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
let decodedData = NSData(base64Encoded: encodedData, options: [])
XCTAssertNil(decodedData)
}
func test_initializeWithBase64EncodedDataWithNonBase64CharacterWithOptionToAllowItSkipsCharacter() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHBya$W11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let encodedData = encodedText.data(using: .utf8) else {
XCTFail("Could not get UTF-8 data")
return
}
guard let decodedData = Data(base64Encoded: encodedData, options: [.ignoreUnknownCharacters]) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
XCTAssertTrue(decodedData == plainText.data(using: .utf8)!)
}
func test_initializeWithBase64EncodedStringGetsDecodedData() {
let plainText = "ARMA virumque cano, Troiae qui primus ab oris\nItaliam, fato profugus, Laviniaque venit"
let encodedText = "QVJNQSB2aXJ1bXF1ZSBjYW5vLCBUcm9pYWUgcXVpIHByaW11cyBhYiBvcmlzCkl0YWxpYW0sIGZhdG8gcHJvZnVndXMsIExhdmluaWFxdWUgdmVuaXQ="
guard let decodedData = Data(base64Encoded: encodedText, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
guard let decodedText = String(data: decodedData, encoding: .utf8) else {
XCTFail("Could not convert decoded data to a UTF-8 String")
return
}
XCTAssertEqual(decodedText, plainText)
}
func test_base64EncodedDataGetsEncodedText() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1aXQgYEFjaGF0ZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVuYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData()
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertLineFeedsContainsLineFeed() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1\naXQgYEFjaGF0ZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVu\nYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength64Characters, .endLineWithLineFeed])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertCarriageReturnContainsCarriageReturn() {
let plainText = "Constitit, et lacrimans, `Quis iam locus’ inquit `Achate,\nquae regio in terris nostri non plena laboris?`"
let encodedText = "Q29uc3RpdGl0LCBldCBsYWNyaW1hbnMsIGBRdWlzIGlhbSBsb2N1c+KAmSBpbnF1aXQgYEFjaGF0\rZSwKcXVhZSByZWdpbyBpbiB0ZXJyaXMgbm9zdHJpIG5vbiBwbGVuYSBsYWJvcmlzP2A="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength76Characters, .endLineWithCarriageReturn])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedDataWithOptionToInsertCarriageReturnAndLineFeedContainsBoth() {
let plainText = "Revocate animos, maestumque timorem mittite: forsan et haec olim meminisse iuvabit."
let encodedText = "UmV2b2NhdGUgYW5pbW9zLCBtYWVzdHVtcXVlIHRpbW9yZW0gbWl0dGl0ZTogZm9yc2FuIGV0IGhh\r\nZWMgb2xpbSBtZW1pbmlzc2UgaXV2YWJpdC4="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedData = data.base64EncodedData(options: [.lineLength76Characters, .endLineWithCarriageReturn, .endLineWithLineFeed])
guard let encodedTextResult = String(data: encodedData, encoding: String.Encoding.ascii) else {
XCTFail("Could not convert encoded data to an ASCII String")
return
}
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64EncodedStringGetsEncodedText() {
let plainText = "Revocate animos, maestumque timorem mittite: forsan et haec olim meminisse iuvabit."
let encodedText = "UmV2b2NhdGUgYW5pbW9zLCBtYWVzdHVtcXVlIHRpbW9yZW0gbWl0dGl0ZTogZm9yc2FuIGV0IGhhZWMgb2xpbSBtZW1pbmlzc2UgaXV2YWJpdC4="
guard let data = plainText.data(using: String.Encoding.utf8) else {
XCTFail("Could not encode UTF-8 string")
return
}
let encodedTextResult = data.base64EncodedString()
XCTAssertEqual(encodedTextResult, encodedText)
}
func test_base64DecodeWithPadding1() {
let encodedPadding1 = "AoR="
let dataPadding1Bytes : [UInt8] = [0x02,0x84]
let dataPadding1 = NSData(bytes: dataPadding1Bytes, length: dataPadding1Bytes.count)
guard let decodedPadding1 = Data(base64Encoded:encodedPadding1, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
XCTAssert(dataPadding1.isEqual(to: decodedPadding1))
}
func test_base64DecodeWithPadding2() {
let encodedPadding2 = "Ao=="
let dataPadding2Bytes : [UInt8] = [0x02]
let dataPadding2 = NSData(bytes: dataPadding2Bytes, length: dataPadding2Bytes.count)
guard let decodedPadding2 = Data(base64Encoded:encodedPadding2, options: []) else {
XCTFail("Could not Base-64 decode data")
return
}
XCTAssert(dataPadding2.isEqual(to: decodedPadding2))
}
func test_rangeOfData() {
let baseData : [UInt8] = [0x00,0x01,0x02,0x03,0x04]
let base = NSData(bytes: baseData, length: baseData.count)
let baseFullRange = NSRange(location : 0,length : baseData.count)
let noPrefixRange = NSRange(location : 2,length : baseData.count-2)
let noSuffixRange = NSRange(location : 0,length : baseData.count-2)
let notFoundRange = NSMakeRange(NSNotFound, 0)
let prefixData : [UInt8] = [0x00,0x01]
let prefix = Data(bytes: prefixData, count: prefixData.count)
let prefixRange = NSMakeRange(0, prefixData.count)
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.anchored], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: baseFullRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: noPrefixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: noPrefixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [], in: noSuffixRange),prefixRange))
XCTAssert(NSEqualRanges(base.range(of: prefix, options: [.backwards], in: noSuffixRange),prefixRange))
let suffixData : [UInt8] = [0x03,0x04]
let suffix = Data(bytes: suffixData, count: suffixData.count)
let suffixRange = NSMakeRange(3, suffixData.count)
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards,.anchored], in: baseFullRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: noPrefixRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: noPrefixRange),suffixRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [], in: noSuffixRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: suffix, options: [.backwards], in: noSuffixRange),notFoundRange))
let sliceData : [UInt8] = [0x02,0x03]
let slice = Data(bytes: sliceData, count: sliceData.count)
let sliceRange = NSMakeRange(2, sliceData.count)
XCTAssert(NSEqualRanges(base.range(of: slice, options: [], in: baseFullRange),sliceRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.backwards], in: baseFullRange),sliceRange))
XCTAssert(NSEqualRanges(base.range(of: slice, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
let empty = Data()
XCTAssert(NSEqualRanges(base.range(of: empty, options: [], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.anchored], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.backwards], in: baseFullRange),notFoundRange))
XCTAssert(NSEqualRanges(base.range(of: empty, options: [.backwards,.anchored], in: baseFullRange),notFoundRange))
}
func test_initMutableDataWithLength() {
let mData = NSMutableData(length: 30)
XCTAssertNotNil(mData)
XCTAssertEqual(mData!.length, 30)
}
func test_replaceBytes() {
var data = Data(bytes: [0, 0, 0, 0, 0])
let newData = Data(bytes: [1, 2, 3, 4, 5])
// test replaceSubrange(_, with:)
XCTAssertFalse(data == newData)
data.replaceSubrange(data.startIndex..<data.endIndex, with: newData)
XCTAssertTrue(data == newData)
// subscript(index:) uses replaceBytes so use it to test edge conditions
data[0] = 0
data[4] = 0
XCTAssertTrue(data == Data(bytes: [0, 2, 3, 4, 0]))
// test NSMutableData.replaceBytes(in:withBytes:length:) directly
func makeData(_ data: [UInt8]) -> NSData {
return NSData(bytes: data, length: data.count)
}
guard let mData = NSMutableData(length: 5) else {
XCTFail("Cant create NSMutableData")
return
}
let replacement = makeData([8, 9, 10])
mData.replaceBytes(in: NSMakeRange(1, 3), withBytes: replacement.bytes,
length: 3)
let expected = makeData([0, 8, 9, 10, 0])
XCTAssertEqual(mData, expected)
}
func test_replaceBytesWithNil() {
func makeData(_ data: [UInt8]) -> NSMutableData {
return NSMutableData(bytes: data, length: data.count)
}
let mData = makeData([1, 2, 3, 4, 5])
mData.replaceBytes(in: NSMakeRange(1, 3), withBytes: nil, length: 0)
let expected = makeData([1, 5])
XCTAssertEqual(mData, expected)
}
func test_initDataWithCapacity() {
let data = Data(capacity: 123)
XCTAssertEqual(data.count, 0)
}
func test_initDataWithCount() {
let dataSize = 1024
let data = Data(count: dataSize)
XCTAssertEqual(data.count, dataSize)
if let index = (data.index { $0 != 0 }) {
XCTFail("Byte at index: \(index) is not zero: \(data[index])")
return
}
}
func test_emptyStringToData() {
let data = "".data(using: .utf8)!
XCTAssertEqual(0, data.count, "data from empty string is empty")
}
}
// Tests from Swift SDK Overlay
extension TestNSData {
func testBasicConstruction() throws {
// Make sure that we were able to create some data
let hello = dataFrom("hello")
let helloLength = hello.count
XCTAssertEqual(hello[0], 0x68, "Unexpected first byte")
let world = dataFrom(" world")
var helloWorld = hello
world.withUnsafeBytes {
helloWorld.append($0, count: world.count)
}
XCTAssertEqual(hello[0], 0x68, "First byte should not have changed")
XCTAssertEqual(hello.count, helloLength, "Length of first data should not have changed")
XCTAssertEqual(helloWorld.count, hello.count + world.count, "The total length should include both buffers")
}
func testInitializationWithArray() {
let data = Data(bytes: [1, 2, 3])
XCTAssertEqual(3, data.count)
let data2 = Data(bytes: [1, 2, 3].filter { $0 >= 2 })
XCTAssertEqual(2, data2.count)
let data3 = Data(bytes: [1, 2, 3, 4, 5][1..<3])
XCTAssertEqual(2, data3.count)
}
func testMutableData() {
let hello = dataFrom("hello")
let helloLength = hello.count
XCTAssertEqual(hello[0], 0x68, "Unexpected first byte")
// Double the length
var mutatingHello = hello
mutatingHello.count *= 2
XCTAssertEqual(hello.count, helloLength, "The length of the initial data should not have changed")
XCTAssertEqual(mutatingHello.count, helloLength * 2, "The length should have changed")
// Get the underlying data for hello2
mutatingHello.withUnsafeMutableBytes { (bytes : UnsafeMutablePointer<UInt8>) in
XCTAssertEqual(bytes.pointee, 0x68, "First byte should be 0x68")
// Mutate it
bytes.pointee = 0x67
XCTAssertEqual(bytes.pointee, 0x67, "First byte should be 0x67")
XCTAssertEqual(mutatingHello[0], 0x67, "First byte accessed via other method should still be 0x67")
// Verify that the first data is still correct
XCTAssertEqual(hello[0], 0x68, "The first byte should still be 0x68")
}
}
func testBridgingDefault() {
let hello = dataFrom("hello")
// Convert from struct Data to NSData
if let s = NSString(data: hello, encoding: String.Encoding.utf8.rawValue) {
XCTAssertTrue(s.isEqual(to: "hello"), "The strings should be equal")
}
// Convert from NSData to struct Data
let goodbye = dataFrom("goodbye")
if let resultingData = NSString(string: "goodbye").data(using: String.Encoding.utf8.rawValue) {
XCTAssertEqual(resultingData[0], goodbye[0], "First byte should be equal")
}
}
func testBridgingMutable() {
// Create a mutable data
var helloWorld = dataFrom("hello")
helloWorld.append(dataFrom("world"))
// Convert from struct Data to NSData
if let s = NSString(data: helloWorld, encoding: String.Encoding.utf8.rawValue) {
XCTAssertTrue(s.isEqual(to: "helloworld"), "The strings should be equal")
}
}
func testEquality() {
let d1 = dataFrom("hello")
let d2 = dataFrom("hello")
// Use == explicitly here to make sure we're calling the right methods
XCTAssertTrue(d1 == d2, "Data should be equal")
}
func testDataInSet() {
let d1 = dataFrom("Hello")
let d2 = dataFrom("Hello")
let d3 = dataFrom("World")
var s = Set<Data>()
s.insert(d1)
s.insert(d2)
s.insert(d3)
XCTAssertEqual(s.count, 2, "Expected only two entries in the Set")
}
func testReplaceSubrange() {
var hello = dataFrom("Hello")
let world = dataFrom("World")
hello[0] = world[0]
XCTAssertEqual(hello[0], world[0])
var goodbyeWorld = dataFrom("Hello World")
let goodbye = dataFrom("Goodbye")
let expected = dataFrom("Goodbye World")
goodbyeWorld.replaceSubrange(0..<5, with: goodbye)
XCTAssertEqual(goodbyeWorld, expected)
}
func testReplaceSubrange2() {
let hello = dataFrom("Hello")
let world = dataFrom(" World")
let goodbye = dataFrom("Goodbye")
let expected = dataFrom("Goodbye World")
var mutateMe = hello
mutateMe.append(world)
if let found = mutateMe.range(of: hello) {
mutateMe.replaceSubrange(found, with: goodbye)
}
XCTAssertEqual(mutateMe, expected)
}
func testReplaceSubrange3() {
// The expected result
let expectedBytes : [UInt8] = [1, 2, 9, 10, 11, 12, 13]
let expected = expectedBytes.withUnsafeBufferPointer {
return Data(buffer: $0)
}
// The data we'll mutate
let someBytes : [UInt8] = [1, 2, 3, 4, 5]
var a = someBytes.withUnsafeBufferPointer {
return Data(buffer: $0)
}
// The bytes we'll insert
let b : [UInt8] = [9, 10, 11, 12, 13]
b.withUnsafeBufferPointer {
a.replaceSubrange(2..<5, with: $0)
}
XCTAssertEqual(expected, a)
}
func testReplaceSubrange4() {
let expectedBytes : [UInt8] = [1, 2, 9, 10, 11, 12, 13]
let expected = Data(bytes: expectedBytes)
// The data we'll mutate
let someBytes : [UInt8] = [1, 2, 3, 4, 5]
var a = Data(bytes: someBytes)
// The bytes we'll insert
let b : [UInt8] = [9, 10, 11, 12, 13]
a.replaceSubrange(2..<5, with: b)
XCTAssertEqual(expected, a)
}
func testReplaceSubrange5() {
var d = Data(bytes: [1, 2, 3])
d.replaceSubrange(0..<0, with: [4])
XCTAssertEqual(Data(bytes: [4, 1, 2, 3]), d)
d.replaceSubrange(0..<4, with: [9])
XCTAssertEqual(Data(bytes: [9]), d)
d.replaceSubrange(0..<d.count, with: [])
XCTAssertEqual(Data(), d)
d.replaceSubrange(0..<0, with: [1, 2, 3, 4])
XCTAssertEqual(Data(bytes: [1, 2, 3, 4]), d)
d.replaceSubrange(1..<3, with: [9, 8])
XCTAssertEqual(Data(bytes: [1, 9, 8, 4]), d)
d.replaceSubrange(d.count..<d.count, with: [5])
XCTAssertEqual(Data(bytes: [1, 9, 8, 4, 5]), d)
}
func testRange() {
let helloWorld = dataFrom("Hello World")
let goodbye = dataFrom("Goodbye")
let hello = dataFrom("Hello")
do {
let found = helloWorld.range(of: goodbye)
XCTAssertTrue(found == nil || found!.isEmpty)
}
do {
let found = helloWorld.range(of: goodbye, options: .anchored)
XCTAssertTrue(found == nil || found!.isEmpty)
}
do {
let found = helloWorld.range(of: hello, in: 7..<helloWorld.count)
XCTAssertTrue(found == nil || found!.isEmpty)
}
}
func testInsertData() {
let hello = dataFrom("Hello")
let world = dataFrom(" World")
let expected = dataFrom("Hello World")
var helloWorld = dataFrom("")
helloWorld.replaceSubrange(0..<0, with: world)
helloWorld.replaceSubrange(0..<0, with: hello)
XCTAssertEqual(helloWorld, expected)
}
func testLoops() {
let hello = dataFrom("Hello")
var count = 0
for _ in hello {
count += 1
}
XCTAssertEqual(count, 5)
}
func testGenericAlgorithms() {
let hello = dataFrom("Hello World")
let isCapital = { (byte : UInt8) in byte >= 65 && byte <= 90 }
let allCaps = hello.filter(isCapital)
XCTAssertEqual(allCaps.count, 2)
let capCount = hello.reduce(0) { isCapital($1) ? $0 + 1 : $0 }
XCTAssertEqual(capCount, 2)
let allLower = hello.map { isCapital($0) ? $0 + 31 : $0 }
XCTAssertEqual(allLower.count, hello.count)
}
func testCustomDeallocator() {
var deallocatorCalled = false
// Scope the data to a block to control lifecycle
do {
let buffer = malloc(16)!
let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: 16)
var data = Data(bytesNoCopy: bytePtr, count: 16, deallocator: .custom({ (ptr, size) in
deallocatorCalled = true
free(UnsafeMutableRawPointer(ptr))
}))
// Use the data
data[0] = 1
}
XCTAssertTrue(deallocatorCalled, "Custom deallocator was never called")
}
func testCopyBytes() {
let c = 10
let underlyingBuffer = malloc(c * MemoryLayout<UInt16>.stride)!
let u16Ptr = underlyingBuffer.bindMemory(to: UInt16.self, capacity: c)
let buffer = UnsafeMutableBufferPointer<UInt16>(start: u16Ptr, count: c)
buffer[0] = 0
buffer[1] = 0
var data = Data(capacity: c * MemoryLayout<UInt16>.stride)
data.resetBytes(in: 0..<c * MemoryLayout<UInt16>.stride)
data[0] = 0xFF
data[1] = 0xFF
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(copiedCount, c * MemoryLayout<UInt16>.stride)
XCTAssertEqual(buffer[0], 0xFFFF)
free(underlyingBuffer)
}
func testCopyBytes_undersized() {
let a : [UInt8] = [1, 2, 3, 4, 5]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let expectedSize = MemoryLayout<UInt8>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize - 1
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
// We should only copy in enough bytes that can fit in the buffer
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(expectedSize - 1, copiedCount)
var index = 0
for v in a[0..<expectedSize-1] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
func testCopyBytes_oversized() {
let a : [Int32] = [1, 0, 1, 0, 1]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let expectedSize = MemoryLayout<Int32>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize + 1
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(expectedSize, copiedCount)
free(underlyingBuffer)
}
func testCopyBytes_ranges() {
do {
// Equal sized buffer, data
let a : [UInt8] = [1, 2, 3, 4, 5]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = data.count
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<0)
XCTAssertEqual(0, copiedCount)
copiedCount = data.copyBytes(to: buffer, from: 1..<1)
XCTAssertEqual(0, copiedCount)
copiedCount = data.copyBytes(to: buffer, from: 0..<3)
XCTAssertEqual((0..<3).count, copiedCount)
var index = 0
for v in a[0..<3] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
do {
// Larger buffer than data
let a : [UInt8] = [1, 2, 3, 4]
let data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = 10
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<3)
XCTAssertEqual((0..<3).count, copiedCount)
var index = 0
for v in a[0..<3] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
do {
// Larger data than buffer
let a : [UInt8] = [1, 2, 3, 4, 5, 6]
let data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
let size = 4
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
var copiedCount : Int
copiedCount = data.copyBytes(to: buffer, from: 0..<data.index(before: data.endIndex))
XCTAssertEqual(4, copiedCount)
var index = 0
for v in a[0..<4] {
XCTAssertEqual(v, buffer[index])
index += 1
}
free(underlyingBuffer)
}
}
func test_base64Data_small() {
let data = "Hello World".data(using: .utf8)!
let base64 = data.base64EncodedString()
XCTAssertEqual("SGVsbG8gV29ybGQ=", base64, "trivial base64 conversion should work")
}
func test_dataHash() {
let dataStruct = "Hello World".data(using: .utf8)!
let dataObj = dataStruct._bridgeToObjectiveC()
XCTAssertEqual(dataObj.hashValue, dataStruct.hashValue, "Data and NSData should have the same hash value")
}
func test_base64Data_medium() {
let data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut at tincidunt arcu. Suspendisse nec sodales erat, sit amet imperdiet ipsum. Etiam sed ornare felis. Nunc mauris turpis, bibendum non lectus quis, malesuada placerat turpis. Nam adipiscing non massa et semper. Nulla convallis semper bibendum. Aliquam dictum nulla cursus mi ultricies, at tincidunt mi sagittis. Nulla faucibus at dui quis sodales. Morbi rutrum, dui id ultrices venenatis, arcu urna egestas felis, vel suscipit mauris arcu quis risus. Nunc venenatis ligula at orci tristique, et mattis purus pulvinar. Etiam ultricies est odio. Nunc eleifend malesuada justo, nec euismod sem ultrices quis. Etiam nec nibh sit amet lorem faucibus dapibus quis nec leo. Praesent sit amet mauris vel lacus hendrerit porta mollis consectetur mi. Donec eget tortor dui. Morbi imperdiet, arcu sit amet elementum interdum, quam nisl tempor quam, vitae feugiat augue purus sed lacus. In ac urna adipiscing purus venenatis volutpat vel et metus. Nullam nec auctor quam. Phasellus porttitor felis ac nibh gravida suscipit tempus at ante. Nunc pellentesque iaculis sapien a mattis. Aenean eleifend dolor non nunc laoreet, non dictum massa aliquam. Aenean quis turpis augue. Praesent augue lectus, mollis nec elementum eu, dignissim at velit. Ut congue neque id ullamcorper pellentesque. Maecenas euismod in elit eu vehicula. Nullam tristique dui nulla, nec convallis metus suscipit eget. Cras semper augue nec cursus blandit. Nulla rhoncus et odio quis blandit. Praesent lobortis dignissim velit ut pulvinar. Duis interdum quam adipiscing dolor semper semper. Nunc bibendum convallis dui, eget mollis magna hendrerit et. Morbi facilisis, augue eu fringilla convallis, mauris est cursus dolor, eu posuere odio nunc quis orci. Ut eu justo sem. Phasellus ut erat rhoncus, faucibus arcu vitae, vulputate erat. Aliquam nec magna viverra, interdum est vitae, rhoncus sapien. Duis tincidunt tempor ipsum ut dapibus. Nullam commodo varius metus, sed sollicitudin eros. Etiam nec odio et dui tempor blandit posuere.".data(using: .utf8)!
let base64 = data.base64EncodedString()
XCTAssertEqual("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgYXQgdGluY2lkdW50IGFyY3UuIFN1c3BlbmRpc3NlIG5lYyBzb2RhbGVzIGVyYXQsIHNpdCBhbWV0IGltcGVyZGlldCBpcHN1bS4gRXRpYW0gc2VkIG9ybmFyZSBmZWxpcy4gTnVuYyBtYXVyaXMgdHVycGlzLCBiaWJlbmR1bSBub24gbGVjdHVzIHF1aXMsIG1hbGVzdWFkYSBwbGFjZXJhdCB0dXJwaXMuIE5hbSBhZGlwaXNjaW5nIG5vbiBtYXNzYSBldCBzZW1wZXIuIE51bGxhIGNvbnZhbGxpcyBzZW1wZXIgYmliZW5kdW0uIEFsaXF1YW0gZGljdHVtIG51bGxhIGN1cnN1cyBtaSB1bHRyaWNpZXMsIGF0IHRpbmNpZHVudCBtaSBzYWdpdHRpcy4gTnVsbGEgZmF1Y2lidXMgYXQgZHVpIHF1aXMgc29kYWxlcy4gTW9yYmkgcnV0cnVtLCBkdWkgaWQgdWx0cmljZXMgdmVuZW5hdGlzLCBhcmN1IHVybmEgZWdlc3RhcyBmZWxpcywgdmVsIHN1c2NpcGl0IG1hdXJpcyBhcmN1IHF1aXMgcmlzdXMuIE51bmMgdmVuZW5hdGlzIGxpZ3VsYSBhdCBvcmNpIHRyaXN0aXF1ZSwgZXQgbWF0dGlzIHB1cnVzIHB1bHZpbmFyLiBFdGlhbSB1bHRyaWNpZXMgZXN0IG9kaW8uIE51bmMgZWxlaWZlbmQgbWFsZXN1YWRhIGp1c3RvLCBuZWMgZXVpc21vZCBzZW0gdWx0cmljZXMgcXVpcy4gRXRpYW0gbmVjIG5pYmggc2l0IGFtZXQgbG9yZW0gZmF1Y2lidXMgZGFwaWJ1cyBxdWlzIG5lYyBsZW8uIFByYWVzZW50IHNpdCBhbWV0IG1hdXJpcyB2ZWwgbGFjdXMgaGVuZHJlcml0IHBvcnRhIG1vbGxpcyBjb25zZWN0ZXR1ciBtaS4gRG9uZWMgZWdldCB0b3J0b3IgZHVpLiBNb3JiaSBpbXBlcmRpZXQsIGFyY3Ugc2l0IGFtZXQgZWxlbWVudHVtIGludGVyZHVtLCBxdWFtIG5pc2wgdGVtcG9yIHF1YW0sIHZpdGFlIGZldWdpYXQgYXVndWUgcHVydXMgc2VkIGxhY3VzLiBJbiBhYyB1cm5hIGFkaXBpc2NpbmcgcHVydXMgdmVuZW5hdGlzIHZvbHV0cGF0IHZlbCBldCBtZXR1cy4gTnVsbGFtIG5lYyBhdWN0b3IgcXVhbS4gUGhhc2VsbHVzIHBvcnR0aXRvciBmZWxpcyBhYyBuaWJoIGdyYXZpZGEgc3VzY2lwaXQgdGVtcHVzIGF0IGFudGUuIE51bmMgcGVsbGVudGVzcXVlIGlhY3VsaXMgc2FwaWVuIGEgbWF0dGlzLiBBZW5lYW4gZWxlaWZlbmQgZG9sb3Igbm9uIG51bmMgbGFvcmVldCwgbm9uIGRpY3R1bSBtYXNzYSBhbGlxdWFtLiBBZW5lYW4gcXVpcyB0dXJwaXMgYXVndWUuIFByYWVzZW50IGF1Z3VlIGxlY3R1cywgbW9sbGlzIG5lYyBlbGVtZW50dW0gZXUsIGRpZ25pc3NpbSBhdCB2ZWxpdC4gVXQgY29uZ3VlIG5lcXVlIGlkIHVsbGFtY29ycGVyIHBlbGxlbnRlc3F1ZS4gTWFlY2VuYXMgZXVpc21vZCBpbiBlbGl0IGV1IHZlaGljdWxhLiBOdWxsYW0gdHJpc3RpcXVlIGR1aSBudWxsYSwgbmVjIGNvbnZhbGxpcyBtZXR1cyBzdXNjaXBpdCBlZ2V0LiBDcmFzIHNlbXBlciBhdWd1ZSBuZWMgY3Vyc3VzIGJsYW5kaXQuIE51bGxhIHJob25jdXMgZXQgb2RpbyBxdWlzIGJsYW5kaXQuIFByYWVzZW50IGxvYm9ydGlzIGRpZ25pc3NpbSB2ZWxpdCB1dCBwdWx2aW5hci4gRHVpcyBpbnRlcmR1bSBxdWFtIGFkaXBpc2NpbmcgZG9sb3Igc2VtcGVyIHNlbXBlci4gTnVuYyBiaWJlbmR1bSBjb252YWxsaXMgZHVpLCBlZ2V0IG1vbGxpcyBtYWduYSBoZW5kcmVyaXQgZXQuIE1vcmJpIGZhY2lsaXNpcywgYXVndWUgZXUgZnJpbmdpbGxhIGNvbnZhbGxpcywgbWF1cmlzIGVzdCBjdXJzdXMgZG9sb3IsIGV1IHBvc3VlcmUgb2RpbyBudW5jIHF1aXMgb3JjaS4gVXQgZXUganVzdG8gc2VtLiBQaGFzZWxsdXMgdXQgZXJhdCByaG9uY3VzLCBmYXVjaWJ1cyBhcmN1IHZpdGFlLCB2dWxwdXRhdGUgZXJhdC4gQWxpcXVhbSBuZWMgbWFnbmEgdml2ZXJyYSwgaW50ZXJkdW0gZXN0IHZpdGFlLCByaG9uY3VzIHNhcGllbi4gRHVpcyB0aW5jaWR1bnQgdGVtcG9yIGlwc3VtIHV0IGRhcGlidXMuIE51bGxhbSBjb21tb2RvIHZhcml1cyBtZXR1cywgc2VkIHNvbGxpY2l0dWRpbiBlcm9zLiBFdGlhbSBuZWMgb2RpbyBldCBkdWkgdGVtcG9yIGJsYW5kaXQgcG9zdWVyZS4=", base64, "medium base64 conversion should work")
}
func test_openingNonExistentFile() {
var didCatchError = false
do {
let _ = try NSData(contentsOfFile: "does not exist", options: [])
} catch {
didCatchError = true
}
XCTAssertTrue(didCatchError)
}
func test_contentsOfFile() {
let testDir = testBundle().resourcePath
let filename = testDir!.appending("/NSStringTestData.txt")
let contents = NSData(contentsOfFile: filename)
XCTAssertNotNil(contents)
if let contents = contents {
let ptr = UnsafeMutableRawPointer(mutating: contents.bytes)
let str = String(bytesNoCopy: ptr, length: contents.length,
encoding: .ascii, freeWhenDone: false)
XCTAssertEqual(str, "swift-corelibs-foundation")
}
}
func test_contentsOfZeroFile() {
#if os(Linux)
guard FileManager.default.fileExists(atPath: "/proc/self") else {
return
}
let contents = NSData(contentsOfFile: "/proc/self/cmdline")
XCTAssertNotNil(contents)
if let contents = contents {
XCTAssertTrue(contents.length > 0)
let ptr = UnsafeMutableRawPointer(mutating: contents.bytes)
let str = String(bytesNoCopy: ptr, length: contents.length,
encoding: .ascii, freeWhenDone: false)
XCTAssertNotNil(str)
if let str = str {
XCTAssertTrue(str.hasSuffix("TestFoundation"))
}
}
do {
let maps = try String(contentsOfFile: "/proc/self/maps", encoding: .utf8)
XCTAssertTrue(maps.count > 0)
} catch {
XCTFail("Cannot read /proc/self/maps: \(String(describing: error))")
}
#endif
}
func test_basicReadWrite() {
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testfile")
let count = 1 << 24
let randomMemory = malloc(count)!
let ptr = randomMemory.bindMemory(to: UInt8.self, capacity: count)
let data = Data(bytesNoCopy: ptr, count: count, deallocator: .free)
do {
try data.write(to: url)
let readData = try Data(contentsOf: url)
XCTAssertEqual(data, readData)
} catch {
XCTFail("Should not have thrown")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
}
func test_writeFailure() {
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testfile")
let data = Data()
do {
try data.write(to: url)
} catch let error as NSError {
print(error)
XCTAssertTrue(false, "Should not have thrown")
} catch {
XCTFail("unexpected error")
}
do {
try data.write(to: url, options: [.withoutOverwriting])
XCTAssertTrue(false, "Should have thrown")
} catch let error as NSError {
XCTAssertEqual(error.code, CocoaError.fileWriteFileExists.rawValue)
} catch {
XCTFail("unexpected error")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
// Make sure clearing the error condition allows the write to succeed
do {
try data.write(to: url, options: [.withoutOverwriting])
} catch {
XCTAssertTrue(false, "Should not have thrown")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
// ignore
}
}
func test_genericBuffers() {
let a : [Int32] = [1, 0, 1, 0, 1]
var data = a.withUnsafeBufferPointer {
return Data(buffer: $0)
}
var expectedSize = MemoryLayout<Int32>.stride * a.count
XCTAssertEqual(expectedSize, data.count)
[false, true].withUnsafeBufferPointer {
data.append($0)
}
expectedSize += MemoryLayout<Bool>.stride * 2
XCTAssertEqual(expectedSize, data.count)
let size = expectedSize
let underlyingBuffer = malloc(size)!
let buffer = UnsafeMutableBufferPointer(start: underlyingBuffer.bindMemory(to: UInt8.self, capacity: size), count: size)
let copiedCount = data.copyBytes(to: buffer)
XCTAssertEqual(copiedCount, expectedSize)
free(underlyingBuffer)
}
// intentionally structured so sizeof() != strideof()
struct MyStruct {
var time: UInt64
let x: UInt32
let y: UInt32
let z: UInt32
init() {
time = 0
x = 1
y = 2
z = 3
}
}
func test_bufferSizeCalculation() {
// Make sure that Data is correctly using strideof instead of sizeof.
// n.b. if sizeof(MyStruct) == strideof(MyStruct), this test is not as useful as it could be
// init
let stuff = [MyStruct(), MyStruct(), MyStruct()]
var data = stuff.withUnsafeBufferPointer {
return Data(buffer: $0)
}
XCTAssertEqual(data.count, MemoryLayout<MyStruct>.stride * 3)
// append
stuff.withUnsafeBufferPointer {
data.append($0)
}
XCTAssertEqual(data.count, MemoryLayout<MyStruct>.stride * 6)
// copyBytes
do {
// equal size
let underlyingBuffer = malloc(6 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 6)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(6 * MemoryLayout<MyStruct>.stride, byteCount)
}
do {
// undersized
let underlyingBuffer = malloc(3 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 3)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 3)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(3 * MemoryLayout<MyStruct>.stride, byteCount)
}
do {
// oversized
let underlyingBuffer = malloc(12 * MemoryLayout<MyStruct>.stride)!
defer { free(underlyingBuffer) }
let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6)
let buffer = UnsafeMutableBufferPointer<MyStruct>(start: ptr, count: 6)
let byteCount = data.copyBytes(to: buffer)
XCTAssertEqual(6 * MemoryLayout<MyStruct>.stride, byteCount)
}
}
func test_repeatingValueInitialization() {
var d = Data(repeating: 0x01, count: 3)
let elements = repeatElement(UInt8(0x02), count: 3) // ensure we fall into the sequence case
d.append(contentsOf: elements)
XCTAssertEqual(d[0], 0x01)
XCTAssertEqual(d[1], 0x01)
XCTAssertEqual(d[2], 0x01)
XCTAssertEqual(d[3], 0x02)
XCTAssertEqual(d[4], 0x02)
XCTAssertEqual(d[5], 0x02)
}
func test_sliceAppending() {
// https://bugs.swift.org/browse/SR-4473
var fooData = Data()
let barData = Data([0, 1, 2, 3, 4, 5])
let slice = barData.suffix(from: 3)
fooData.append(slice)
XCTAssertEqual(fooData[0], 0x03)
XCTAssertEqual(fooData[1], 0x04)
XCTAssertEqual(fooData[2], 0x05)
}
func test_replaceSubrange() {
// https://bugs.swift.org/browse/SR-4462
let data = Data(bytes: [0x01, 0x02])
var dataII = Data(base64Encoded: data.base64EncodedString())!
dataII.replaceSubrange(0..<1, with: Data())
XCTAssertEqual(dataII[0], 0x02)
}
func test_sliceWithUnsafeBytes() {
let base = Data([0, 1, 2, 3, 4, 5])
let slice = base[2..<4]
let segment = slice.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> [UInt8] in
return [ptr.pointee, ptr.advanced(by: 1).pointee]
}
XCTAssertEqual(segment, [UInt8(2), UInt8(3)])
}
func test_sliceIteration() {
let base = Data([0, 1, 2, 3, 4, 5])
let slice = base[2..<4]
var found = [UInt8]()
for byte in slice {
found.append(byte)
}
XCTAssertEqual(found[0], 2)
XCTAssertEqual(found[1], 3)
}
}
| apache-2.0 |
weby/Swifton | Sources/Swifton/JSONRenderable.swift | 2 | 88 | public protocol JSONRenderable {
func renderableJSONAttributes() -> [String: Any]
}
| mit |
zmarvin/EnjoyMusic | Pods/Macaw/Source/animation/types/animation_generators/TransformGenerator.swift | 1 | 2950 | import UIKit
func addTransformAnimation(_ animation: BasicAnimation, sceneLayer: CALayer, animationCache: AnimationCache, completion: @escaping (() -> ())) {
guard let transformAnimation = animation as? TransformAnimation else {
return
}
guard let node = animation.node else {
return
}
// Creating proper animation
var generatedAnimation: CAAnimation?
generatedAnimation = transformAnimationByFunc(node, valueFunc: transformAnimation.getVFunc(), duration: animation.getDuration(), fps: transformAnimation.logicalFps)
guard let generatedAnim = generatedAnimation else {
return
}
generatedAnim.repeatCount = Float(animation.repeatCount)
generatedAnim.timingFunction = caTimingFunction(animation.easing)
generatedAnim.completion = { finished in
if !animation.manualStop {
animation.progress = 1.0
node.placeVar.value = transformAnimation.getVFunc()(1.0)
} else {
node.placeVar.value = transformAnimation.getVFunc()(animation.progress)
}
animationCache.freeLayer(node)
animation.completion?()
if !finished {
animationRestorer.addRestoreClosure(completion)
return
}
completion()
}
generatedAnim.progress = { progress in
let t = Double(progress)
node.placeVar.value = transformAnimation.getVFunc()(t)
animation.progress = t
animation.onProgressUpdate?(t)
}
let layer = animationCache.layerForNode(node, animation: animation)
layer.add(generatedAnim, forKey: animation.ID)
animation.removeFunc = {
layer.removeAnimation(forKey: animation.ID)
}
}
func transfomToCG(_ transform: Transform) -> CGAffineTransform {
return CGAffineTransform(
a: CGFloat(transform.m11),
b: CGFloat(transform.m12),
c: CGFloat(transform.m21),
d: CGFloat(transform.m22),
tx: CGFloat(transform.dx),
ty: CGFloat(transform.dy))
}
func transformAnimationByFunc(_ node: Node, valueFunc: (Double) -> Transform, duration: Double, fps: UInt) -> CAAnimation {
var transformValues = [CATransform3D]()
var timeValues = [Double]()
let step = 1.0 / (duration * Double(fps))
var dt = 0.0
var tValue = Array(stride(from: 0.0, to: 1.0, by: step))
tValue.append(1.0)
for t in tValue {
dt = t
if 1.0 - dt < step {
dt = 1.0
}
let value = AnimationUtils.absoluteTransform(node, pos: valueFunc(dt))
let cgValue = CATransform3DMakeAffineTransform(RenderUtils.mapTransform(value))
transformValues.append(cgValue)
}
let transformAnimation = CAKeyframeAnimation(keyPath: "transform")
transformAnimation.duration = duration
transformAnimation.values = transformValues
transformAnimation.keyTimes = timeValues as [NSNumber]?
transformAnimation.fillMode = kCAFillModeForwards
transformAnimation.isRemovedOnCompletion = false
return transformAnimation
}
func fixedAngle(_ angle: CGFloat) -> CGFloat {
return angle > -0.0000000000000000000000001 ? angle : CGFloat(2.0 * M_PI) + angle
}
| mit |
matchmore/alps-ios-sdk | Matchmore/Matchmore+Location.swift | 1 | 1599 | //
// Matchmore+Location.swift
// Matchmore
//
// Created by Maciej Burda on 15/11/2017.
// Copyright © 2018 Matchmore SA. All rights reserved.
//
import Foundation
public extension Matchmore {
/// Last location gathered by SDK.
public static var lastLocation: Location? {
return instance.locationUpdateManager.lastLocation
}
/// Starts location updating and sending to MatchMore's cloud.
public class func startUpdatingLocation() {
instance.contextManager.locationManager?.startUpdatingLocation()
}
/// Stops location updating and sending to MatchMore's cloud.
public class func stopUpdatingLocation() {
instance.contextManager.locationManager?.stopUpdatingLocation()
}
/// Starts ranging iBeacons that were set on Matchmore's cloud. Cloud is being notified about proxmity event every `updateTimeInterval` seconds.
public class func startRangingBeacons(updateTimeInterval: TimeInterval) {
instance.contextManager.proximityHandler.refreshTimer = Int(updateTimeInterval * 1000)
instance.contextManager.beaconTriples.updateBeaconTriplets {
instance.contextManager.startRanging()
}
}
public class func triggerProxmityEventForDeviceId(deviceId: String, distance: Double, completion: ((Error?) -> Void)?) {
let proximityEvent = ProximityEvent(deviceId: deviceId, distance: distance)
DeviceAPI.triggerProximityEvents(deviceId: instance.mobileDevices.main!.id!, proximityEvent: proximityEvent) { (_, error) -> Void in
completion?(error)
}
}
}
| mit |
xuanyi0627/jetstream-ios | JetstreamTests/ChangeSetTests.swift | 1 | 5861 | //
// ChangeSetTests.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import XCTest
class ChangeSetTests: XCTestCase {
var root = TestModel()
var child = TestModel()
var scope = Scope(name: "Testing")
override func setUp() {
root = TestModel()
child = TestModel()
scope = Scope(name: "Testing")
root.setScopeAndMakeRootModel(scope)
}
override func tearDown() {
super.tearDown()
}
func testBasicReversal() {
root.integer = 10
root.float32 = 10.0
root.string = "test"
scope.getAndClearSyncFragments()
root.integer = 20
root.float32 = 20.0
root.string = "test 2"
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
changeSet.revertOnScope(scope)
XCTAssertEqual(scope.getAndClearSyncFragments().count, 0, "Should have reverted without generating Sync fragments")
XCTAssertEqual(root.integer, 10, "Change set reverted")
XCTAssertEqual(root.float32, Float(10.0), "Change set reverted")
XCTAssertEqual(root.string!, "test", "Change set reverted")
}
func testModelReversal() {
root.childModel = child
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
changeSet.revertOnScope(scope)
XCTAssertEqual(scope.getAndClearSyncFragments().count, 0, "Should have reverted without generating Sync fragments")
XCTAssert(root.childModel == nil, "Change set reverted")
XCTAssertEqual(scope.modelObjects.count, 1 , "Scope knows correct models")
}
func testModelReapplying() {
root.childModel = child
scope.getAndClearSyncFragments()
root.childModel = nil
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
changeSet.revertOnScope(scope)
XCTAssertEqual(scope.getAndClearSyncFragments().count, 0, "Should have reverted without generating Sync fragments")
XCTAssert(root.childModel == child, "Change set reverted")
XCTAssertEqual(scope.modelObjects.count, 2 , "Scope knows correct models")
}
func testArrayReversal() {
root.array.append(child)
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 2, "Correct number of sync fragments")
changeSet.revertOnScope(scope)
XCTAssertEqual(scope.getAndClearSyncFragments().count, 0, "Should have reverted without generating Sync fragments")
XCTAssertEqual(root.array.count, 0, "Change set reverted")
XCTAssertEqual(scope.modelObjects.count, 1 , "Scope knows correct models")
}
func testMovingChildModel() {
root.childModel = child
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 2, "Correct number of sync fragments")
root.childModel = nil
root.childModel2 = child
changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 1, "No add fragment created")
root.childModel2 = nil
changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 1, "No add fragment created")
root.childModel = child
changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 2, "Add fragment created")
}
func testRemovalOfAddFragmentsWhenNotAttachedToAnyProperties() {
root.localModel = TestModel()
var changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 0, "Add fragment should have been removed")
root.localModelArray = [TestModel(), TestModel()]
changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 0, "Add fragment should have been removed")
root.localModel = TestModel()
root.localModelArray = [TestModel(), TestModel()]
changeSet = ChangeSet(syncFragments: scope.getAndClearSyncFragments(), scope: scope)
XCTAssertEqual(changeSet.syncFragments.count, 0, "Add fragment should have been removed")
}
}
| mit |
mathcamp/lightbase | hldb/Lib/FMDBConnector.swift | 2 | 1978 | //
// FMDBConnector.swift
// hldb
//
// Created by Noah Picard on 6/27/16.
// Copyright © 2016 Mathcamp. All rights reserved.
//
import Foundation
public struct FMCursor: LazySequenceType, GeneratorType {
public typealias Element = NSDictionary
let fmResult: FMResultSet
public mutating func next() -> NSDictionary? {
if fmResult.next() {
return fmResult.resultDictionary()
} else {
return nil
}
}
}
public class FMAbstractDB: AbstractDB {
public typealias Cursor = FMCursor
internal let fmdb: FMDatabase
public init(fmdb: FMDatabase) {
self.fmdb = fmdb
}
public func executeUpdate(sql: String, withArgumentsInArray args:[AnyObject]) -> Bool {
return fmdb.executeUpdate(sql, withArgumentsInArray: args)
}
public func executeQuery(query: String, withArgumentsInArray args:[AnyObject]) -> FMCursor? {
return (fmdb.executeQuery(query, withArgumentsInArray: args) as FMResultSet?).map(FMCursor.init)
}
public func lastErrorMessage() -> String {
return fmdb.lastErrorMessage()
}
public func lastErrorCode() -> Int {
return Int(fmdb.lastErrorCode())
}
}
public class FMAbstractDBQueue: AbstractDBQueue {
public typealias DB = FMAbstractDB
let dbPath: String
let fmdbQueue: FMDatabaseQueue
public required init(dbPath: String) {
self.dbPath = dbPath
fmdbQueue = FMDatabaseQueue.init(path: dbPath)
}
public func execInDatabase(block: DB -> ()) {
fmdbQueue.inDatabase{ db in block(FMAbstractDB(fmdb: db)) }
}
public func execInTransaction(block: DB -> RollbackChoice) {
let fullBlock: (FMDatabase!, UnsafeMutablePointer<ObjCBool>) -> () = {db, success in
success.initialize(ObjCBool(
{
switch block(FMAbstractDB(fmdb: db)) {
case .Rollback:
return true
case .Ok:
return false
}}()
))
}
fmdbQueue.inTransaction(fullBlock)
}
}
| mit |
danube83/AppStoreSample | SampleProject/ViewControllers/DataProvider/HomeDataProvider.swift | 1 | 745 | //
// HomeDataProvider.swift
// SampleProject
//
// Created by danube83 on 2017. 2. 4..
// Copyright © 2017년 danube83. All rights reserved.
//
import Foundation
class HomeDataProvider {
var topFreeApplications: [TopFreeApplicationModel]?
func loadHomeData(completion: @escaping ()->()) {
let api = topFreeApplicationAPI()
send(api: api, keyPath: "feed.entry") { [weak self] (response: [TopFreeApplicationModel]?) in
defer {
completion()
}
guard let unwrappedResponse = response else {
return
}
self?.topFreeApplications = unwrappedResponse
}
}
}
| mit |
weizhangCoder/PageViewController_swift | ZWPageView/ZWPageView/ZWPageView/UIColor-Extension.swift | 1 | 1077 | //
// UIColor-Extension.swift
// ZWPageView
//
// Created by zhangwei on 16/12/13.
// Copyright © 2016年 jyall. All rights reserved.
//
import UIKit
extension UIColor{
convenience init(r:CGFloat,g:CGFloat,b:CGFloat,alpha:CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
//随机颜色
class func randimColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
class func getRGBDelta(_ firstColor : UIColor,_ secondColor : UIColor) -> (CGFloat,CGFloat,CGFloat){
let firstRGB = firstColor.getRGB()
let secondRGB = secondColor.getRGB()
return(firstRGB.0 - secondRGB.0,firstRGB.1 - secondRGB.1,firstRGB.2 - secondRGB.2)
}
func getRGB() -> (CGFloat,CGFloat,CGFloat) {
guard let cmps = cgColor.components else {
fatalError("保证传入正确的RGB值")
}
return(cmps[0] * 255,cmps[1] * 255,cmps[2] * 255)
}
}
| mit |
stephanmantler/SwiftyGPIO | Sources/1Wire.swift | 1 | 3894 | /*
SwiftyGPIO
Copyright (c) 2017 Umberto Raimondi
Licensed under the MIT license, as follows:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.)
*/
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
// MARK: - 1-Wire Presets
extension SwiftyGPIO {
public static func hardware1Wires(for board: SupportedBoard) -> [OneWireInterface]? {
switch board {
case .RaspberryPiRev1:
fallthrough
case .RaspberryPiRev2:
fallthrough
case .RaspberryPiPlusZero:
fallthrough
case .RaspberryPi2:
fallthrough
case .RaspberryPi3:
return [SysFSOneWire(masterId: 1)]
default:
return nil
}
}
}
// MARK: 1-Wire
public protocol OneWireInterface {
func getSlaves() -> [String]
func readData(_ slaveId: String) -> [String]
}
/// Hardware 1-Wire via SysFS
public final class SysFSOneWire: OneWireInterface {
let masterId: Int
public init(masterId: Int) {
self.masterId = masterId
}
public func getSlaves() -> [String] {
let listpath = ONEWIREBASEPATH+"w1_bus_master"+String(masterId)+"/w1_master_slaves"
let fd = open(listpath, O_RDONLY | O_SYNC)
guard fd>0 else {
perror("Couldn't open 1-Wire master device")
abort()
}
var slaves = [String]()
while let s = readLine(fd) {
slaves.append(s)
}
close(fd)
return slaves
}
public func readData(_ slaveId: String) -> [String] {
let devicepath = ONEWIREBASEPATH+slaveId+"/w1_slave"
let fd = open(devicepath, O_RDONLY | O_SYNC)
guard fd>0 else {
perror("Couldn't open 1-Wire slave device")
abort()
}
var lines = [String]()
while let s = readLine(fd) {
lines.append(s)
}
close(fd)
return lines
}
private func readLine(_ fd: Int32) -> String? {
var buf = [CChar](repeating:0, count: 128)
var ptr = UnsafeMutablePointer<CChar>(&buf)
var pos = 0
repeat {
let n = read(fd, ptr, MemoryLayout<CChar>.stride)
if n<0 {
perror("Error while reading from 1-Wire interface")
abort()
} else if n == 0 {
break
}
ptr += 1
pos += 1
} while buf[pos-1] != CChar(UInt8(ascii: "\n"))
if pos == 0 {
return nil
} else {
buf[pos-1] = 0
return String(cString: &buf)
}
}
}
// MARK: - 1-Wire Constants
internal let ONEWIREBASEPATH = "/sys/bus/w1/devices/"
// MARK: - Darwin / Xcode Support
#if os(OSX) || os(iOS)
private var O_SYNC: CInt { fatalError("Linux only") }
#endif
| mit |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBAConsentSection.swift | 1 | 5613 | //
// SBAConsentSection.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
/**
Mapping used to define each section in the consent document. This is used for both
visual consent and consent review.
*/
public protocol SBAConsentSection: class {
var consentSectionType: SBAConsentSectionType { get }
var sectionTitle: String? { get }
var sectionFormalTitle: String? { get }
var sectionSummary: String? { get }
var sectionContent: String? { get }
var sectionHtmlContent: String? { get }
var sectionLearnMoreButtonTitle: String? { get }
var sectionCustomImage: UIImage? { get }
var sectionCustomAnimationURLString: String? { get }
}
public enum SBAConsentSectionType: String {
// Maps to ORKConsentSectionType
// These cases use images and animations baked into ResearchKit
case overview
case privacy
case dataGathering
case dataUse
case timeCommitment
case studySurvey
case studyTasks
case onlyInDocument
// Maps to ResearchUXFactory resources
// These cases use images and animations baked into ResearchUXFactory
case understanding
case activities
case sensorData
case medicalCare
case followUp
case potentialRisks
case exitArrow
case thinkItOver
case futureResearch
case dataSharing
case qualifiedResearchers
// The section defines its own image and animation
case custom
/**
Some sections of the consent flow map to sections where the image and animation
are defined in ResearchKit. For these cases, use the ResearchKit section types.
*/
var orkSectionType: ORKConsentSectionType {
switch(self) {
case .overview:
// syoung 10/05/2016 The layout of the ORKConsentSectionType.overview does not
// match the layout of the other views so the animation is janky.
return .custom
case .privacy:
return .privacy
case .dataGathering:
return .dataGathering
case .dataUse:
return .dataUse
case .timeCommitment:
return .timeCommitment
case .studySurvey:
return .studySurvey
case .studyTasks:
return .studyTasks
case .onlyInDocument:
return .onlyInDocument
case .potentialRisks:
// Internally, we use the "withdrawing" image and animation for potential risks
return .withdrawing
default:
return .custom
}
}
var customImage: UIImage? {
let imageName = "consent_\(self.rawValue)"
return SBAResourceFinder.shared.image(forResource: imageName)
}
}
extension SBAConsentSection {
func createConsentSection(previous: SBAConsentSectionType?) -> ORKConsentSection {
let section = ORKConsentSection(type: self.consentSectionType.orkSectionType)
section.title = self.sectionTitle
section.formalTitle = self.sectionFormalTitle
section.summary = self.sectionSummary
section.content = self.sectionContent
section.htmlContent = self.sectionHtmlContent
section.customImage = self.sectionCustomImage ?? self.consentSectionType.customImage
section.customAnimationURL = animationURL(previous: previous)
section.customLearnMoreButtonTitle = self.sectionLearnMoreButtonTitle ?? Localization.buttonLearnMore()
return section
}
func animationURL(previous: SBAConsentSectionType?) -> URL? {
let fromSection = previous?.rawValue ?? "blank"
let toSection = self.consentSectionType.rawValue
let urlString = self.sectionCustomAnimationURLString ?? "consent_\(fromSection)_to_\(toSection)"
let scaleFactor = UIScreen.main.scale >= 3 ? "@3x" : "@2x"
return SBAResourceFinder.shared.url(forResource: "\(urlString)\(scaleFactor)", withExtension: "m4v")
}
}
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.