repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
lszzy/FWDebug
Example/Example/SwiftController.swift
1
4269
// // SwiftController.swift // Example // // Created by wuyong on 2018/3/2. // Copyright © 2018年 wuyong.site. All rights reserved. // import UIKit import FWDebug import CoreLocation @objcMembers class SwiftController: UIViewController, CLLocationManagerDelegate { // MARK: - Property private struct AssociatedKeys { static var object = "ak_object" } var object: Any? { get { return objc_getAssociatedObject(self, &AssociatedKeys.object) } set { objc_setAssociatedObject(self, &AssociatedKeys.object, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var locationManager: CLLocationManager? var locationButton: UIButton? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = "Swift" self.edgesForExtendedLayout = [] self.view.backgroundColor = UIColor.white self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Debug", style: .plain, target: self, action: #selector(onDebug)) let retainCycleButton = UIButton(type: .system) retainCycleButton.setTitle("Retain Cycle", for: .normal) retainCycleButton.addTarget(self, action: #selector(onRetainCycle), for: .touchUpInside) retainCycleButton.frame = CGRect(x: self.view.frame.size.width / 2 - 100, y: 20, width: 200, height: 30) self.view.addSubview(retainCycleButton) let fakeLocationButton = UIButton(type: .system) self.locationButton = fakeLocationButton fakeLocationButton.setTitle("Fake Location", for: .normal) fakeLocationButton.addTarget(self, action: #selector(onFakeLocation), for: .touchUpInside) fakeLocationButton.frame = CGRect(x: self.view.frame.size.width / 2 - 100, y: 70, width: 200, height: 30) self.view.addSubview(fakeLocationButton) let crashButton = UIButton(type: .system) crashButton.setTitle("Crash", for: .normal) crashButton.addTarget(self, action: #selector(onCrash), for: .touchUpInside) crashButton.frame = CGRect(x: self.view.frame.size.width / 2 - 100, y: 120, width: 200, height: 30) self.view.addSubview(crashButton) } // MARK: - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //if let location = locations.last { if let location = manager.location { self.locationButton?.setTitle("\(location.coordinate.latitude),\(location.coordinate.longitude)", for: .normal) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { self.locationButton?.setTitle("Failed", for: .normal) } // MARK: - Action func onDebug() { if FWDebugManager.sharedInstance().isHidden { FWDebugManager.sharedInstance().show() FWDebugManager.sharedInstance().log("Show FWDebug") NSLog("Show FWDebug") } else { FWDebugManager.sharedInstance().hide() FWDebugManager.sharedInstance().log("Hide FWDebug") NSLog("Hide FWDebug") } } func onRetainCycle() { let retainObject = SwiftController() retainObject.object = self self.object = retainObject } func onFakeLocation() { if self.locationManager == nil { self.locationManager = CLLocationManager() self.locationManager?.delegate = self self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest self.locationManager?.distanceFilter = kCLDistanceFilterNone self.locationManager?.requestWhenInUseAuthorization() self.locationManager?.startUpdatingLocation() self.locationButton?.setTitle("Updating", for: .normal) } else { self.locationManager?.stopUpdatingLocation() self.locationManager?.delegate = nil self.locationManager = nil self.locationButton?.setTitle("Fake Location", for: .normal) } } func onCrash() { let object = NSObject() object.perform(#selector(onCrash)) } }
mit
2575a3ca9573dcd38d665b306827f1c8
37.432432
137
0.645335
4.897819
false
false
false
false
banxi1988/BXSlider
Pod/Classes/BXSlide.swift
1
1186
// // BXSlide.swift // Pods // // Created by Haizhen Lee on 16/4/19. // // import Foundation import UIKit public protocol BXSlide{ var bx_image:UIImage?{ get } var bx_imageURL:NSURL?{ get } var bx_title:String?{ get } } public extension BXSlide{ public var bx_duration:NSTimeInterval{ return 5.0 } var bx_image:UIImage?{ return nil } var bx_imageURL:NSURL?{ return nil } var bx_title:String?{ return nil } } extension NSURL:BXSlide{ public var bx_imageURL:NSURL?{ return self } } extension UIImage:BXSlide{ public var bx_image:UIImage?{ return self } } public class BXSimpleSlide:BXSlide{ public let image:UIImage? public let imageURL:NSURL? public let title:String? public var bx_image:UIImage?{ return image } public var bx_imageURL:NSURL?{ return imageURL } public var bx_title:String?{ return title } public var bx_duration:NSTimeInterval{ return 5.0 } public init(image:UIImage,title:String?=nil){ self.image = image self.title = title self.imageURL = nil } public init(imageURL:NSURL,title:String?=nil){ self.image = nil self.title = title self.imageURL = imageURL } }
mit
1e77462f45bb5ea775f45c48db82f1b1
17.546875
53
0.677909
3.498525
false
false
false
false
sheepy1/SelectionOfZhihu
SelectionOfZhihu/UserCell.swift
1
2083
// // UserCell.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/14. // Copyright © 2016年 Sheepy. All rights reserved. // //import UIKit // //class UserCell: UITableViewCell { // var avatarImageView: UIImageView! // // var nameLabel: UILabel! // // var signatureLabel: UILabel! // // var followImageView: UIImageView! // // var followCount: UILabel! // // override init(style: UITableViewCellStyle, reuseIdentifier: String?) { // super.init(style: style, reuseIdentifier: reuseIdentifier) // // avatarImageView = UIImageView(frame: CGRect(x: 8, y: 8, width: 80, height: 80)) // // nameLabel = UILabel(frame: CGRect(x: 100, y: 8, width: 200, height: 30)) // // signatureLabel = UILabel(frame: CGRect(x: 100, y: 40, width: 300, height: 30)) // // followImageView = UIImageView(frame: CGRect(x: 300, y: 8, width: 10, height: 10)) // followImageView.image = UIImage(named: "agree") // // followCount = UILabel(frame: CGRect(x: 320, y: 8, width: 50, height: 20)) // // [avatarImageView, nameLabel, signatureLabel, followImageView, followCount].forEach { // addSubview($0) // } // } // // func bindModel(model: TopUserModel, withIndex index: Int) { // avatarImageView.setImageWithId(index, imagePath: model.avatar) // // nameLabel.text = model.name // // signatureLabel.text = model.signature // // followCount.text = "\(model.agree)" // } // // func bindModel(model: JSON, withIndex index: Int) { // avatarImageView.setImageWithId(index, imagePath: model["avatar"].stringValue) // // nameLabel.text = model["name"].stringValue // // signatureLabel.text = model["signature"].stringValue // // followCount.text = "\(model["agree"].intValue)" // } // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // // //}
mit
4bbcffe72f17e6c64bc004645655cda1
29.985075
94
0.579961
3.713775
false
false
false
false
nevercry/VideoMarks
VideoMarks/Models/TaskManager.swift
1
14034
// // TaskManager.swift // VideoMarks // // Created by nevercry on 7/25/16. // Copyright © 2016 nevercry. All rights reserved. // import UIKit import Photos class TaskManager: NSObject { fileprivate var session: URLSession? var taskList:[DownloadTask] = [DownloadTask]() static let sharedInstance = TaskManager(); private override init() { super.init() let config = URLSessionConfiguration.background(withIdentifier: "downloadSession") self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) self.taskList = [DownloadTask]() } func addNewTask(_ url: URL, collectionId: String) { if url.lastPathComponent == "m3u8" { let networksession = URLSession(configuration: URLSessionConfiguration.default) networksession.dataTask(with: URLRequest(url: url), completionHandler: { (data, res, error) in print("解析...") guard (data != nil) else { print("m3u8 文件解析失败") return } // 判断URL属于那个视频网站 let m3u8Parser = HLSPlayListParser.shareInstance var videoFragments: [NSString] // 视频片段地址 if url.absoluteString.contains("youku.com") { print("url 属于youku") videoFragments = m3u8Parser.youkuParse(data!) } else { print("url 未知网站 暂不支持") return } guard videoFragments.count > 0 else { return } self.newGroupTask(videoFragments as [String], collectionId: collectionId) }).resume() } else { self.newTask(url, collectionId: collectionId) } } private func newTask(_ url: URL, collectionId: String) { let downloadTask = self.session?.downloadTask(with: url) downloadTask?.resume() let task = DownloadTask(url: url, taskIdentifier: downloadTask!.taskIdentifier, collectionId: collectionId) self.taskList.append(task) NotificationCenter.default.post(name: VideoMarksConstants.DownloadTaskStart, object: nil) } private func newGroupTask(_ urls: [String], collectionId: String) { var taskIds:[Int] = [] var taskUrls:[URL] = [] var tasks: [URLSessionTask] = [] for url in urls { let taskUrl = URL(string: url)! let downloadTask = self.session!.downloadTask(with: taskUrl) taskIds.append(downloadTask.taskIdentifier) taskUrls.append(taskUrl) tasks.append(downloadTask) } let groupTask = DownloadTask(urls: taskUrls, taskIdentifiers: taskIds, collectionId: collectionId) self.taskList.append(groupTask) for task in tasks { task.resume() } NotificationCenter.default.post(name: VideoMarksConstants.DownloadTaskStart, object: nil) } func downloadTaskFor(taskId: Int) -> DownloadTask? { for downloadTask in self.taskList { if downloadTask.haveTask(taskId: taskId) { return downloadTask } } return nil } func taskIndexFor(taskId: Int) -> Int? { for (index, downloadTask) in self.taskList.enumerated() { if downloadTask.haveTask(taskId: taskId) { return index } } return nil } func singleFileDidFinishDownload(at location: URL) { if let documentURL = VideoMarksConstants.documentURL() { let fileManager = FileManager.default let destURL = documentURL.appendingPathComponent("tmp.mp4") print("destURL is \(destURL)") if fileManager.fileExists(atPath: destURL.path) { do { try fileManager.removeItem(at: destURL) } catch { print("remove item error \(error)") } } do { try fileManager.moveItem(at: location, to: destURL) print("move item to destURL \(destURL)") } catch { print("error download \(error)") } } } func subFile(atIndex taskIndex: Int, didFinishDownloadTo location: URL) { if let documentURL = VideoMarksConstants.documentURL() { let fileManager = FileManager.default let combineDir = documentURL.appendingPathComponent("tmpCombine", isDirectory: true) if !fileManager.fileExists(atPath: combineDir.path) { do { print("文件夹不存在 创建文件夹") try fileManager.createDirectory(at: combineDir, withIntermediateDirectories: false, attributes: nil) } catch { print("创建文件夹失败 \(error)") } } print("combineDir is \(combineDir)") let videoURL = combineDir.appendingPathComponent("\(taskIndex).mp4") if fileManager.fileExists(atPath: videoURL.path) { do { print("删除已存在 \(videoURL) 的文件") try fileManager.removeItem(at: videoURL) } catch { print("remove item error \(error)") } } do { print("move item to destURL \(videoURL)") try fileManager.moveItem(at: location, to: videoURL) } catch { print("error download \(error)") } } } // MARK: - 合并所有视频片段 func combineAllVideoFragment(withTask task: DownloadTask) { print("合并所有视频片段") self.backgroundUpdateTask = beginBackgroundUpdateTask() guard let documentURL = VideoMarksConstants.documentURL() else { return } let fileManager = FileManager.default let combineDir = documentURL.appendingPathComponent("tmpCombine", isDirectory: true); let composition = AVMutableComposition() let videoTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid) let audioTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid) var previousTime = kCMTimeZero for i in 0 ..< task.subTaskCount() { let videoURL = combineDir.appendingPathComponent("\(i).mp4") let asset = AVAsset(url: videoURL) do { print("加入asset \(videoURL)") // Debug let audios = asset.tracks(withMediaType: AVMediaTypeAudio) let videos = asset.tracks(withMediaType: AVMediaTypeVideo) print("audio tracks is \(audios) videos is \(videos)") print("tracks is \(asset.tracks)") guard audios.count > 0 && videos.count > 0 else { print("找不到视频") return } try videoTrack.insertTimeRange(CMTimeRange(start: kCMTimeZero, end: asset.duration), of: asset.tracks(withMediaType: AVMediaTypeVideo)[0], at: previousTime) try audioTrack.insertTimeRange(CMTimeRange(start: kCMTimeZero, end: asset.duration), of: asset.tracks(withMediaType: AVMediaTypeAudio)[0], at: previousTime) } catch { print("加入失败 \(error)") } previousTime = CMTimeAdd(previousTime, asset.duration) } // 创建exportor guard let exportor = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough) else { print("创建ExportSession 失败") return } let exportURL = documentURL.appendingPathComponent("tmp.mp4") if fileManager.fileExists(atPath: exportURL.path) { do { print("文件已存在 删除文件") try fileManager.removeItem(at: exportURL) } catch { print("删除文件失败 \(error)") } } exportor.outputURL = exportURL exportor.outputFileType = AVFileTypeMPEG4 exportor.exportAsynchronously { DispatchQueue.main.async(execute: { if exportor.status == .completed { print("合并成功") self.saveVideoToPhotos(inTask: task) // MARK: 标记合并成功 self.clearUpTmpFiles() } else { print("导出失败") } }) } endBackgroundUpdateTask() } // MARK: - 合并后的清理工作 func clearUpTmpFiles() { guard let documentURL = VideoMarksConstants.documentURL() else { return } DispatchQueue.global(qos: DispatchQoS.QoSClass.utility).async { let fileManager = FileManager.default let combineDir = documentURL.appendingPathComponent("tmpCombine", isDirectory: true) if fileManager.fileExists(atPath: combineDir.path) { do { print("开始删除缓存文件") try fileManager.removeItem(at: combineDir) } catch { print("删除缓存失败 \(error)") } print("完成清理") } } } // MARK: - 保存视频到相册 func saveVideoToPhotos(inTask task: DownloadTask) { print("保存视频到相册") guard let documentURL = VideoMarksConstants.documentURL() else { return } let fileURL = documentURL.appendingPathComponent("tmp.mp4") PHPhotoLibrary.shared().performChanges({ if let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL) { let asset = assetChangeRequest.placeholderForCreatedAsset! let assets = NSArray(object: asset) if let collection = task.fetchAssetCollection(collectionId: task.collectionId) { let collectionChangeRequest = PHAssetCollectionChangeRequest(for: collection) collectionChangeRequest?.addAssets(assets) } } }) { (success, error) in guard success == true else { print("download Video error \(error)") return } do { try FileManager.default.removeItem(at: fileURL) } catch { print("error delete") } } if let indexTask = self.taskList.index(of: task) { print("完成任务 删除task") self.taskList.remove(at: indexTask) } NotificationCenter.default.post(name: VideoMarksConstants.DownloadTaskFinish, object: nil) } // MARK: - 后台任务 var backgroundUpdateTask = UIBackgroundTaskInvalid func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { return UIApplication.shared.beginBackgroundTask(expirationHandler: { self.endBackgroundUpdateTask() }) } func endBackgroundUpdateTask() { UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask) self.backgroundUpdateTask = UIBackgroundTaskInvalid } } extension TaskManager: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let task = self.downloadTaskFor(taskId: downloadTask.taskIdentifier) else { return } task.increaseSubTaskComplteCount() switch task.type { case .singleFile: self.singleFileDidFinishDownload(at: location) self.saveVideoToPhotos(inTask: task) case .groupFile: let taskIndex = task.subTaskIndex(withTaskId: downloadTask.taskIdentifier) self.subFile(atIndex: taskIndex, didFinishDownloadTo: location) if task.isDownloadTaskCompleted { self.combineAllVideoFragment(withTask: task) } } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { guard let task = self.downloadTaskFor(taskId: downloadTask.taskIdentifier) else { return } let subProgress = task.fetchSubProgress(withTaskId: downloadTask.taskIdentifier) subProgress.totalUnitCount = totalBytesExpectedToWrite subProgress.completedUnitCount = totalBytesWritten let progressInfo = ["task": task,] NotificationCenter.default.post(name: VideoMarksConstants.DownloadTaskProgress, object: progressInfo) } } // MARK: - NSURLSessionDelegate extension TaskManager: URLSessionDelegate { func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { if let completionHandler = appDelegate.backgroundSessionCompletionHandler { appDelegate.backgroundSessionCompletionHandler = nil DispatchQueue.main.async(execute: { completionHandler() }) } } } }
mit
56593b915b78afb5eb30752e62acbb2e
38.793605
176
0.58295
5.546596
false
false
false
false
Touchwonders/Transition
Examples/NavigationTransitionsExample/Transition/Transition/FadeTransition.swift
1
3257
// // MIT License // // Copyright (c) 2017 Touchwonders B.V. // // 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 import Transition class FadeTransition: TransitionAnimation { private var operation: TransitionOperation private var operationContext: TransitionOperationContext! private var context: UIViewControllerContextTransitioning! init(for operation: TransitionOperation) { self.operation = operation } func setup(in operationContext: TransitionOperationContext) { self.operationContext = operationContext context = operationContext.context context.containerView.backgroundColor = UIColor(red: 82.0/255.0, green: 77.0/255.0, blue: 153.0/255.0, alpha: 1.0) context.toView.frame = context.finalFrame(for: context.toViewController) if isPresenting { context.containerView.addSubview(context.toView) } else { context.containerView.insertSubview(context.toView, at: 0) } context.toView.alpha = 0 } func completion(position: UIViewAnimatingPosition) { context.fromView.alpha = 1.0 if position != .end { context.toView.removeFromSuperview() } } var layers: [AnimationLayer] { return [ AnimationLayer(range: AnimationRange(start: 0.0, end: 0.2), timingParameters: AnimationTimingParameters(controlPoint1: CGPoint(x: 0.0, y: 0.0), controlPoint2: CGPoint(x: 1.0, y: 1.0)), animation: earlyFadeOut, identifier: "earlyFadeOut"), AnimationLayer(range: AnimationRange(start: 0.1, end: 0.4), timingParameters: AnimationTimingParameters(controlPoint1: CGPoint(x: 0.0, y: 0.0), controlPoint2: CGPoint(x: 1.0, y: 1.0)), animation: delayedFadeIn, identifier: "delayedFadeIn") ] } var isPresenting: Bool { return operationContext.operation.isPresenting } var earlyFadeOut: AnimationFunction { return { self.context.fromView.alpha = 0 } } var delayedFadeIn: AnimationFunction { return { self.context.toView.alpha = 1 } } }
mit
64aebb663c8dde0b5c26c618912afc3e
39.209877
251
0.67946
4.568022
false
false
false
false
congncif/IDMCore
IDMCore/Classes/SynchronizedArray.swift
1
18047
// // SynchronizedArray.swift // IDMCore // // Created by FOLY on 12/10/18. // Thanks to Basem Emara import Foundation /// A thread-safe array. public final class SynchronizedArray<Element> { fileprivate var queue: DispatchQueue fileprivate var array = [Element]() public init(queue: DispatchQueue = DispatchQueue.concurrent, elements: [Element] = []) { self.queue = queue self.array = elements } } // MARK: - Properties public extension SynchronizedArray { /// The first element of the collection. var first: Element? { var result: Element? queue.sync { result = self.array.first } return result } /// The last element of the collection. var last: Element? { var result: Element? queue.sync { result = self.array.last } return result } /// The number of elements in the array. var count: Int { var result = 0 queue.sync { result = self.array.count } return result } /// A Boolean value indicating whether the collection is empty. var isEmpty: Bool { var result = false queue.sync { result = self.array.isEmpty } return result } /// A textual representation of the array and its elements. var description: String { var result = "" queue.sync { result = self.array.description } return result } } // MARK: - Immutable public extension SynchronizedArray { /// Returns the first element of the sequence that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Returns: The first element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate. func first(where predicate: (Element) -> Bool) -> Element? { var result: Element? queue.sync { result = self.array.first(where: predicate) } return result } /// Returns the last element of the sequence that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Returns: The last element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate. func last(where predicate: (Element) -> Bool) -> Element? { var result: Element? queue.sync { result = self.array.last(where: predicate) } return result } /// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. /// - Returns: An array of the elements that includeElement allowed. func filter(_ isIncluded: @escaping (Element) -> Bool) -> SynchronizedArray { var result: SynchronizedArray? queue.sync { result = SynchronizedArray(queue: self.queue, elements: self.array.filter(isIncluded)) } return result ?? self } /// Returns the first index in which an element of the collection satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil. func firstIndex(where predicate: (Element) -> Bool) -> Int? { var result: Int? queue.sync { result = self.array.firstIndex(where: predicate) } return result } /// Returns the elements of the collection, sorted using the given predicate as the comparison between elements. /// /// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. /// - Returns: A sorted array of the collection’s elements. func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> SynchronizedArray { var result: SynchronizedArray? queue.sync { result = SynchronizedArray(queue: self.queue, elements: self.array.sorted(by: areInIncreasingOrder)) } return result ?? self } /// Returns an array containing the results of mapping the given closure over the sequence’s elements. /// /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence. func map<ElementOfResult>(_ transform: @escaping (Element) -> ElementOfResult) -> [ElementOfResult] { var result = [ElementOfResult]() queue.sync { result = self.array.map(transform) } return result } /// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence. /// /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence. func compactMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] { var result = [ElementOfResult]() queue.sync { result = self.array.compactMap(transform) } return result } /// Returns the result of combining the elements of the sequence using the given closure. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult. func reduce<ElementOfResult>(_ initialResult: ElementOfResult, _ nextPartialResult: @escaping (ElementOfResult, Element) -> ElementOfResult) -> ElementOfResult { var result: ElementOfResult? queue.sync { result = self.array.reduce(initialResult, nextPartialResult) } return result ?? initialResult } /// Returns the result of combining the elements of the sequence using the given closure. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult. func reduce<ElementOfResult>(into initialResult: ElementOfResult, _ updateAccumulatingResult: @escaping (inout ElementOfResult, Element) -> Void) -> ElementOfResult { var result: ElementOfResult? queue.sync { result = self.array.reduce(into: initialResult, updateAccumulatingResult) } return result ?? initialResult } /// Calls the given closure on each element in the sequence in the same order as a for-in loop. /// /// - Parameter body: A closure that takes an element of the sequence as a parameter. func forEach(_ body: (Element) -> Void) { queue.sync { self.array.forEach(body) } } /// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false. func contains(where predicate: (Element) -> Bool) -> Bool { var result = false queue.sync { result = self.array.contains(where: predicate) } return result } /// Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition. /// - Returns: true if the sequence contains only elements that satisfy predicate; otherwise, false. func allSatisfy(_ predicate: (Element) -> Bool) -> Bool { var result = false queue.sync { result = self.array.allSatisfy(predicate) } return result } } // MARK: - Mutable public extension SynchronizedArray { /// Adds a new element at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The element to append to the array. /// - completion: The block to execute when completed. func append(_ element: Element, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.append(element) DispatchQueue.main.async { completion?() } } } /// Adds new elements at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The elements to append to the array. /// - completion: The block to execute when completed. func append(_ elements: [Element], completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array += elements DispatchQueue.main.async { completion?() } } } /// Inserts a new element at the specified position. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The new element to insert into the array. /// - index: The position at which to insert the new element. /// - completion: The block to execute when completed. func insert(_ element: Element, at index: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.insert(element, at: index) DispatchQueue.main.async { completion?() } } } /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed element. func removeFirst(completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.removeFirst() DispatchQueue.main.async { completion?(element) } } } /// Removes the specified number of elements from the beginning of the collection. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - k: The number of elements to remove from the collection. /// - completion: The block to execute when remove completed. func removeFirst(_ k: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { defer { DispatchQueue.main.async { completion?() } } guard 0...self.array.count ~= k else { return } self.array.removeFirst(k) } } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed element. func removeLast(completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.removeLast() DispatchQueue.main.async { completion?(element) } } } /// Removes the specified number of elements from the end of the collection. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - k: The number of elements to remove from the collection. /// - completion: The block to execute when remove completed. func removeLast(_ k: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { defer { DispatchQueue.main.async { completion?() } } guard 0...self.array.count ~= k else { return } self.array.removeLast(k) } } /// Removes and returns the element at the specified position. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - index: The position of the element to remove. /// - completion: The handler with the removed element. func remove(at index: Int, completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.remove(at: index) DispatchQueue.main.async { completion?(element) } } } /// Removes and returns the elements that meet the criteria. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - completion: The handler with the removed elements. func remove(where predicate: @escaping (Element) -> Bool, completion: (([Element]) -> Void)? = nil) { queue.async(flags: .barrier) { var elements = [Element]() while let index = self.array.firstIndex(where: predicate) { elements.append(self.array.remove(at: index)) } DispatchQueue.main.async { completion?(elements) } } } /// Removes all elements from the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed elements. func removeAll(completion: (([Element]) -> Void)? = nil) { queue.async(flags: .barrier) { let elements = self.array self.array.removeAll() DispatchQueue.main.async { completion?(elements) } } } } public extension SynchronizedArray { /// Accesses the element at the specified position if it exists. /// /// - Parameter index: The position of the element to access. /// - Returns: optional element if it exists. subscript(index: Int) -> Element? { get { var result: Element? queue.sync { result = self.array[safe: index] } return result } set { guard let newValue = newValue else { return } queue.async(flags: .barrier) { self.array[index] = newValue } } } } // MARK: - Equatable public extension SynchronizedArray where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the given element. /// /// - Parameter element: The element to find in the sequence. /// - Returns: true if the element was found in the sequence; otherwise, false. func contains(_ element: Element) -> Bool { var result = false queue.sync { result = self.array.contains(element) } return result } /// Removes the specified element. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter element: An element to search for in the collection. func remove(_ element: Element, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.remove(element) DispatchQueue.main.async { completion?() } } } /// Removes the specified element. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to remove from. /// - right: An element to search for in the collection. static func -= (left: inout SynchronizedArray, right: Element) { left.remove(right) } } // MARK: - Infix operators public extension SynchronizedArray { /// Adds a new element at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to append to. /// - right: The element to append to the array. static func += (left: inout SynchronizedArray, right: Element) { left.append(right) } /// Adds new elements at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to append to. /// - right: The elements to append to the array. static func += (left: inout SynchronizedArray, right: [Element]) { left.append(right) } } private extension SynchronizedArray { // swiftlint:disable file_length } extension Array where Element: Equatable { mutating func remove(_ element: Element) { guard let index = firstIndex(of: element) else { return } remove(at: index) } } extension Collection { subscript(safe index: Index) -> Element? { // http://www.vadimbulavin.com/handling-out-of-bounds-exception/ return indices.contains(index) ? self[index] : nil } }
mit
a9fa4ad1c66ec535a290a45ff888a018
40.006818
226
0.64773
4.746909
false
false
false
false
cfilipov/MuscleBook
MuscleBook/ValueCoding.swift
1
3231
// // ValueCoding.swift // ValueCoding // // Created by Daniel Thorpe on 11/10/2015. // // https://github.com/danthorpe/YapDatabaseExtensions // import Foundation // MARK: - ArchiverType /** A generic protocol for classes which can archive/unarchive value types. */ public protocol CodingType { associatedtype ValueType /// The value type which is being encoded/decoded var value: ValueType { get } /// Required initializer receiving the wrapped value type. init(_: ValueType) } /** A generic protocol for value types which require archiving. */ public protocol ValueCoding { associatedtype Coder: CodingType } // MARK: - Protocol Extensions extension CodingType where ValueType: ValueCoding, ValueType.Coder == Self { internal static func decode(object: AnyObject?) -> ValueType? { return (object as? Self)?.value } internal static func decode<S: SequenceType where S.Generator.Element: AnyObject>(objects: S?) -> [ValueType] { return objects?.flatMap(decode) ?? [] } } extension SequenceType where Generator.Element: CodingType { /// Access the values from a sequence of archives. public var values: [Generator.Element.ValueType] { return map { $0.value } } } /** Static methods for decoding `AnyObject` to Self, and returning encoded object of Self. */ extension ValueCoding where Coder: NSCoding, Coder.ValueType == Self { /** Decodes the value from a single archive, if possible. For example let foo = Foo.decode(decoder.decodeObjectForKey("foo")) - parameter object: an optional `AnyObject` which if not nil should be of `Archiver` type. - returns: an optional `Self` */ public static func decode(object: AnyObject?) -> Self? { return Coder.decode(object) } /** Decodes the values from a sequence of archives, if possible For example let foos = Foo.decode(decoder.decodeObjectForKey("foos") as? [AnyObject]) - parameter objects: a `SequenceType` of `AnyObject`. - returns: the array of values which were able to be unarchived. */ public static func decode<S: SequenceType where S.Generator.Element: AnyObject>(objects: S?) -> [Self] { return Coder.decode(objects) } /** Encodes the value type into its Archvier. Typically this would be used inside of `encodeWithCoder:` when the value is composed inside another `ValueCoding` or `NSCoding` type. For example: encoder.encodeObject(foo.encoded, forKey: "foo") */ public var encoded: Coder { return Coder(self) } } extension SequenceType where Generator.Element: ValueCoding, Generator.Element.Coder: NSCoding, Generator.Element.Coder.ValueType == Generator.Element { /** Encodes the sequence of value types into a sequence of archives. Typically this would be used inside of `encodeWithCoder:` when a sequence of values is composed inside another `ValueCoding` or `NSCoding` type. For example: encoder.encodeObject(foos.encoded, forKey: "foos") */ public var encoded: [Generator.Element.Coder] { return map { $0.encoded } } }
gpl-3.0
d106667b30b5b2e9875769d6400580f1
23.477273
115
0.675642
4.426027
false
false
false
false
pohl/Crow
Css.swift
1
9791
// // Css.swift // Crow // // A simple parser for a tiny subset of CSS. // // To support more CSS syntax, it would probably be easiest to replace this // hand-rolled parser with one based on a library or parser generator. // // Created by Pohl Longsine on 8/27/14. // Copyright (c) 2014 the screaming organization. All rights reserved. // import Foundation public struct Stylesheet { public let rules: [Rule] public var description: String { return "stylesheet" } } public struct Rule { public let selectors: [Selector] public let declarations: [Declaration] } public enum Selector { case Simple(SimpleSelector) } public struct SimpleSelector { public var tagName: String? public var id: String? public var classes: [String] } public struct Declaration { public let name: String public let value: Value } public enum Value { case Keyword(String) case Length(Float, Unit) case Color(UInt8, UInt8, UInt8, UInt8) // RGBA } public enum Unit { case Px } public typealias Specificity = (Int, Int, Int) extension Selector { public var specificity: Specificity { switch self { case .Simple(let simple): let a = simple.id == nil ? 0 : 1 let b = simple.classes.count let c = simple.tagName == nil ? 0 : 1 return Specificity(a, b, c) } } public var description: String { switch self { case .Simple(let simple): return simple.description } } } extension SimpleSelector { public var description: String { switch (self.tagName, self.id) { case (.Some(let t), .None): return "t:\(t), \(classes)" case (.None, .Some(let i)): return "i:\(i), \(classes)" case (.Some(let t), .Some(let i)): return "t: \(t), i:\(i), \(classes)" case (.None, .None): return "\(classes)" } } } extension Value { // Return the size of a length in px, or zero for non-lengths. public func toPx() -> Float { switch self { case Length(let f, .Px): return f case _: return 0.0 } } } // Parse a whole CSS stylesheet. public func parseCss(source: String) -> Stylesheet { var parser = CssParser(pos: source.startIndex, input: source ) return Stylesheet(rules: parser.parseRules()) } struct CssParser { var pos: String.Index let input: String } extension CssParser { init(input: String) { self.input = input self.pos = self.input.startIndex } } extension CssParser { // Parse a list of rule sets, separated by optional whitespace. mutating func parseRules() -> [Rule] { var rules: [Rule] = [] while (true) { self.consumeWhitespace() if self.eof() { break } rules.append(self.parseRule()) } return rules; } // Parse a rule set: `<selectors> { <declarations> }`. mutating func parseRule() -> Rule { return Rule(selectors: self.parseSelectors(), declarations: self.parseDeclarations()) } // Parse a comma-separated list of selectors. mutating func parseSelectors() -> [Selector] { var selectors: [Selector] = [] outerLoop: while true { selectors.append(.Simple(self.parseSimpleSelector())) self.consumeWhitespace() let c = self.nextCharacter() switch c { case ",": self.consumeCharacter() self.consumeWhitespace() case "{": break outerLoop case _: assert(false, "Unexpected character \(c) in selector list") } } // Return selectors with highest specificity first, for use in matching. selectors.sort { $0 > $1 } return selectors } // Parse one simple selector, e.g.: `type#id.class1.class2.class3` mutating func parseSimpleSelector() -> SimpleSelector { var selector = SimpleSelector(tagName: nil, id: nil, classes: []) outerLoop: while !self.eof() { switch self.nextCharacter() { case "#": self.consumeCharacter() selector.id = self.parseIdentifier() case ".": self.consumeCharacter() selector.classes.append(self.parseIdentifier()) case "*": // universal selector self.consumeCharacter() case let c where validIdentifierChar(c): selector.tagName = self.parseIdentifier() case _: break outerLoop } } return selector; } // Parse a list of declarations enclosed in `{ ... }`. mutating func parseDeclarations() -> [Declaration] { let leftCurly = self.consumeCharacter(); assert(leftCurly == "{") var declarations: [Declaration] = [] while true { self.consumeWhitespace() if self.nextCharacter() == "}" { self.consumeCharacter() break } declarations.append(self.parseDeclaration()) } return declarations; } // Parse one `<property>: <value>;` declaration. mutating func parseDeclaration() -> Declaration { let propertyName = self.parseIdentifier() self.consumeWhitespace() let colon = self.consumeCharacter() assert(colon == ":") self.consumeWhitespace() let value = self.parseValue() self.consumeWhitespace() let semicolon = self.consumeCharacter() assert(semicolon == ";") return Declaration (name: propertyName, value: value) } // Methods for parsing values: mutating func parseValue() -> Value { switch self.nextCharacter() { case "0"..."9": return self.parseLength() case "#": return self.parseColor() case _: return .Keyword(self.parseIdentifier()) } } mutating func parseLength() -> Value { return .Length(self.parseFloat(), self.parseUnit()) } mutating func parseFloat() -> Float { let s = self.consumeWhile() { switch $0 { case "0"..."9", ".": return true case _: return false } } var result: Float = 0.0 let success = NSScanner(string: s).scanFloat(&result) return Float(result) } mutating func parseUnit() -> Unit { switch self.parseIdentifier().lowercaseString { case "px": return .Px case _: assert(false, "unrecognized unit") } } mutating func parseColor() -> Value { let hash = self.consumeCharacter(); assert(hash == "#") return .Color(self.parseHexPair(), self.parseHexPair(), self.parseHexPair(), 255) } // Parse two hexadecimal digits. mutating func parseHexPair() -> UInt8 { let plusTwo = self.pos.successor().successor() let hexPairRange = Range(start: self.pos, end: plusTwo) let s = self.input.substringWithRange(hexPairRange) self.pos = plusTwo var result: CUnsignedInt = 0 let success = NSScanner(string: s).scanHexInt(&result) return UInt8(result) } // Parse a property name or keyword. mutating func parseIdentifier() -> String { return self.consumeWhile(validIdentifierChar) } // Consume and discard zero or more whitespace Character. mutating func consumeWhitespace() { self.consumeWhile( {$0.isMemberOf(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }) } // Consume Character until `test` returns false. mutating func consumeWhile(test: Character -> Bool) -> String { var result = "" while !self.eof() && test(self.nextCharacter()) { result.append(consumeCharacter()) } return result } // Return the current Character, and advance self.pos to the next Character. mutating func consumeCharacter() -> Character { let result = input[self.pos] self.pos = self.pos.successor() return result } // Read the current Character without consuming it. func nextCharacter() -> Character { return input[self.pos] } // Return true if all input is consumed. func eof() -> Bool { return self.pos >= self.input.endIndex } } func validIdentifierChar(c: Character) -> Bool { switch c { case "a"..."z", "A"..."Z", "0"..."9", "-", "_": return true // TODO: Include U+00A0 and higher. case _: return false } } func > (lhs:Specificity, rhs:Specificity) -> Bool { if lhs.0 == rhs.0 { if lhs.1 == rhs.1 { return lhs.2 > rhs.2 } else { return lhs.1 > rhs.1 } } else { return lhs.0 > rhs.0 } } func > (lhs: Selector, rhs: Selector) -> Bool { return lhs.specificity > rhs.specificity } public func == (lhs: Value, rhs: Value) -> Bool { switch (lhs, rhs) { case (.Keyword(let k1), .Keyword(let k2)): return k1 == k2 case (.Length(let f1, let u1), .Length(let f2, let u2)): return f1 == f2 && u1 == u2 case (.Color(let r1, let g1, let b1, let a1), .Color(let r2, let g2, let b2, let a2)): return r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2 default: return false } } public func == (lhs: SimpleSelector, rhs: SimpleSelector) -> Bool { return lhs.tagName == rhs.tagName && lhs.id == rhs.id && lhs.classes == rhs.classes }
mit
362a0eb76575db341c2b39aaa2ef2dc5
26.974286
99
0.565009
4.35349
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/viewcontrollers/account/CreateHDMAccountViewController.swift
1
3195
// // CreateHDAccountViewController.swift // chance_btc_wallet // // Created by Chance on 2016/12/2. // Copyright © 2016年 chance. All rights reserved. // import UIKit class CreateHDAccountViewController: UIViewController { /// MARK: - 成员变量 @IBOutlet var buttonConfirm: UIButton! @IBOutlet var labelTextNickname: CHLabelTextField! @IBOutlet var labelTitle: UILabel! override func viewDidLoad() { super.viewDidLoad() self.setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 控制器方法 extension CreateHDAccountViewController { func setupUI() { self.navigationItem.title = "Create Acount".localized() self.labelTitle.text = "Create HD Acount".localized() self.labelTextNickname.title = "Account Nickname".localized() self.labelTextNickname.placeholder = "Give your account a nickname".localized() self.labelTextNickname.textField?.keyboardType = .default self.labelTextNickname.delegate = self self.buttonConfirm.setTitle("Create".localized(), for: [.normal]) } //检测输入值是否合法 func checkValue() -> Bool { if self.labelTextNickname.text.isEmpty { SVProgressHUD.showInfo(withStatus: "Username is empty".localized()) return false } return true } /** 点击确认按钮 - parameter sender: */ @IBAction func handleConfirmPress(_ sender: AnyObject?) { if self.checkValue() { //创建默认HD账户 let nickName = self.labelTextNickname.text guard let account = CHBTCWallet.sharedInstance.createHDAccount(by: nickName) else { SVProgressHUD.showError(withStatus: "Create wallet account failed".localized()) return } CHBTCWallet.sharedInstance.selectedAccountIndex = account.index //同时记录钱包界面最新的用户索引位 WalletViewController.selectedCardIndex = account.index WalletViewController.scrollCardAnimated = true SVProgressHUD.showSuccess(withStatus: "Create account successfully!") _ = self.navigationController?.popViewController(animated: true) } } } // MARK: - 实现输入框代理方法 extension CreateHDAccountViewController: CHLabelTextFieldDelegate { func textFieldShouldReturn(_ ltf: CHLabelTextField) -> Bool { ltf.textField?.resignFirstResponder() return true } func textField(_ ltf: CHLabelTextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let maxCharOfName = 50 if(ltf.textField === self.labelTextNickname.textField) { if (range.location>(maxCharOfName - 1)) { return false } } return true; } }
mit
341a2b8abb8f52431070226ede6a3ca8
27.537037
128
0.610642
5.250426
false
false
false
false
hejeffery/JBridge
JBridge/JBridge/JBridge.swift
1
3615
// // JBridge.swift // JBridge // // Created by jhe.jeffery on 2017/5/2. // Copyright © 2017年 HeJeffery. All rights reserved. // import Foundation import UIKit import JavaScriptCore import FCUUID import AVFoundation class JBridge: NSObject, JBridgeProtocol { weak var jsContext: JSContext? weak var controller: UIViewController? weak var webView: UIWebView? func showAlert(_ title: String, message: String, left: String, right: String) { DispatchQueue.main.async { let alertView = UIAlertView.init(title: title == "null" ? "提示" : title, message: message, delegate: nil, cancelButtonTitle: left == "null" ? "取消" : left, otherButtonTitles: right == "null" ? "确定" : right) alertView.show() } } func showActionSheet(_ title: String, destructive: String, others: [String]) { DispatchQueue.main.async { let actionSheet = UIActionSheet.init(title: title == "null" ? "提示" : title, delegate: nil, cancelButtonTitle: "取消", destructiveButtonTitle: destructive == "null" ? nil : destructive) for item in others { actionSheet.addButton(withTitle: item) } guard let controller = self.controller else { return } actionSheet.show(in: controller.view) } } func fetchUUID() -> String { return UIDevice.current.uuid() } func fetchVendor() -> String { return FCUUID.uuidForVendor() } func fetchModel() -> String { return UIDevice.current.model } func fetchSystemVersion() -> String { return UIDevice.current.systemVersion } func fetchSystemName() -> String { return UIDevice.current.systemName } func call(_ number: String) { DispatchQueue.main.async { let callString = "tel://" + number self.webView?.loadRequest(URLRequest(url: URL.init(string: callString)!)) } } func sendSms(_ number: String) { DispatchQueue.main.async { let sendString = "sms://" + number self.webView?.loadRequest(URLRequest(url: URL.init(string: sendString)!)) } } func sendMail(_ mail: String) { DispatchQueue.main.async { let mailString = "mailto://" + mail self.webView?.loadRequest(URLRequest(url: URL.init(string: mailString)!)) } } func flashlight() { DispatchQueue.main.async { let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) if captureDevice!.isTorchAvailable { try! captureDevice!.lockForConfiguration() if captureDevice!.torchMode == .off { captureDevice!.torchMode = AVCaptureTorchMode.on } else { captureDevice!.torchMode = AVCaptureTorchMode.off } captureDevice!.unlockForConfiguration() } } } func locationInfo() { DispatchQueue.main.async { } } }
mit
1344fd2af84c8c408ca105a474b3442d
28.203252
115
0.510857
5.467275
false
false
false
false
amoriello/trust-line-ios
Trustline/AccountTableViewCell.swift
1
3432
// // AccountTableViewCell.swift // Trustline // // Created by matt on 11/10/2015. // Copyright © 2015 amoriello.hutti. All rights reserved. // import UIKit import DRCellSlideGestureRecognizer class AccountTableViewCell: UITableViewCell { typealias CellActionTriggeredHandler = (CDAccount) -> (Void) @IBOutlet weak var accountName: UILabel! @IBOutlet weak var login: UILabel! @IBOutlet weak var lastUse: UILabel! var keyboardTriggeredHandler: CellActionTriggeredHandler? var showPasswordTriggeredHandler: CellActionTriggeredHandler? var clipboardTriggeredHandler: CellActionTriggeredHandler? var account: CDAccount! { didSet { updateAccountViewCell() } } let greenColor = UIColor(red: 91/255.0, green: 220/255.0, blue: 88/255.0, alpha: 1) let blueColor = UIColor(red: 24/255.0, green: 182/255.0, blue: 222/255.0, alpha: 1) let yellowColor = UIColor(red: 254/255.0, green: 217/255.0, blue: 56/255.0, alpha: 1) override func awakeFromNib() { super.awakeFromNib() // Initialization code addAnimationToCell() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } private func updateAccountViewCell() { accountName.text = account.title if let _ = account.login { login.text = "[email protected]" } else { login.text = "" } let usages = Array(account.usages).sort { $0.date.timeIntervalSinceReferenceDate < $1.date.timeIntervalSinceReferenceDate } if usages.count > 0 { let dateFormater = NSDateFormatter() dateFormater.dateFormat = "MMM, d 'at' HH:mm" lastUse.text = dateFormater.stringFromDate(usages.last!.date) } else { lastUse.text = "Nerver used" } } private func addAnimationToCell() { let slideGestureRecognizer = DRCellSlideGestureRecognizer(); let sendKeystrokesAction = DRCellSlideAction(forFraction: 0.45) sendKeystrokesAction.elasticity = 10 sendKeystrokesAction.icon = UIImage(named: "keyboard") sendKeystrokesAction.activeBackgroundColor = greenColor sendKeystrokesAction.didTriggerBlock = {(tableview, indexPath) in if let handler = self.keyboardTriggeredHandler { handler(self.account) } } let showPasswordAction = DRCellSlideAction(forFraction: -0.35) showPasswordAction.activeBackgroundColor = blueColor showPasswordAction.icon = UIImage(named: "visible") showPasswordAction.elasticity = 10 showPasswordAction.didTriggerBlock = {(tableView, indexPath) in if let handler = self.showPasswordTriggeredHandler { handler(self.account) } } let copyToClipboardAction = DRCellSlideAction(forFraction: -0.55) copyToClipboardAction.activeBackgroundColor = yellowColor copyToClipboardAction.icon = UIImage(named: "clipboard") copyToClipboardAction.elasticity = 10 copyToClipboardAction.didTriggerBlock = {(tableView, indexPath) in if let handler = self.clipboardTriggeredHandler { handler(self.account) } } slideGestureRecognizer.addActions(sendKeystrokesAction) slideGestureRecognizer.addActions(showPasswordAction) slideGestureRecognizer.addActions(copyToClipboardAction) self.addGestureRecognizer(slideGestureRecognizer) } }
mit
40394b35e09b733d89f7c3f2246a3cd0
29.096491
88
0.711163
4.568575
false
false
false
false
berishaerblin/Attendance
Attendance/ProfessorProfileViewController.swift
1
9982
// // ProfessorProfileViewController.swift // Attendance // // Created by Erblin Berisha on 8/15/17. // Copyright © 2017 Erblin Berisha. All rights reserved. // import UIKit import SwiftKeychainWrapper import CoreData class ProfessorProfileViewController: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! let container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer var mainVar: String? var subjectToShow: Subjects? var values: Values! private var students = [ProfessorStudents]() var searchController: UISearchController! var inSearchMode = false override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self searchBar.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) mainVar = UserDefaults.standard.string(forKey: "currentSubject") self.navigationItem.title = mainVar if let context = container?.viewContext, let nameToSearch = mainVar { subjectToShow = Subjects.find(theSubject: nameToSearch, in: context) } tableView.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return setNumberOfRowsInSection() } private func setNumberOfRowsInSection() -> Int{ students = configureTableViewFromStudnets() return students.count } func configureTableViewFromStudnets() -> [ProfessorStudents] { var result = [ProfessorStudents]() if let context = container?.viewContext { let request: NSFetchRequest<ProfessorStudents> = ProfessorStudents.fetchRequest() if !inSearchMode { if subjectToShow != nil { request.predicate = NSPredicate(format: "subjects = %@", subjectToShow!) result = (try! context.fetch(request)) } } else { if subjectToShow != nil, searchKey != nil { request.predicate = NSPredicate(format: "subjects = %@ and studentName contains[c] %@", subjectToShow!, searchKey!) result = (try! context.fetch(request)) } } } return result } var fetchedResultsController: NSFetchedResultsController<ProfessorStudents>? var searchKey: String? func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if !inSearchMode { fetchAttendance() } let cell = tableView.dequeueReusableCell(withIdentifier: "allStudents", for: indexPath) if let theStudent = fetchedResultsController?.object(at: indexPath) { print(theStudent.studentName ?? "nuk ka") cell.textLabel?.text = "\(theStudent.studentName!) \(theStudent.studentSurname!)" cell.detailTextLabel?.text = "\(theStudent.itWas)" } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let objc = fetchedResultsController?.fetchedObjects, objc.count > 0 { let student = objc[indexPath.row] performSegue(withIdentifier: "studentDetail", sender: student) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { view.endEditing(true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { inSearchMode = false //searchBar.showsCancelButton = false searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1) view.endEditing(true) tableView.reloadData() }else { //searchBar.showsCancelButton = true inSearchMode = true searchKey = searchBar.text!.lowercased() fetchAttendanceFromSearch(searchKey: searchKey!) //filter({$0.name.range(of: lower) != nil}) } } // func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { // searchBar.showsCancelButton = true // } // // func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { // searchBar.showsCancelButton = false // searchBar.resignFirstResponder() // } private func fetchAttendance() { if let context = container?.viewContext { let request: NSFetchRequest<ProfessorStudents> = ProfessorStudents.fetchRequest() if subjectToShow != nil { request.predicate = NSPredicate(format: "subjects = %@", subjectToShow!) } request.sortDescriptors = [NSSortDescriptor(key: "studentName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))] let fetched = NSFetchedResultsController<ProfessorStudents>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController = fetched do { try fetchedResultsController?.performFetch() } catch { print("NUk ka") } } } private func fetchAttendanceFromSearch(searchKey: String) { if let context = container?.viewContext { let request: NSFetchRequest<ProfessorStudents> = ProfessorStudents.fetchRequest() if subjectToShow != nil { request.predicate = NSPredicate(format: "subjects = %@ and studentName contains[c] %@", subjectToShow!, searchKey) } request.sortDescriptors = [NSSortDescriptor(key: "studentName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))] let fetched = NSFetchedResultsController<ProfessorStudents>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController = fetched do { try fetchedResultsController?.performFetch() } catch { print("NUk ka") } tableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "studentDetail" { if let destination = segue.destination as? StudentDetailViewController { if let student = sender as? ProfessorStudents { destination.student = student } } } } @IBAction func deleteAllStudentsTapped(_ sender: UIBarButtonItem) { handleTheDeletion() } private func handleTheDeletion() { let alert = UIAlertController(title: "Warning!", message: "Are you sure you want to delte all the students", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Yes, delete all", style: .destructive, handler: { [weak self] (action) in let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProfessorStudents") if self?.subjectToShow != nil { fetchRequest.predicate = NSPredicate(format: "subjects = %@", (self?.subjectToShow)!) } let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) if let context = self?.container?.viewContext { do { try context.execute(batchDeleteRequest) self?.tableView.reloadData() } catch { print("Could not delte the Items") } } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true) { [weak self] in self?.tableView.reloadData() } } @IBAction func signOutTapped(_ sender: UIBarButtonItem) { let _ = KeychainWrapper.standard.removeObject(forKey: KEY_UID) dismiss(animated: false, completion: nil) } // MARK: Supporting code public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections([sectionIndex], with: .fade) case .delete: tableView.deleteSections([sectionIndex], with: .fade) default: break } } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: tableView.reloadRows(at: [indexPath!], with: .fade) case .move: tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .fade) } } public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
gpl-3.0
aa944d50ddb899aa7925287fa659e836
38.607143
216
0.627192
5.683941
false
false
false
false
CH-HOWIE/Swift3_UITabBar_kvc
LoveFreshBeen_swift3.0/Classes/Home/View/AcitvitiesCell.swift
1
893
// // AcitvitiesCell.swift // LoveFreshBeen_swift3.0 // // Created by HOWIE-CH on 16/7/25. // Copyright © 2016年 Howie. All rights reserved. // import UIKit import SDWebImage class AcitvitiesCell: UITableViewCell { @IBOutlet weak var activitiesImage: UIImageView! var item: ActivitiesItem? { didSet { guard let tempItem = item else { return } let url = URL(string: tempItem.img!) activitiesImage.sd_setImage(with: url) } } override var frame: CGRect { didSet { var newFrame = frame newFrame.size.height -= 10 newFrame.size.width -= 20 newFrame.origin.x += 10 super.frame = newFrame } } }
apache-2.0
509b91fd322ce77a62a5424255010e49
18.777778
52
0.486517
4.734043
false
false
false
false
NxSoftware/Kata-Swift-BankOCR
Sources/Entry.swift
1
693
import Foundation struct Entry { let value: String let checksum: Int? var checksumIsInvalid: Bool { return checksum != 0 } var isIllegible: Bool { return value.contains("?") } init(value: String) { self.value = value checksum = Entry.calculateChecksum(for: value) } private static func calculateChecksum(for value: String) -> Int? { guard let numericValue = Int(value) else { return nil } var runningTotal = 0 for i in 0..<value.characters.count { let divisor = Int(pow(10, Double(i))) let digit = (numericValue / divisor) % 10 runningTotal += (digit * (i + 1)) } return runningTotal % 11 } }
mit
5247667be1ece93025fc3588190f9913
20
68
0.614719
3.96
false
false
false
false
HeMet/MVVMKit
MVVMKit/Utils/MulticastEvent.swift
1
1343
// // MulticastEvent.swift // MVVMKit // // Created by Евгений Губин on 20.06.15. // Copyright (c) 2015 GitHub. All rights reserved. // import Foundation public struct MulticastEvent<ContextType: AnyObject, ArgsType> { typealias Listener = (ContextType, ArgsType) -> () // there is no good way in swift to compare two closures (it's intentional) var listeners = [String: Listener]() weak var context: ContextType! public init(context: ContextType) { self.context = context } public mutating func register(tag: String, listener: Listener) { listeners[tag] = listener } public mutating func unregister(tag: String) { listeners.removeValueForKey(tag) } public func fire(args: ArgsType) { if let ctx = context { for (tag, listener) in listeners { listener(context, args) } } } } infix operator += { associativity left precedence 90 } infix operator -= { associativity left precedence 90 } public func += <CtxType, ArgsType>(var mce: MulticastEvent<CtxType, ArgsType>, ri: (String, (CtxType, ArgsType) -> ())) { mce.register(ri.0, listener: ri.1) } public func -= <CtxType, ArgsType>(var mce: MulticastEvent<CtxType, ArgsType>, tag: String) { mce.unregister(tag) }
mit
9ff78f3fb75dc8a28fc03af90185e49d
26.75
122
0.639369
4.057927
false
false
false
false
stormpath/stormpath-swift-example
Pods/Stormpath/Stormpath/Networking/StormpathError.swift
1
2555
// // StormpathError.swift // Stormpath // // Created by Edward Jiang on 2/9/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation let StormpathErrorDomain = "StormpathErrorDomain" /** StormpathError represents an error that can be passed back by a Stormpath API after a network response. It typically contains a HTTP status code, along with a localizedDescription of the specific error as passed back by the Framework Integration API. It also has two special error codes: 0 - Internal SDK Error (which should be reported to Stormpath as a bug) 1 - Unrecognized API Response (which means the Framework integration may not support this version of Stormpath) */ @objc(SPHStormpathError) public class StormpathError: NSError { /** Internal SDK Error represents errors that should not have occurred and are likely a bug with the Stormpath SDK. */ static let InternalSDKError = StormpathError(code: 0, description: "Internal SDK Error") /** API Response Error represents errors that occurred because the API didn't respond in a recognized way. Check that the SDK is configured to hit a correct endpoint, or that the Framework integration is a compatible version. */ static let APIResponseError = StormpathError(code: 1, description: "Unrecognized API Response") /** Converts a Framework Integration error response into a StormpathError object. */ class func error(from response: APIResponse) -> StormpathError { var description = "" if let errorDescription = response.json["message"].string { description = errorDescription } else if response.status == 401 { description = "Unauthorized" } else { return StormpathError.APIResponseError } return StormpathError(code: response.status, description: description) } /** Initializer for StormpathError - parameters: - code: HTTP Error code for the error. - description: Localized description of the error. */ init(code: Int, description: String) { var userInfo = [String: Any]() userInfo[NSLocalizedDescriptionKey] = description super.init(domain: StormpathErrorDomain, code: code, userInfo: userInfo) Logger.logError(self) } /// Not implemented, do not use. required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
e7801e2c3dc7588a05de1bfdbe70dc1a
32.605263
99
0.680893
5.057426
false
false
false
false
karivalkama/Agricola-Scripture-Editor
Pods/QRCode/QRCode/CIImageExtension.swift
1
1317
// // CIImageExtension.swift // QRCode // // Created by Jaiouch Yaman - Société ID-APPS on 18/12/2015. // Copyright © 2015 Alexander Schuch. All rights reserved. // import Foundation internal typealias Scale = (dx: CGFloat, dy: CGFloat) internal extension CIImage { /// Creates an `UIImage` with interpolation disabled and scaled given a scale property /// /// - parameter withScale: a given scale using to resize the result image /// /// - returns: an non-interpolated UIImage func nonInterpolatedImage(withScale scale: Scale = Scale(dx: 1, dy: 1)) -> UIImage? { guard let cgImage = CIContext(options: nil).createCGImage(self, from: self.extent) else { return nil } let size = CGSize(width: self.extent.size.width * scale.dx, height: self.extent.size.height * scale.dy) UIGraphicsBeginImageContextWithOptions(size, true, 0) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.interpolationQuality = .none context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.draw(cgImage, in: context.boundingBoxOfClipPath) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
mit
0feb63946dd7de4ead9592c062339ff1
36.542857
111
0.675038
4.322368
false
false
false
false
zisko/swift
stdlib/public/core/ManagedBuffer.swift
1
23602
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_bufferAllocate") internal func _swift_bufferAllocate( bufferType type: AnyClass, size: Int, alignmentMask: Int ) -> AnyObject /// A class whose instances contain a property of type `Header` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Header` and destroys /// any live elements in the `deinit` of a subclass. /// - Note: Subclasses must not have any stored properties; any storage /// needed should be included in `Header`. @_fixed_layout // FIXME(sil-serialize-all) open class ManagedBuffer<Header, Element> { /// Create a new instance of the most-derived class, calling /// `factory` on the partially-constructed object to generate /// an initial `Header`. @_inlineable // FIXME(sil-serialize-all) public final class func create( minimumCapacity: Int, makingHeaderWith factory: ( ManagedBuffer<Header, Element>) throws -> Header ) rethrows -> ManagedBuffer<Header, Element> { let p = Builtin.allocWithTailElems_1( self, minimumCapacity._builtinWordValue, Element.self) let initHeaderVal = try factory(p) p.headerAddress.initialize(to: initHeaderVal) // The _fixLifetime is not really needed, because p is used afterwards. // But let's be conservative and fix the lifetime after we use the // headerAddress. _fixLifetime(p) return p } /// The actual number of elements that can be stored in this object. /// /// This header may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @_inlineable // FIXME(sil-serialize-all) public final var capacity: Int { let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self)) let endAddr = storageAddr + _stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress return realCapacity } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final var headerAddress: UnsafeMutablePointer<Header> { return UnsafeMutablePointer<Header>(Builtin.addressof(&header)) } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(headerAddress, firstElementAddress) } /// The stored `Header` instance. /// /// During instance creation, in particular during /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s /// `header` property is as-yet uninitialized, and therefore /// reading the `header` property during `ManagedBuffer.create` is undefined. public final var header: Header //===--- internal/private API -------------------------------------------===// /// Make ordinary initialization unavailable @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_doNotCallMe: ()) { _sanityCheckFailure("Only initialize these by calling create") } } /// Contains a buffer object, and provides access to an instance of /// `Header` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Header` and any constructed `Element`s. /// /// Example Buffer Class /// -------------------- /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int, String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToHeader, pointerToElements) -> Void in /// pointerToElements.deinitialize(count: self.count) /// pointerToHeader.deinitialize(count: 1) /// } /// } /// /// // All properties are *computed* based on members of the Header /// var count: Int { /// return Manager(unsafeBufferObject: self).header.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).header.1 /// } /// } /// @_fixed_layout public struct ManagedBufferPointer<Header, Element> : Equatable { /// Create with new storage containing an initial `Header` and space /// for at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// - parameter factory: A function that produces the initial /// `Header` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) public init( bufferClass: AnyClass, minimumCapacity: Int, makingHeaderWith factory: (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header ) rethrows { self = ManagedBufferPointer( bufferClass: bufferClass, minimumCapacity: minimumCapacity) // initialize the header field try withUnsafeMutablePointerToHeader { $0.initialize(to: try factory( self.buffer, { ManagedBufferPointer(unsafeBufferObject: $0).capacity })) } // FIXME: workaround for <rdar://problem/18619176>. If we don't // access header somewhere, its addressor gets linked away _ = header } /// Manage the given `buffer`. /// /// - Precondition: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) public init(unsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._checkValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// Internal version for use by _ContiguousArrayBuffer where we know that we /// have a valid buffer class. /// This version of the init function gets called from /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get /// specialized with current versions of the compiler, we can't get rid of the /// _debugPreconditions in _checkValidBufferClass for any array. Since we know /// for the _ContiguousArrayBuffer that this check must always succeed we omit /// it in this specialized constructor. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// The stored `Header` instance. @_inlineable // FIXME(sil-serialize-all) public var header: Header { addressWithNativeOwner { return (UnsafePointer(_headerPointer), _nativeBuffer) } mutableAddressWithNativeOwner { return (_headerPointer, _nativeBuffer) } } /// Returns the object instance being used for storage. @_inlineable // FIXME(sil-serialize-all) public var buffer: AnyObject { return Builtin.castFromNativeObject(_nativeBuffer) } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @_inlineable // FIXME(sil-serialize-all) public var capacity: Int { return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only /// for the duration of the call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(_nativeBuffer) } return try body(_headerPointer, _elementPointer) } /// Returns `true` iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. @_inlineable // FIXME(sil-serialize-all) public mutating func isUniqueReference() -> Bool { return _isUnique(&_nativeBuffer) } //===--- internal/private API -------------------------------------------===// /// Create with new storage containing space for an initial `Header` /// and at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init( bufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true) _precondition( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") self.init( _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity) } /// Internal version for use by _ContiguousArrayBuffer.init where we know that /// we have a valid buffer class and that the capacity is >= 0. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init( _uncheckedBufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true) _sanityCheck( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") let totalSize = _My._elementOffset + minimumCapacity * MemoryLayout<Element>.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, size: totalSize, alignmentMask: _My._alignmentMask) self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer) } /// Manage the given `buffer`. /// /// - Note: It is an error to use the `header` property of the resulting /// instance unless it has been initialized. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_ buffer: ManagedBuffer<Header, Element>) { _nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } internal typealias _My = ManagedBufferPointer @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func _checkValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func _sanityCheckValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _sanityCheck( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _sanityCheck( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } /// The required alignment for allocations of this type, minus 1 @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _alignmentMask: Int { return max( MemoryLayout<_HeapObject>.alignment, max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1 } /// The actual number of bytes allocated for this object. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _capacityInBytes: Int { return _stdlib_malloc_size(_address) } /// The address of this instance in a convenient pointer-to-bytes form @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _address: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _headerOffset: Int { _onFastPath() return _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Header>.alignment) } /// An **unmanaged** pointer to the storage for the `Header` /// instance. Not safe to use without _fixLifetime calls to /// guarantee it doesn't dangle @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _headerPointer: UnsafeMutablePointer<Header> { _onFastPath() return (_address + _My._headerOffset).assumingMemoryBound( to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not /// safe to use without _fixLifetime calls to guarantee it doesn't /// dangle. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _elementPointer: UnsafeMutablePointer<Element> { _onFastPath() return (_address + _My._elementOffset).assumingMemoryBound( to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _elementOffset: Int { _onFastPath() return _roundUp( _headerOffset + MemoryLayout<Header>.size, toAlignment: MemoryLayout<Element>.alignment) } @_inlineable // FIXME(sil-serialize-all) public static func == ( lhs: ManagedBufferPointer, rhs: ManagedBufferPointer ) -> Bool { return lhs._address == rhs._address } @_versioned // FIXME(sil-serialize-all) internal var _nativeBuffer: Builtin.NativeObject } // FIXME: when our calling convention changes to pass self at +0, // inout should be dropped from the arguments to these functions. // FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too, // but currently does not. rdar://problem/29341361 /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean /// expression. In debug builds, an instance in the left-hand side of a `&&` /// or `||` expression may still be referenced when evaluating the right-hand /// side, inflating the instance's reference count. For example, this version /// of the `update(withValue)` method will re-copy `myStorage` on every call: /// /// // Copies too frequently: /// mutating func badUpdate(withValue value: T) { /// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to /// the left-hand side or store the result of the first expression in a local /// constant: /// /// mutating func goodUpdate(withValue value: T) { /// let shouldCopy = myStorage.shouldCopy /// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. @_inlineable public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool { return _isUnique(&object) } @_inlineable @_versioned internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool { return _isUniqueOrPinned(&object) } /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. If `object` is `nil`, the return value is `false`. @_inlineable public func isKnownUniquelyReferenced<T : AnyObject>( _ object: inout T? ) -> Bool { return _isUnique(&object) }
apache-2.0
98ce4d302a21562f6dfa2513d4d8cb29
38.076159
92
0.686933
4.605268
false
false
false
false
Nibelungc/My-Custom-Classes
Swift/WelcomePageController.swift
1
10727
// // WelcomePageController.swift // TranslateIt // // Created by Denis Baluev on 04/12/15. // Copyright © 2015 Denis Baluev. All rights reserved. // import UIKit class WelcomePageController: UIViewController { /** Public */ var closeButton: UIButton var finishButton: UIButton var pageControl: UIPageControl var statusBarHidden = true var resetPageOnWillAppear = true let viewControllers: [UIViewController] static var welcomeController: WelcomePageController? static var wasShown: Bool { get { return NSUserDefaults.standardUserDefaults().boolForKey(kWelcomePagecontrollerWasShown) } set { NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: kWelcomePagecontrollerWasShown) NSUserDefaults.standardUserDefaults().synchronize() } } /** Private */ static private let kWelcomePagecontrollerWasShown = "kWelcomePagecontrollerWasShown" private var initialViewController: UIViewController! private let pageController: UIPageViewController private let DefaultPadding: CGFloat = 8.0 private var tintColor: UIColor? // MARK: - Initialization convenience init(withImages images: [UIImage], tintColor: UIColor? = nil){ let controllersWithImages: [UIViewController] = images.map() { image in let viewController = UIViewController() let imageView = UIImageView(frame: viewController.view.bounds) imageView.contentMode = .ScaleAspectFit imageView.image = image imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] viewController.view.addSubview(imageView) return viewController } self.init(viewControllers: controllersWithImages, tintColor: tintColor) } init(viewControllers controllers: [UIViewController], tintColor tint: UIColor? = nil){ viewControllers = controllers.isEmpty ? [WelcomePageController.placeholderViewController()] : controllers pageControl = UIPageControl() finishButton = UIButton(type: .Custom) closeButton = UIButton(type: .Custom); pageController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) tintColor = tint super.init(nibName: nil, bundle: nil) self.configureUIElements() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (pageControl.currentPage != 0 && resetPageOnWillAppear){ pageController.setViewControllers([viewControllers.first!], direction: .Forward, animated: false, completion: nil) pageViewController(pageController, didFinishAnimating: true, previousViewControllers: [], transitionCompleted: true) } if statusBarHidden { UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Slide) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if statusBarHidden { UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Slide) } } // MARK: - Setup UI private func configureUIElements() { var windowTintColor: UIColor? = UIColor.blueColor() if let applicationWindow = UIApplication.sharedApplication().delegate?.window { windowTintColor = applicationWindow?.tintColor } view.tintColor = tintColor ?? windowTintColor /** PageController setup */ let firstControllerInArray = [viewControllers.first!] pageController.setViewControllers(firstControllerInArray, direction: .Forward, animated: true, completion: nil) pageController.view.frame = view.bounds pageController.delegate = self pageController.dataSource = self pageController.view.backgroundColor = UIColor.whiteColor() addChildViewController(pageController) view.addSubview(pageController.view) pageController.didMoveToParentViewController(self) /** PageControl setup */ pageControl.center = CGPointMake(view.center.x, CGRectGetMinY(view.bounds) + 20.0) pageControl.numberOfPages = viewControllers.count pageControl.pageIndicatorTintColor = UIColor(white: 1.0, alpha: 0.5) pageControl.currentPageIndicatorTintColor = view.tintColor view.addSubview(pageControl) /** Close button setup */ let closeButtonSize = CGSizeMake(44.0, 44.0) closeButton.frame = CGRectMake(CGRectGetMaxX(view.bounds) - closeButtonSize.width, 0, closeButtonSize.width, closeButtonSize.height); closeButton.addTarget(self, action: "dismiss:", forControlEvents: .TouchUpInside) closeButton.setImage(closeButtonImageForFrame(closeButton.bounds), forState: .Normal) view.addSubview(closeButton) /** Finish button setup */ let lastViewController = viewControllers.last! let padding = DefaultPadding * 3 let bottomPadding = DefaultPadding * 2 let buttonSize = CGSizeMake(CGRectGetWidth(view.bounds) - padding * 2, 50) finishButton.frame = CGRectMake(padding, CGRectGetHeight(view.bounds) - buttonSize.height - bottomPadding, buttonSize.width, buttonSize.height) finishButton.addTarget(self, action: "dismiss:", forControlEvents: .TouchUpInside) finishButton.setTitle("Начать пользоваться", forState: .Normal) finishButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) finishButton.titleLabel?.font = UIFont.systemFontOfSize(20.0) finishButton.layer.masksToBounds = true finishButton.layer.cornerRadius = CGRectGetMidY(finishButton.bounds) finishButton.backgroundColor = view.tintColor lastViewController.view.addSubview(finishButton) } // MARK: - Helper methods private func closeButtonImageForFrame(frame: CGRect) -> UIImage{ let padding = DefaultPadding + 5 let imageRect = CGRectInset(frame, padding, padding) UIGraphicsBeginImageContextWithOptions(frame.size, false, 2.0) let context = UIGraphicsGetCurrentContext()! drawLineFromPoint(CGPointMake(padding, padding), toPoint: CGPointMake(CGRectGetMaxX(imageRect), CGRectGetMaxY(imageRect)), withinContext: context) drawLineFromPoint(CGPointMake(CGRectGetMaxX(imageRect), padding), toPoint: CGPointMake(padding, CGRectGetMaxY(imageRect)), withinContext: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } private func drawLineFromPoint(point: CGPoint, toPoint endPoint: CGPoint, withinContext context: CGContextRef) { CGContextSetLineCap(context, .Round) CGContextSetStrokeColorWithColor(context, view.tintColor.CGColor) CGContextSetLineWidth(context, 3.0) CGContextMoveToPoint(context, point.x, point.y) CGContextAddLineToPoint(context, endPoint.x, endPoint.y) CGContextStrokePath(context) } private class func placeholderViewController(withText text: String = "You have to add at least one ViewController") -> UIViewController { let viewController = UIViewController.init() let messageLabel = UILabel.init(frame: viewController.view.bounds) messageLabel.textAlignment = .Center messageLabel.text = text viewController.view.addSubview(messageLabel) return viewController } private func viewControllerAtIndex(index: Int) -> UIViewController? { guard index >= 0 && index < viewControllers.count else { return nil } return viewControllers[index] } private func indexOfCurrentViewController() -> Int? { guard let currentViewControler = pageController.viewControllers?.last else { return nil } return viewControllers.indexOf(currentViewControler) } // MARK: - Actions /** Dismiss if was presented. Otherwise sets "initialViewController" as root for window */ @objc private func dismiss(animated: Bool = true){ if presentingViewController != nil { dismissViewControllerAnimated(true, completion: nil) } else { UIView.transitionWithView(view.window!, duration: 0.3, options: .TransitionCrossDissolve, animations: { self.view.window?.rootViewController = self.initialViewController }, completion: nil) } WelcomePageController.wasShown = true } } // MARK: - UIPageViewControllerDataSource extension WelcomePageController: UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.indexOf(viewController) else { return nil } return viewControllerAtIndex(index - 1) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.indexOf(viewController) else { return nil } return viewControllerAtIndex(index + 1) } } // MARK: - UIPageViewControllerDelegate extension WelcomePageController: UIPageViewControllerDelegate { func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { pageControl.currentPage = indexOfCurrentViewController() ?? 0 } } // MARK: - UIApplication extension extension UIApplication { func setRootViewController(rootVC: UIViewController, withWelcomePageController welcomeVC: WelcomePageController) { guard let applicationWindow = delegate?.window! else { print("[WelcomePageController]: Can't find application window") return } applicationWindow.rootViewController = WelcomePageController.wasShown ? rootVC : welcomeVC welcomeVC.initialViewController = rootVC WelcomePageController.welcomeController = welcomeVC } }
mit
bd34348bb0f2fa1b12d15921ea8caf94
40.828125
188
0.693594
5.84817
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Alamofire/Source/SessionManager.swift
41
38292
// // SessionManager.swift // // Copyright (c) 2014 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 creating and managing `Request` objects, as well as their underlying `NSURLSession`. open class SessionManager { // MARK: - Helper Types /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as /// associated values. /// /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with /// streaming information. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding /// error. public enum MultipartFormDataEncodingResult { case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) case failure(Error) } // MARK: - Properties /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use /// directly for any ad hoc requests. public static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. public static let defaultHTTPHeaders: HTTPHeaders = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` let userAgent: String = { if let info = Bundle.main.infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() let alamofireVersion: String = { guard let afInfo = Bundle(for: SessionManager.self).infoDictionary, let build = afInfo["CFBundleShortVersionString"] else { return "Unknown" } return "Alamofire/\(build)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() /// Default memory threshold used when encoding `MultipartFormData` in bytes. public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 /// The underlying session. public let session: URLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. open var startRequestsImmediately: Bool = true /// The request adapter called each time a new request is created. open var adapter: RequestAdapter? /// The request retrier called each time a request encounters an error to determine whether to retry the request. open var retrier: RequestRetrier? { get { return delegate.retrier } set { delegate.retrier = newValue } } /// The background completion handler closure provided by the UIApplicationDelegate /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation /// will automatically call the handler. /// /// If you need to handle your own events before the handler is called, then you need to override the /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. /// /// `nil` by default. open var backgroundCompletionHandler: (() -> Void)? let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) // MARK: - Lifecycle /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter configuration: The configuration used to construct the managed session. /// `URLSessionConfiguration.default` by default. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by /// default. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance. public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter session: The URL session. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionManager = self delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Data Request /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` /// and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult open func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) return request(encodedURLRequest) } catch { return request(originalRequest, failedWith: error) } } /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request. /// /// - returns: The created `DataRequest`. @discardableResult open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try urlRequest.asURLRequest() let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) let task = try originalTask.task(session: session, adapter: adapter, queue: queue) let request = DataRequest(session: session, requestTask: .data(originalTask, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return request(originalRequest, failedWith: error) } } // MARK: Private - Request Implementation private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { var requestTask: Request.RequestTask = .data(nil, nil) if let urlRequest = urlRequest { let originalTask = DataRequest.Requestable(urlRequest: urlRequest) requestTask = .data(originalTask, nil) } let underlyingError = error.underlyingAdaptError ?? error let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: request, with: underlyingError) } else { if startRequestsImmediately { request.resume() } } return request } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, /// `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return download(encodedURLRequest, to: destination) } catch { return download(nil, to: destination, failedWith: error) } } /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save /// them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try urlRequest.asURLRequest() return download(.request(urlRequest), to: destination) } catch { return download(nil, to: destination, failedWith: error) } } // MARK: Resume Data /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve /// the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for /// additional information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return download(.resumeData(resumeData), to: destination) } // MARK: Private - Download Implementation private func download( _ downloadable: DownloadRequest.Downloadable, to destination: DownloadRequest.DownloadFileDestination?) -> DownloadRequest { do { let task = try downloadable.task(session: session, adapter: adapter, queue: queue) let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) download.downloadDelegate.destination = destination delegate[task] = download if startRequestsImmediately { download.resume() } return download } catch { return download(downloadable, to: destination, failedWith: error) } } private func download( _ downloadable: DownloadRequest.Downloadable?, to destination: DownloadRequest.DownloadFileDestination?, failedWith error: Error) -> DownloadRequest { var downloadTask: Request.RequestTask = .download(nil, nil) if let downloadable = downloadable { downloadTask = .download(downloadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) download.downloadDelegate.destination = destination if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: download, with: underlyingError) } else { if startRequestsImmediately { download.resume() } } return download } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(fileURL, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.file(fileURL, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: Data /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(data, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.data(data, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: InputStream /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(stream, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.stream(stream, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, queue: DispatchQueue? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, queue: queue, encodingCompletion: encodingCompletion ) } catch { (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } } } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, queue: DispatchQueue? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { DispatchQueue.global(qos: .utility).async { let formData = MultipartFormData() multipartFormData(formData) var tempFileURL: URL? do { var urlRequestWithContentType = try urlRequest.asURLRequest() urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(data, with: urlRequestWithContentType), streamingFromDisk: false, streamFileURL: nil ) (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } } else { let fileManager = FileManager.default let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) tempFileURL = fileURL var directoryError: Error? // Create directory inside serial queue to ensure two threads don't do this in parallel self.queue.sync { do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { directoryError = error } } if let directoryError = directoryError { throw directoryError } try formData.writeEncodedData(to: fileURL) let upload = self.upload(fileURL, with: urlRequestWithContentType) // Cleanup the temp file once the upload is complete upload.delegate.queue.addOperation { do { try FileManager.default.removeItem(at: fileURL) } catch { // No-op } } (queue ?? DispatchQueue.main).async { let encodingResult = MultipartFormDataEncodingResult.success( request: upload, streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } } catch { // Cleanup the temp file in the event that the multipart form data encoding failed if let tempFileURL = tempFileURL { do { try FileManager.default.removeItem(at: tempFileURL) } catch { // No-op } } (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } } } } // MARK: Private - Upload Implementation private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { do { let task = try uploadable.task(session: session, adapter: adapter, queue: queue) let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) if case let .stream(inputStream, _) = uploadable { upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } } delegate[task] = upload if startRequestsImmediately { upload.resume() } return upload } catch { return upload(uploadable, failedWith: error) } } private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { var uploadTask: Request.RequestTask = .upload(nil, nil) if let uploadable = uploadable { uploadTask = .upload(uploadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: upload, with: underlyingError) } else { if startRequestsImmediately { upload.resume() } } return upload } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(withHostName hostName: String, port: Int) -> StreamRequest { return stream(.stream(hostName: hostName, port: port)) } // MARK: NetService /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(with netService: NetService) -> StreamRequest { return stream(.netService(netService)) } // MARK: Private - Stream Implementation @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { do { let task = try streamable.task(session: session, adapter: adapter, queue: queue) let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return stream(failedWith: error) } } @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(failedWith error: Error) -> StreamRequest { let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) if startRequestsImmediately { stream.resume() } return stream } #endif // MARK: - Internal - Retry Request func retry(_ request: Request) -> Bool { guard let originalTask = request.originalTask else { return false } do { let task = try originalTask.task(session: session, adapter: adapter, queue: queue) if let originalTask = request.task { delegate[originalTask] = nil // removes the old request to avoid endless growth } request.delegate.task = task // resets all task delegate data request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { DispatchQueue.utility.async { [weak self] in guard let strongSelf = self else { return } retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in guard let strongSelf = self else { return } guard shouldRetry else { if strongSelf.startRequestsImmediately { request.resume() } return } DispatchQueue.utility.after(timeDelay) { guard let strongSelf = self else { return } let retrySucceeded = strongSelf.retry(request) if retrySucceeded, let task = request.task { strongSelf.delegate[task] = request } else { if strongSelf.startRequestsImmediately { request.resume() } } } } } } }
mit
1100d3b31101b7792e121fd2eee6670d
41.593993
129
0.62389
5.415359
false
false
false
false
bmichotte/HSTracker
HSTracker/Logging/PlayerTurn.swift
2
499
// // PlayerTurn.swift // HSTracker // // Created by Benjamin Michotte on 15/10/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation struct PlayerTurn { let player: PlayerType let turn: Int } extension PlayerTurn: Hashable { var hashValue: Int { return player.rawValue.hashValue ^ turn.hashValue } static func == (lhs: PlayerTurn, rhs: PlayerTurn) -> Bool { return lhs.player == rhs.player && lhs.turn == rhs.turn } }
mit
c54490bafcc1b5569f1a0d29103fdc99
19.75
63
0.654618
3.92126
false
false
false
false
geekaurora/ReactiveListViewKit
Example/ReactiveListViewKitDemo/Data Layer/Feed.swift
1
2850
// // Feed.swift // ReactiveListViewKit // // Created by Cheng Zhang on 1/3/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import CZUtils import ReactiveListViewKit /// Model of feed class Feed: ReactiveListDiffable { let feedId: String let content: String? let imageInfo: ImageInfo? let user: User? var userHasLiked: Bool var likesCount: Int // MARK: - NSCopying func copy(with zone: NSZone? = nil) -> Any { return codableCopy(with: zone) } // MARK: - Decodable required init(from decoder: Decoder) throws { /** Direct decode. */ let values = try decoder.container(keyedBy: CodingKeys.self) feedId = try values.decode(String.self, forKey: .feedId) userHasLiked = try values.decode(Bool.self, forKey: .userHasLiked) user = try values.decode(User.self, forKey: .user) /** Nested decode. */ // e.g. content = dict["caption"]["content"] let caption = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .caption) content = try caption.decode(String.self, forKey: .content) let likes = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .likes) likesCount = try likes.decode(Int.self, forKey: .likesCount) let images = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .images) imageInfo = try images.decode(ImageInfo.self, forKey: .imageInfo) } } // MARK: - State extension Feed: State { func reduce(action: Action) { switch action { case let action as LikeFeedAction: // React to `LikeFeedEvent`: flip `userHasLiked` flag if action.feed.feedId == feedId { userHasLiked = !userHasLiked likesCount += userHasLiked ? 1 : -1 } default: break } } } // MARK: - Encodable extension Feed { enum CodingKeys: String, CodingKey { case feedId = "id" case userHasLiked = "user_has_liked" case caption = "caption" case content = "text" case images = "images" case imageInfo = "standard_resolution" case likes = "likes" case likesCount = "count" case user } func encode(to encoder: Encoder) throws { /** Direct encode. */ var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(feedId, forKey: .feedId) try container.encode(userHasLiked, forKey: .userHasLiked) try container.encode(user, forKey: .user) /** Nested encode. */ var caption = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .caption) try caption.encode(content, forKey: .content) var likes = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .likes) try likes.encode(likesCount, forKey: .likesCount) var images = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .images) try images.encode(imageInfo, forKey: .imageInfo) } }
mit
d0784b94c6a69d4ee24e3bd368eafc50
29.634409
88
0.675325
3.97905
false
false
false
false
hooman/swift
test/DebugInfo/inlinedAt.swift
3
1762
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -emit-verbose-sil -o - \ // RUN: | %FileCheck %s --check-prefix=CHECK-SIL // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | %FileCheck %s public var glob : Int = 0 @inline(never) public func hold(_ n : Int) { glob = n } #sourceLocation(file: "abc.swift", line: 100) @inline(__always) func h(_ k : Int) -> Int { // 101 hold(k) // 102 return k // 103 } #sourceLocation(file: "abc.swift", line: 200) @inline(__always) func g(_ j : Int) -> Int { // 201 hold(j) // 202 return h(j) // 203 } #sourceLocation(file: "abc.swift", line: 301) public func f(_ i : Int) -> Int { // 301 return g(i) // 302 } // CHECK-SIL: sil {{.*}}@$s9inlinedAt1fyS2iF : // CHECK-SIL-NOT: return // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1 // CHECK-SIL-SAME: line:101:10:in_prologue // CHECK-SIL-SAME: perf_inlined_at line:203:10 // CHECK-SIL-SAME: perf_inlined_at line:302:10 // CHECK: define {{.*}}@"$s9inlinedAt1fyS2iF"({{.*}}) // CHECK-NOT: ret // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value({{.*}}), !dbg ![[L1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK: ![[L3:.*]] = !DILocation(line: 302, column: 10, // CHECK-SAME: scope: ![[F:.*]]) // CHECK: ![[H:.*]] = distinct !DISubprogram(name: "h", // CHECK: ![[L1]] = !DILocation(line: 101, column: 8, scope: ![[H]], // CHECK-SAME: inlinedAt: ![[L2:.*]]) // CHECK: ![[L2]] = !DILocation(line: 203, column: 10, scope: ![[G]], // CHECK-SAME: inlinedAt: ![[L3]])
apache-2.0
7feecef7380b280d2dc71afd477e01fe
34.24
77
0.527242
3.011966
false
false
false
false
japango/chiayiapp
chiayi/chiayi/AppDelegate.swift
1
7536
// // AppDelegate.swift // chiayi // // Created by gosick on 2015/10/5. // Copyright © 2015年 gosick. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext 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: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.gosick.chiayi" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("chiayi", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
b8ce7aa4bb8a349d03446ed0c95eba5e
56.946154
291
0.732776
6.169533
false
false
false
false
mozilla-mobile/firefox-ios
Sync/Synchronizers/IndependentRecordSynchronizer.swift
2
6367
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Storage private let log = Logger.syncLogger class Uploader { /** * Upload just about anything that can be turned into something we can upload. */ func sequentialPosts<T>(_ items: [T], by: Int, lastTimestamp: Timestamp, storageOp: @escaping ([T], Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { // This needs to be a real Array, not an ArraySlice, // for the types to line up. let chunks = chunk(items, by: by).map { Array($0) } let start = deferMaybe(lastTimestamp) let perChunk: ([T], Timestamp) -> DeferredTimestamp = { (records, timestamp) in // TODO: detect interruptions -- clients uploading records during our sync -- // by using ifUnmodifiedSince. We can detect uploaded records since our download // (chain the download timestamp into this function), and we can detect uploads // that race with our own (chain download timestamps across 'walk' steps). // If we do that, we can also advance our last fetch timestamp after each chunk. log.debug("Uploading \(records.count) records.") return storageOp(records, timestamp) } return walk(chunks, start: start, f: perChunk) } } open class IndependentRecordSynchronizer: TimestampedSingleCollectionSynchronizer { private func reportApplyStatsWrap<T>(apply: @escaping (T) -> Success) -> (T) -> Success { return { record in return apply(record).bind({ result in var stats = SyncDownloadStats() stats.applied = 1 if result.isSuccess { stats.succeeded = 1 } else { stats.failed = 1 } self.statsSession.recordDownload(stats: stats) return Deferred(value: result) }) } } /** * Just like the usual applyIncomingToStorage, but doesn't fast-forward the timestamp. */ func applyIncomingRecords<T>(_ records: [T], apply: @escaping (T) -> Success) -> Success { if records.isEmpty { log.debug("No records; done applying.") return succeed() } return walk(records, f: reportApplyStatsWrap(apply: apply)) } func applyIncomingToStorage<T>(_ records: [T], fetched: Timestamp, apply: @escaping (T) -> Success) -> Success { func done() -> Success { log.debug("Bumping fetch timestamp to \(fetched).") self.lastFetched = fetched return succeed() } if records.isEmpty { log.debug("No records; done applying.") return done() } return walk(records, f: reportApplyStatsWrap(apply: apply)) >>> done } } extension TimestampedSingleCollectionSynchronizer { /** * On each chunk that we upload, we pass along the server modified timestamp to the next, * chained through the provided `onUpload` function. * * The last chunk passes this modified timestamp out, and we assign it to lastFetched. * * The idea of this is twofold: * * 1. It does the fast-forwarding that every other Sync client does. * * 2. It allows us to (eventually) pass the last collection modified time as If-Unmodified-Since * on each upload batch, as we do between the download and the upload phase. * This alone allows us to detect conflicts from racing clients. * * In order to implement the latter, we'd need to chain the date from getSince in place of the * 0 in the call to uploadOutgoingFromStorage in each synchronizer. */ func uploadRecords<T>( _ records: [Record<T>], lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>, onUpload: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp ) -> DeferredTimestamp { if records.isEmpty { log.debug("No modified records to upload.") return deferMaybe(lastTimestamp) } func reportUploadStatsWrap(result: POSTResult, timestamp: Timestamp?) -> DeferredTimestamp { let stats = SyncUploadStats(sent: result.success.count, sentFailed: result.failed.count) self.statsSession.recordUpload(stats: stats) return onUpload(result, timestamp) } let batch = storageClient.newBatch(ifUnmodifiedSince: (lastTimestamp == 0) ? nil : lastTimestamp, onCollectionUploaded: reportUploadStatsWrap) return batch.addRecords(records) >>> batch.endBatch >>> { let timestamp = batch.ifUnmodifiedSince ?? lastTimestamp self.setTimestamp(timestamp) return deferMaybe(timestamp) } } func uploadRecordsSingleBatch<T>(_ records: [Record<T>], lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>) -> Deferred<Maybe<(timestamp: Timestamp, succeeded: [GUID])>> { if records.isEmpty { log.debug("No modified records to upload.") return deferMaybe((timestamp: lastTimestamp, succeeded: [])) } func reportUploadStatsWrap(result: POSTResult, timestamp: Timestamp?) -> DeferredTimestamp { let stats = SyncUploadStats(sent: result.success.count, sentFailed: result.failed.count) self.statsSession.recordUpload(stats: stats) return deferMaybe(timestamp ?? lastTimestamp) } let batch = storageClient.newBatch(ifUnmodifiedSince: (lastTimestamp == 0) ? nil : lastTimestamp, onCollectionUploaded: reportUploadStatsWrap) return batch.addRecords(records, singleBatch: true) >>== batch.endSingleBatch >>== { (succeeded, lastModified) in guard let timestamp = lastModified else { return deferMaybe(FatalError(message: "Could not retrieve lastModified from the server response.")) } self.setTimestamp(timestamp) return deferMaybe((timestamp: timestamp, succeeded: succeeded)) } } }
mpl-2.0
f29c3259e39c7a830469f0dd8f0ad15d
41.165563
192
0.629182
4.970336
false
false
false
false
Rivukis/Parlance
ParlanceTests/ParlanceCoordinatableTests.swift
1
3694
// // ParlanceCoordinatableSpec.swift // Parlance // // Created by Brian Radebaugh on 2/8/17. // Copyright © 2017 Brian Radebaugh. All rights reserved. // import XCTest import Parlance enum TestLanguage { case languageOne case languageTwo } final class TestParlanceCoordinator: ParlanceCoordinatable { var languageToReturn: TestLanguage! static let shared = TestParlanceCoordinator() func currentLanguage(for locale: Locale) -> TestLanguage { return languageToReturn } func category(for int: Int, language: TestLanguage) -> PluralCategory { if language == .languageTwo { return .other } switch int { case 0: return .zero case 1: return .one case 2: return .two case 3: return .few case 4: return .many default: return .other } } } class ParlanceCoordinatableTests: XCTestCase { func testCurrentLanguage() { // Given let subject = TestParlanceCoordinator() // When the language is .languageOne subject.languageToReturn = .languageOne // Then XCTAssert(subject.currentLanguage == .languageOne, "should get the language from category(for:)") // When the language is .languageTwo subject.languageToReturn = .languageTwo // Then XCTAssert(subject.currentLanguage == .languageTwo, "should get the language from category(for:)") } func testRawCategoryValues() { // Given let subject = TestParlanceCoordinator() subject.languageToReturn = .languageOne // When int is 0 var int = 0 // Then return the raw value of PluralCategory of zero XCTAssert(subject.rawCategory(for: int) == "zero", "should return the raw value of 'zero'") // When int is 1 int = 1 // Then return the raw value of PluralCategory of one XCTAssert(subject.rawCategory(for: int) == "one", "should return the raw value of 'one'") // When int is 2 int = 2 // Then return the raw value of PluralCategory of two XCTAssert(subject.rawCategory(for: int) == "two", "should return the raw value of 'two'") // When int is 3 int = 3 // Then return the raw value of PluralCategory of few XCTAssert(subject.rawCategory(for: int) == "few", "should return the raw value of 'few'") // When int is 4 int = 4 // Then return the raw value of PluralCategory of many XCTAssert(subject.rawCategory(for: int) == "many", "should return the raw value of 'many'") // When int is 5 int = 5 // Then return the raw value of PluralCategory of other XCTAssert(subject.rawCategory(for: int) == "other", "should return the raw value of 'other'") } func testRawValueLanguage() { // Given let subject = TestParlanceCoordinator() // When the language is .languageOne subject.languageToReturn = .languageOne // Then should respect the language XCTAssert(subject.rawCategory(for: 0) == "zero", "should return the raw value of 'zero'") // When the language is .languageTwo subject.languageToReturn = .languageTwo // Then should respect the language XCTAssert(subject.rawCategory(for: 0) == "other", "should return the raw value of 'other'") } }
mit
76a9918efc7933fa2c3d8fcf9476dfca
28.782258
105
0.582724
5.186798
false
true
false
false
KevinCoble/AIToolbox
iOS Playgrounds/SupportVectorMachine.playground/Sources/SVMExtensions.swift
3
5493
// // SVMExtensions.swift // AIToolbox // // Created by Kevin Coble on 1/17/16. // Copyright © 2016 Kevin Coble. All rights reserved. // // This file contains extensions to the SVMModel class to get it to play nicely with the rest of the library // This code doesn't go in the SVM file, as I want to keep that close to the original LIBSVM source material import Foundation enum SVMError: Error { case invalidModelType } extension SVMModel : Classifier { public func getInputDimension() -> Int { if (supportVector.count < 1) { return 0 } return supportVector[0].count } public func getParameterDimension() -> Int { return totalSupportVectors //!! This needs to be calculated correctly } public func getNumberOfClasses() -> Int { return numClasses } public func setParameters(_ parameters: [Double]) throws { //!! This needs to be filled in } public func getParameters() throws -> [Double] { //!! This needs to be filled in return [] } public func setCustomInitializer(_ function: ((_ trainData: MLDataSet)->[Double])!) { // Ignore, as SVM doesn't use an initialization } public func trainClassifier(_ trainData: MLClassificationDataSet) throws { // Verify the SVMModel is the right type if type != .c_SVM_Classification || type != .ν_SVM_Classification { throw SVMError.invalidModelType } // Verify the data set is the right type if (trainData.dataType != .classification) { throw DataTypeError.invalidDataType } // Train on the data (ignore initialization, as SVM's do single-batch training) if (trainData is DataSet) { train(trainData as! DataSet) } else { // Convert the data set to a DataSet class, as the SVM was ported from a public domain code that used specific properties that were added to the DataSet class but are not in the MLDataSet protocols if let convertedData = DataSet(fromClassificationDataSet: trainData) { train(convertedData) } } } public func continueTrainingClassifier(_ trainData: MLClassificationDataSet) throws { // Linear regression uses one-batch training (solved analytically) throw MachineLearningError.continuationNotSupported } public func classifyOne(_ inputs: [Double]) ->Int { // Get the support vector start index for each class var coeffStart = [0] for index in 0..<numClasses-1 { coeffStart.append(coeffStart[index] + supportVectorCount[index]) } // Get the kernel value for each support vector at the input value var kernelValue: [Double] = [] for sv in 0..<totalSupportVectors { kernelValue.append(Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[sv])) } // Allocate vote space for the classification var vote = [Int](repeating: 0, count: numClasses) // Initialize the decision values var decisionValues: [Double] = [] // Get the seperation info between each class pair var permutation = 0 for i in 0..<numClasses { for j in i+1..<numClasses { var sum = 0.0 for k in 0..<supportVectorCount[i] { sum += coefficients[j-1][coeffStart[i]+k] * kernelValue[coeffStart[i]+k] } for k in 0..<supportVectorCount[j] { sum += coefficients[i][coeffStart[j]+k] * kernelValue[coeffStart[j]+k] } sum -= ρ[permutation] decisionValues.append(sum) permutation += 1 if (sum > 0) { vote[i] += 1 } else { vote[j] += 1 } } } // Get the most likely class, and set it var maxIndex = 0 for index in 1..<numClasses { if (vote[index] > vote[maxIndex]) { maxIndex = index } } return labels[maxIndex] } public func classify(_ testData: MLClassificationDataSet) throws { // Verify the SVMModel is the right type if type != .c_SVM_Classification || type != .ν_SVM_Classification { throw SVMError.invalidModelType } // Verify the data set is the right type if (testData.dataType != .classification) { throw DataTypeError.invalidDataType } if (supportVector.count <= 0) { throw MachineLearningError.notTrained } if (testData.inputDimension != supportVector[0].count) { throw DataTypeError.wrongDimensionOnInput } // Put the data into a DataSet for SVM (it uses a DataSet so that it can be both regressor and classifier) if let data = DataSet(dataType: .classification, withInputsFrom: testData) { // Predict predictValues(data) // Transfer the predictions back to the classifier data set for index in 0..<testData.size { let resultClass = try data.getClass(index) try testData.setClass(index, newClass: resultClass) } } else { throw MachineLearningError.dataWrongDimension } } }
apache-2.0
8d82384c296f542cec2e23171fbeedd5
35.593333
210
0.588814
4.699486
false
false
false
false
antelope-app/Antelope
Antelope-ios/Antelope/User.swift
1
2074
// // User.swift // Antelope // // Created by Jae Lee on 10/31/15. // Copyright © 2015 AdShield. All rights reserved. // import Foundation class User: NSObject { var id: Int! var device_id: String! var created_at: String! var device_apn_token: String! var trial_period: Bool! var aborting: Bool = false func initFromData(data: NSData) -> User { do { if let results: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary { if let id = results["id"] as? Int { self.id = id } if let device_id = results["device_id"] as? String { self.device_id = device_id } if let created_at = results["created_at"] as? String { self.created_at = created_at } if let device_apn_token = results["device_apn_token"] as? String { self.device_apn_token = device_apn_token } if let trial_period = results["trial_period"] { self.trial_period = trial_period.boolValue } } } catch { print("failed") } return self } func getByDeviceId(completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> User { let device_id: String! = UIDevice().identifierForVendor?.UUIDString print("User: getting by device id", device_id) let request = NSMutableURLRequest(URL: NSURL(string: "\(Constants.SERVER_DOMAIN)/users/trial_status/\(device_id)")!) request.HTTPMethod = "GET" let urlSession = NSURLSession.sharedSession() let sessionTask = urlSession.dataTaskWithRequest(request, completionHandler: completionHandler) sessionTask.resume() return self } }
gpl-2.0
94dc9db3beda47347c34ab8e6221c290
31.40625
160
0.533526
4.889151
false
false
false
false
jorgevila/ioscreator
IOS8SwiftIndexedTableViewTutorial/IOS8SwiftIndexedTableViewTutorial/TableViewController.swift
39
3705
// // TableViewController.swift // IOS8SwiftIndexedTableViewTutorial // // Created by Arthur Knopper on 10/05/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class TableViewController: UITableViewController { var tableData = [String]() var indexOfNumbers = [String]() override func viewDidLoad() { super.viewDidLoad() var allNumbers = "100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500" tableData = allNumbers.componentsSeparatedByString(" ") var indexNumbers = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15" indexOfNumbers = indexNumbers.componentsSeparatedByString(" ") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return indexOfNumbers.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... cell.textLabel?.text = tableData[indexPath.section] return cell } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return indexOfNumbers } override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { var temp = indexOfNumbers as NSArray return temp.indexOfObject(title) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
f0cc3b83aaa8fd5cbde7fcd68566af33
33.305556
157
0.676113
5.448529
false
false
false
false
kstaring/swift
test/Generics/deduction.swift
1
9584
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Deduction of generic arguments //===----------------------------------------------------------------------===// func identity<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> Int { return 0 } struct X { } struct Y { } func useIdentity(_ x: Int, y: Float, i32: Int32) { var x2 = identity(x) var y2 = identity(y) // Deduction that involves the result type x2 = identity(17) var i32_2 : Int32 = identity(17) // Deduction where the result type and input type can get different results var xx : X, yy : Y xx = identity(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} } // FIXME: Crummy diagnostic! func twoIdentical<T>(_ x: T, _ y: T) -> T {} func useTwoIdentical(_ xi: Int, yi: Float) { var x = xi, y = yi x = twoIdentical(x, x) y = twoIdentical(y, y) x = twoIdentical(x, 1) x = twoIdentical(1, x) y = twoIdentical(1.0, y) y = twoIdentical(y, 1.0) twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func mySwap<T>(_ x: inout T, _ y: inout T) { let tmp = x x = y y = tmp } func useSwap(_ xi: Int, yi: Float) { var x = xi, y = yi mySwap(&x, &x) mySwap(&y, &y) mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} // expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}} mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func takeTuples<T, U>(_: (T, U), _: (U, T)) { } func useTuples(_ x: Int, y: Float, z: (Float, Int)) { takeTuples((x, y), (y, x)) takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} // FIXME: Use 'z', which requires us to fix our tuple-conversion // representation. } func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {} func passFunction(_ f: (Int) -> Float, x: Int, y: Float) { acceptFunction(f, x, y) acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}} func testReturnTuple(_ x: Int, y: Float) { returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}} var _ : (Int, Float) = returnTuple(x) var _ : (Float, Float) = returnTuple(y) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) { confusingArgAndParam(g, f) confusingArgAndParam(f, g) } func acceptUnaryFn<T, U>(_ f: (T) -> U) { } func acceptUnaryFnSame<T>(_ f: (T) -> T) { } func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { } func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { } func unaryFnIntInt(_: Int) -> Int {} func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}} func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}} // Variable forms of the above functions var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt func passOverloadSet() { // Passing a non-generic function to a generic function acceptUnaryFn(unaryFnIntInt) acceptUnaryFnSame(unaryFnIntInt) // Passing an overloaded function set to a generic function // FIXME: Yet more terrible diagnostics. acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}} acceptUnaryFnSame(unaryFnOvl) // Passing a variable of function type to a generic function acceptUnaryFn(unaryFnIntIntVar) acceptUnaryFnSame(unaryFnIntIntVar) // Passing a variable of function type to a generic function to an inout parameter acceptUnaryFnRef(&unaryFnIntIntVar) acceptUnaryFnSameRef(&unaryFnIntIntVar) acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}} } func acceptFnFloatFloat(_ f: (Float) -> Float) {} func acceptFnDoubleDouble(_ f: (Double) -> Double) {} func passGeneric() { acceptFnFloatFloat(identity) acceptFnFloatFloat(identity2) } //===----------------------------------------------------------------------===// // Simple deduction for generic member functions //===----------------------------------------------------------------------===// struct SomeType { func identity<T>(_ x: T) -> T { return x } func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}} func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}} func returnAs<T>() -> T {} } func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) { var st = sti, i = ii, f = fi i = st.identity(i) f = st.identity(f) i = st.identity2(i) f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}} i = st.returnAs() f = st.returnAs() acceptFnFloatFloat(st.identity) acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}} acceptFnDoubleDouble(st.identity2) } struct StaticFuncs { static func chameleon<T>() -> T {} func chameleon2<T>() -> T {} } struct StaticFuncsGeneric<U> { // FIXME: Nested generics are very broken // static func chameleon<T>() -> T {} } func chameleon<T>() -> T {} func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) { var x: Int16 x = StaticFuncs.chameleon() x = sf.chameleon2() // FIXME: Nested generics are very broken // x = sfi.chameleon() // typealias SFI = StaticFuncsGeneric<Int> // x = SFI.chameleon() _ = x } //===----------------------------------------------------------------------===// // Deduction checking for constraints //===----------------------------------------------------------------------===// protocol IsBefore { func isBefore(_ other: Self) -> Bool } func min2<T : IsBefore>(_ x: T, _ y: T) -> T { if y.isBefore(x) { return y } return x } extension Int : IsBefore { func isBefore(_ other: Int) -> Bool { return self < other } } func callMin(_ x: Int, y: Int, a: Float, b: Float) { _ = min2(x, y) min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}} } func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} func callRangeOfIsBefore(_ ia: [Int], da: [Double]) { rangeOfIsBefore(ia.makeIterator()) rangeOfIsBefore(da.makeIterator()) // expected-error{{ambiguous reference to member 'makeIterator()'}} } //===----------------------------------------------------------------------===// // Deduction for member operators //===----------------------------------------------------------------------===// protocol Addable { static func +(x: Self, y: Self) -> Self } func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T { u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} return x+y } //===----------------------------------------------------------------------===// // Deduction for bound generic types //===----------------------------------------------------------------------===// struct MyVector<T> { func size() -> Int {} } func getVectorSize<T>(_ v: MyVector<T>) -> Int { return v.size() } func ovlVector<T>(_ v: MyVector<T>) -> X {} func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {} func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) { var i : Int i = getVectorSize(vi) i = getVectorSize(vf) getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}} var x : X, y : Y x = ovlVector(vi) x = ovlVector(vf) var vvi : MyVector<MyVector<Int>> y = ovlVector(vvi) var yy = ovlVector(vvi) yy = y y = yy } // <rdar://problem/15104554> postfix operator <*> protocol MetaFunction { associatedtype Result static postfix func <*> (_: Self) -> Result? } protocol Bool_ {} struct False : Bool_ {} struct True : Bool_ {} postfix func <*> <B:Bool_>(_: Test<B>) -> Int? { return .none } postfix func <*> (_: Test<True>) -> String? { return .none } class Test<C: Bool_> : MetaFunction { typealias Result = Int } // picks first <*> typealias Inty = Test<True>.Result var iy : Inty = 5 // okay, because we picked the first <*> var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}} // rdar://problem/20577950 class DeducePropertyParams { let badSet: Set = ["Hello"] } // SR-69 struct A {} func foo() { for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}} } let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}} let oi : Int? = 5 let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}} }
apache-2.0
e78673ef62b3b2bfd94c6c870eeffca9
31.161074
150
0.597037
3.762858
false
false
false
false
bradhilton/HttpRequest
Pods/Convertible/Convertible/Swift Extensions/Array+Convertible.swift
1
1556
// // Array+Convertible.swift // Convertibles // // Created by Bradley Hilton on 6/15/15. // Copyright © 2015 Skyvive. All rights reserved. // import Foundation extension Array : DataModelConvertible {} extension Array : JsonConvertible { public static func initializeWithJson(json: JsonValue, options: [ConvertibleOption]) throws -> Array { switch json { case .Array(let array): return try resultFromArray(array, options: options) default: throw ConvertibleError.CannotCreateType(type: self, fromJson: json) } } static func resultFromArray(array: [JsonValue], options: [ConvertibleOption]) throws -> Array { let error = ConvertibleError.NotJsonInitializable(type: Element.self) guard let generic = Element.self as? JsonInitializable.Type else { throw error } var result = Array<Element>() for json in array { guard let element = try generic.initializeWithJson(json, options: options) as? Element else { throw error } result.append(element) } return result } public func serializeToJsonWithOptions(options: [ConvertibleOption]) throws -> JsonValue { var array = [JsonValue]() for element in self { guard let element = element as? JsonSerializable else { throw ConvertibleError.NotJsonSerializable(type: Element.self) } array.append(try element.serializeToJsonWithOptions(options)) } return JsonValue.Array(array) } }
mit
3cf6b284fd93bf7b2db89647c91acb0c
34.363636
119
0.659807
4.740854
false
false
false
false
valvoline/UIButton-AlphaMask
UIButton+AlphaMask/UIButton+AlphaMask.swift
1
2527
// // UIButtonMask.swift // ButtonMask // // Created by Costantino Pistagna on 03/02/2017. // Copyright © 2017 sofapps. All rights reserved. // import UIKit extension UIButton { open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if let anImage = self.image(for: .normal) { return isAlphaVisible(atPoint: point, forImage: anImage) } return super.point(inside: point, with: event) } func isAlphaVisible(atPoint: CGPoint, forImage image: UIImage) -> Bool { var point = atPoint let iSize = image.size let bSize = self.bounds.size point.x *= (bSize.width > 0) ? (iSize.width / bSize.width) : 1 point.y *= (bSize.height > 0) ? (iSize.height / bSize.height) : 1 if let pixelColor = image.color(atPixel: point) { var fAlpha: CGFloat = 0 pixelColor.getRed(nil, green: nil, blue: nil, alpha: &fAlpha) return (fAlpha == 1.0) } return false } } extension UIImage { func color(atPixel point:CGPoint) -> UIColor? { if CGRect(x:0, y:0, width:self.size.width, height:self.size.height).contains(point) == false { return nil } let imageRef = self.cgImage let width = imageRef!.width let height = imageRef!.height let colorSpace = CGColorSpaceCreateDeviceRGB() let rawData = UnsafeMutablePointer<UInt8>.allocate(capacity: (height*width*4)) let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue let context = CGContext.init(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) context?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: width, height: height)) let byteIndex: Int = (bytesPerRow * Int(point.y)) + Int(point.x) * bytesPerPixel let red = CGFloat(rawData[byteIndex]) / CGFloat(255.0) let green = CGFloat(rawData[byteIndex + 1]) / CGFloat(255.0) let blue = CGFloat(rawData[byteIndex + 2]) / CGFloat(255.0) let alpha = CGFloat(rawData[byteIndex + 3]) / CGFloat(255.0) return UIColor.init(colorLiteralRed: Float(red), green: Float(green), blue: Float(blue), alpha: Float(alpha)) } }
bsd-3-clause
bfa98c6f03ab139c0c0d40d9c87c94b4
38.46875
186
0.62312
4.061093
false
false
false
false
aranasaurus/minutes-app
minutes/code/projects/ProjectsFlowController.swift
1
5682
// // ProjectsFlowController.swift // Minutes // // Created by Ryan Arana on 11/27/16. // Copyright © 2016 Aranasaurus. All rights reserved. // import UIKit class ProjectsFlowController: NSObject { static let moneyFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .currencyAccounting formatter.currencyGroupingSeparator = "," return formatter }() fileprivate enum TextFields: Int { case rename case setRate } let dataStore: DataStore<Project> var root: ProjectsViewController! var selectedProject: Project? = nil init(dataStore: DataStore<Project>) { self.dataStore = dataStore super.init() self.root = ProjectsViewController(dataStore: dataStore, onProjectSelected: onProjectSelected) } func setupRootNav() { root.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addProjectTapped)) } @objc func addProjectTapped() { let alert = UIAlertController(title: "New Project", message: nil, preferredStyle: .alert) alert.addTextField() { textField in textField.placeholder = "Name" textField.autocapitalizationType = .words textField.keyboardType = .alphabet } alert.addTextField() { textField in textField.placeholder = "Default Rate" textField.keyboardType = .decimalPad } alert.addAction(UIAlertAction(title: "Add", style: .default) { action in guard action.title == "Add" else { return } // TODO: Error handling let name = alert.textFields!.first!.text! let rate = Double(alert.textFields![1].text!)! // TODO: Yikes this dataStore needs some work, this stuff shouldn't be being done here (the identifier generation and appending to the data array). self.dataStore.data.append(Project(identifier: name.hash, name: name, defaultRate: rate)) self.dataStore.save() self.root.reload() }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) root.present(alert, animated: true, completion: nil) } func onProjectSelected(project: Project) { selectedProject = project let popup = UIAlertController(title: project.name, message: nil, preferredStyle: .actionSheet) let rename = UIAlertAction(title: "Rename", style: .default) { _ in let alert = UIAlertController(title: "Rename \(project.name)", message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.text = project.name textField.clearButtonMode = .whileEditing textField.spellCheckingType = .default textField.autocapitalizationType = .words textField.returnKeyType = .done textField.delegate = self textField.tag = TextFields.rename.rawValue } alert.addAction(UIAlertAction(title: "Save", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.root.present(alert, animated: true, completion: nil) } popup.addAction(rename) let setRate = UIAlertAction(title: "Set Rate", style: .default) { _ in let alert = UIAlertController(title: "Set Rate", message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.text = ProjectsFlowController.moneyFormatter.string(from: NSNumber(floatLiteral: project.defaultRate)) textField.clearButtonMode = .never textField.keyboardType = .numbersAndPunctuation textField.returnKeyType = .done textField.delegate = self textField.tag = TextFields.setRate.rawValue } alert.addAction(UIAlertAction(title: "Save", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.root.present(alert, animated: true, completion: nil) } popup.addAction(setRate) let delete = UIAlertAction(title: "Delete", style: .destructive) { _ in guard let index = self.dataStore.data.firstIndex(of: project) else { return } self.dataStore.data.remove(at: index) self.root.remove(at: index) self.dataStore.save() } popup.addAction(delete) let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in self.root.clearSelection() } popup.addAction(cancel) root.present(popup, animated: true, completion: nil) } } extension ProjectsFlowController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { guard let project = selectedProject, let field = TextFields.init(rawValue: textField.tag) else { return } switch field { case .rename: project.name = textField.text ?? project.name dataStore.save() case .setRate: guard let text = textField.text, let rate = ProjectsFlowController.moneyFormatter.number(from: text)?.doubleValue else { return } project.defaultRate = rate dataStore.save() } guard let index = dataStore.data.firstIndex(of: project) else { return } root.reload(at: index) } }
mit
1377e1c08299a7b7cdcb5d1567eee3b6
38.451389
159
0.622778
4.944299
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Library/ReaderPanel.swift
2
20142
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonTitleColor = UIColor.Photon.White100 static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor.Photon.Blue50 static let MarkAsReadButtonTitleColor = UIColor.Photon.White100 static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: UITableViewCell, Themeable { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed hostnameLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed updateAccessibilityLabel() } } let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = .zero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = .scaleAspectFit readStatusImageView.snp.makeConstraints { (make) -> Void in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.centerY.equalTo(self.contentView) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) contentView.addSubview(hostnameLabel) titleLabel.numberOfLines = 2 titleLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000) } hostnameLabel.numberOfLines = 1 hostnameLabel.snp.makeConstraints { (make) -> Void in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.leading.trailing.equalTo(self.titleLabel) } applyTheme() } func setupDynamicFonts() { titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } func applyTheme() { titleLabel.textColor = UIColor.theme.homePanel.readingListActive hostnameLabel.textColor = UIColor.theme.homePanel.readingListActive } override func prepareForReuse() { super.prepareForReuse() applyTheme() setupDynamicFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return String(hostname[hostname.index(hostname.startIndex, offsetBy: prefix.count)...]) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(NSAttributedString.Key.accessibilitySpeechPitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, LibraryPanel { weak var libraryPanelDelegate: LibraryPanelDelegate? let profile: Profile fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() fileprivate var records: [ReadingListItem]? init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) [ Notification.Name.FirefoxAccountChanged, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Note this will then call applyTheme() on this class, which reloads the tableview. (navigationController as? ThemedNavigationController)?.applyTheme() } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "ReadingTable" tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableView.automaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = .zero tableView.layoutMargins = .zero tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() tableView.dragDelegate = self } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .DynamicFontChanged: refreshReadingList() case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "ReadingList.db" { refreshReadingList() } default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count tableView.tableHeaderView = nil if let newRecords = profile.readingList.getAvailableRecords().value.successValue { records = newRecords if records?.count == 0 { tableView.isScrollEnabled = false tableView.tableHeaderView = createEmptyStateOverview() } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true } } self.tableView.reloadData() } } fileprivate func createEmptyStateOverview() -> UIView { let overlayView = UIView(frame: tableView.bounds) let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalToSuperview().offset(UIDevice.current.orientation.isLandscape ? 16 : 150) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) } let readerModeLabel = UILabel() overlayView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readerModeLabel.numberOfLines = 0 readerModeLabel.snp.makeConstraints { make in make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) overlayView.addSubview(readerModeImageView) readerModeImageView.snp.makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } let readingListLabel = UILabel() overlayView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readingListLabel.numberOfLines = 0 readingListLabel.snp.makeConstraints { make in make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) overlayView.addSubview(readingListImageView) readingListImageView.snp.makeConstraints { make in make.centerY.equalTo(readingListLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } [welcomeLabel, readerModeLabel, readingListLabel].forEach { $0.textColor = UIColor.theme.homePanel.welcomeScreenText } return overlayView } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let record = records?[indexPath.row] else { return [] } let delete = UITableViewRowAction(style: .default, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in self?.deleteItem(atIndex: index) } let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in self?.toggleItem(atIndex: index) } unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor return [unreadToggle, delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark libraryPanelDelegate?.libraryPanel(didSelectURL: encodedURL, visitType: visitType) UnifiedTelemetry.recordEvent(category: .action, method: .open, object: .readingListItem) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .readingListItem, value: .readingListPanel) if profile.readingList.deleteRecord(record).value.isSuccess { records?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) // reshow empty state if no records left if records?.count == 0 { refreshReadingList() } } } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readingListItem, value: !record.unread ? .markAsUnread : .markAsRead, extras: [ "from": "reading-list-panel" ]) if let updatedRecord = profile.readingList.updateRecord(record, unread: !record.unread).value.successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: .automatic) } } } } extension ReadingListPanel: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let record = records?[indexPath.row] else { return nil } return Site(url: record.url, title: record.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil } let removeAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { _, _ in self.deleteItem(atIndex: indexPath) }) actions.append(removeAction) return actions } } @available(iOS 11.0, *) extension ReadingListPanel: UITableViewDragDelegate { func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let site = getSiteDetails(for: indexPath), let url = URL(string: site.url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .url, value: .readingListPanel) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = site return [dragItem] } func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { presentedViewController?.dismiss(animated: true) } } extension ReadingListPanel: Themeable { func applyTheme() { tableView.separatorColor = UIColor.theme.tableView.separator view.backgroundColor = UIColor.theme.tableView.rowBackground refreshReadingList() } }
mpl-2.0
e9498bc55fa78db46ae5bdbee237a50c
43.561947
333
0.690646
5.584142
false
false
false
false
alecananian/osx-coin-ticker
CoinTicker/Source/Exchanges/HitBTCExchange.swift
1
5004
// // HitBTCExchange.swift // CoinTicker // // Created by Alec Ananian on 1/29/18. // Copyright © 2018 Alec Ananian. // // 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 Starscream import SwiftyJSON import PromiseKit class HitBTCExchange: Exchange { private struct Constants { static let WebSocketURL = URL(string: "wss://api.hitbtc.com/api/2/ws")! static let ProductListAPIPath = "https://api.hitbtc.com/api/2/public/symbol" static let FullTickerAPIPath = "https://api.hitbtc.com/api/2/public/ticker" static let SingleTickerAPIPathFormat = "https://api.hitbtc.com/api/2/public/ticker/%@" } init(delegate: ExchangeDelegate? = nil) { super.init(site: .hitbtc, delegate: delegate) } override func load() { super.load(from: Constants.ProductListAPIPath) { $0.json.arrayValue.compactMap { result in CurrencyPair( baseCurrency: result["baseCurrency"].string, quoteCurrency: result["quoteCurrency"].string, customCode: result["id"].string ) } } } override internal func fetch() { let apiPath: String if selectedCurrencyPairs.count == 1, let currencyPair = selectedCurrencyPairs.first { apiPath = String(format: Constants.SingleTickerAPIPathFormat, currencyPair.customCode) } else { apiPath = Constants.FullTickerAPIPath } requestAPI(apiPath).map { [weak self] result in if let strongSelf = self { let results = result.json.array ?? [result.json] results.forEach({ result in if let currencyPair = strongSelf.selectedCurrencyPair(withCustomCode: result["symbol"].stringValue) { strongSelf.setPrice(result["last"].doubleValue, for: currencyPair) } }) if strongSelf.isUpdatingInRealTime { strongSelf.delegate?.exchangeDidUpdatePrices(strongSelf) } else { strongSelf.onFetchComplete() } } }.catch { error in print("Error fetching HitBTC ticker: \(error)") } if isUpdatingInRealTime { let socket = WebSocket(request: URLRequest(url: Constants.WebSocketURL)) socket.callbackQueue = socketResponseQueue socket.onEvent = { [weak self] event in switch event { case .connected(_): self?.selectedCurrencyPairs.forEach({ currencyPair in let json = JSON([ "method": "subscribeTicker", "params": [ "symbol": currencyPair.customCode ] ]) if let string = json.rawString() { socket.write(string: string) } }) case .text(let text): if let strongSelf = self { let result = JSON(parseJSON: text) if result["method"] == "ticker" { let data = result["params"] if let currencyPair = strongSelf.selectedCurrencyPair(withCustomCode: data["symbol"].stringValue) { let price = data["last"].doubleValue strongSelf.setPrice(price, for: currencyPair) strongSelf.delegate?.exchangeDidUpdatePrices(strongSelf) } } } default: break } } socket.connect() self.socket = socket } } }
mit
7fc542db3e392eb6aa6e6614b6cc6dfd
38.706349
127
0.563862
5.173733
false
false
false
false
xuephil/Perfect
Examples/Ultimate Noughts and Crosses/Ultimate Noughts and Crosses/GameViewController.swift
2
5786
// // GameViewController.swift // Ultimate Noughts and Crosses // // Created by Kyle Jessup on 2015-10-28. // Copyright © 2015 PerfectlySoft. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import UIKit let CONTENT_TAG = 10 struct GridLocation { var contentView: UIView var major: (x: Int, y: Int) var minor: (x: Int, y: Int) } extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } var viewCenter: CGPoint { let r = self.bounds return CGPoint(x: CGRectGetMidX(r), y: CGRectGetMidY(r)) } var contentView: UIView? { for child in self.subviews { if child.tag == CONTENT_TAG { return child } } return nil } func childWithTag(tag: Int) -> UIView? { for child in self.subviews { if child.tag == tag { return child } } return nil } var gridLocation: GridLocation? { if self.tag == CONTENT_TAG { if let superView = self.superview { if let loc1 = superView.locationForTag { if let superView2 = superView.superview { if let superViewWrap = superView2.superview { if superViewWrap.tag == CONTENT_TAG { if let superView3 = superViewWrap.superview { if let loc2 = superView3.locationForTag { return GridLocation(contentView: self, major: loc2, minor: loc1) } } } } } } } } return nil } var locationForTag: (Int, Int)? { switch self.tag { case 1: return (0, 0) case 2: return (1, 0) case 3: return (2, 0) case 4: return (0, 1) case 5: return (1, 1) case 6: return (2, 1) case 7: return (0, 2) case 8: return (1, 2) case 9: return (2, 2) default: return nil } } } class GameViewController: UIViewController { @IBOutlet var mainBoard: UIView? var localPlayerNick = "" override func viewDidLoad() { super.viewDidLoad() self.loadBoard() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadBoard() { let mainInner = loadOneBoard() self.placeInsideAndConstrain(mainInner, superView: mainBoard!) var children = [Int:UIView]() for child in mainInner.subviews { let tag = child.tag if tag != 0 { children[tag] = child } } for tag in 1...9 { if let view = children[tag] { let newChild = self.loadOneBoard() if let subHolder = view.contentView { self.placeInsideAndConstrain(newChild, superView: subHolder) } } } } func loadOneBoard() -> UIView { let loaded = NSBundle.mainBundle().loadNibNamed("Board", owner: self, options: nil) let v = loaded[0] as! UIView return v } func placeInsideAndConstrain(childView: UIView, superView: UIView) { childView.translatesAutoresizingMaskIntoConstraints = false superView.addSubview(childView) superView.addConstraints([ NSLayoutConstraint(item: childView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: childView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: childView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: childView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0) ]) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let first = touches.first { let pt = first.locationInView(mainBoard!) if let hit = mainBoard!.hitTest(pt, withEvent: event) { if let gridLocation = hit.gridLocation { print("Major: \(gridLocation.major) Minor: \(gridLocation.minor)") // !FIX! check if it's a valid location let ex = rand() % 2 == 0 let img = UIImageView(image: UIImage(named: ex ? "Ex" : "Oh")) gridLocation.contentView.addSubview(img) img.frame = gridLocation.contentView.bounds img.center = gridLocation.contentView.viewCenter } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
agpl-3.0
4bb5b8cadd46ce5a8a29f96cc05cf4f6
27.082524
202
0.687468
3.710712
false
false
false
false
jeantil/autokbisw
Sources/autokbisw/IOKeyEventMonitor.swift
1
7799
// Copyright [2016] Jean Helou // // 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 Carbon import Foundation import IOKit import IOKit.hid import IOKit.usb internal final class IOKeyEventMonitor { private let hidManager: IOHIDManager fileprivate let MAPPINGS_DEFAULTS_KEY = "keyboardISMapping" fileprivate let notificationCenter: CFNotificationCenter fileprivate var lastActiveKeyboard: String = "" fileprivate var kb2is: [String: TISInputSource] = [String: TISInputSource]() fileprivate var defaults: UserDefaults = UserDefaults.standard fileprivate var useLocation: Bool fileprivate var verbosity: Int init? (usagePage: Int, usage: Int, useLocation: Bool, verbosity: Int) { self.useLocation = useLocation self.verbosity = verbosity hidManager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) notificationCenter = CFNotificationCenterGetDistributedCenter() let deviceMatch: CFMutableDictionary = [kIOHIDDeviceUsageKey: usage, kIOHIDDeviceUsagePageKey: usagePage] as NSMutableDictionary IOHIDManagerSetDeviceMatching(hidManager, deviceMatch) loadMappings() } deinit { self.saveMappings() let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) IOHIDManagerRegisterInputValueCallback(hidManager, Optional.none, context) CFNotificationCenterRemoveObserver(notificationCenter, context, CFNotificationName(kTISNotifySelectedKeyboardInputSourceChanged), nil) } func start() { let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) observeIputSourceChangedNotification(context: context) registerHIDKeyboardCallback(context: context) IOHIDManagerScheduleWithRunLoop(hidManager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode!.rawValue) IOHIDManagerOpen(hidManager, IOOptionBits(kIOHIDOptionsTypeNone)) } private func observeIputSourceChangedNotification(context: UnsafeMutableRawPointer) { let inputSourceChanged: CFNotificationCallback = { _, observer, _, _, _ in let selfPtr = Unmanaged<IOKeyEventMonitor>.fromOpaque(observer!).takeUnretainedValue() selfPtr.onInputSourceChanged() } CFNotificationCenterAddObserver(notificationCenter, context, inputSourceChanged, kTISNotifySelectedKeyboardInputSourceChanged, nil, CFNotificationSuspensionBehavior.deliverImmediately) } private func registerHIDKeyboardCallback(context: UnsafeMutableRawPointer) { let myHIDKeyboardCallback: IOHIDValueCallback = { context, _, sender, _ in let selfPtr = Unmanaged<IOKeyEventMonitor>.fromOpaque(context!).takeUnretainedValue() let senderDevice = Unmanaged<IOHIDDevice>.fromOpaque(sender!).takeUnretainedValue() let vendorId = IOHIDDeviceGetProperty(senderDevice, kIOHIDVendorIDKey as CFString) ??? "unknown" let productId = IOHIDDeviceGetProperty(senderDevice, kIOHIDProductIDKey as CFString) ??? "unknown" let product = IOHIDDeviceGetProperty(senderDevice, kIOHIDProductKey as CFString) ??? "unknown" let manufacturer = IOHIDDeviceGetProperty(senderDevice, kIOHIDManufacturerKey as CFString) ??? "unknown" let serialNumber = IOHIDDeviceGetProperty(senderDevice, kIOHIDSerialNumberKey as CFString) ??? "unknown" let locationId = IOHIDDeviceGetProperty(senderDevice, kIOHIDLocationIDKey as CFString) ??? "unknown" let uniqueId = IOHIDDeviceGetProperty(senderDevice, kIOHIDUniqueIDKey as CFString) ??? "unknown" let keyboard = selfPtr.useLocation ? "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)-\(locationId)]" : "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)]" if selfPtr.verbosity >= TRACE { print("received event from keyboard \(keyboard) - \(locationId) - \(uniqueId)") } selfPtr.onKeyboardEvent(keyboard: keyboard) } IOHIDManagerRegisterInputValueCallback(hidManager, myHIDKeyboardCallback, context) } } extension IOKeyEventMonitor { func restoreInputSource(keyboard: String) { if let targetIs = kb2is[keyboard] { if verbosity >= DEBUG { print("set input source to \(targetIs) for keyboard \(keyboard)") } TISSelectInputSource(targetIs) } else { storeInputSource(keyboard: keyboard) } } func storeInputSource(keyboard: String) { let currentSource: TISInputSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() kb2is[keyboard] = currentSource saveMappings() } func onInputSourceChanged() { storeInputSource(keyboard: lastActiveKeyboard) } func onKeyboardEvent(keyboard: String) { guard lastActiveKeyboard != keyboard else { return } restoreInputSource(keyboard: keyboard) lastActiveKeyboard = keyboard } func loadMappings() { let selectableIsProperties = [ kTISPropertyInputSourceIsEnableCapable: true, kTISPropertyInputSourceCategory: kTISCategoryKeyboardInputSource, ] as CFDictionary let inputSources = TISCreateInputSourceList(selectableIsProperties, false).takeUnretainedValue() as! Array<TISInputSource> let inputSourcesById = inputSources.reduce([String: TISInputSource]()) { (dict, inputSource) -> [String: TISInputSource] in var dict = dict if let id = unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID)) { dict[id] = inputSource } return dict } if let mappings = self.defaults.dictionary(forKey: MAPPINGS_DEFAULTS_KEY) { for (keyboardId, inputSourceId) in mappings { kb2is[keyboardId] = inputSourcesById[String(describing: inputSourceId)] } } } func saveMappings() { let mappings = kb2is.mapValues(is2Id) defaults.set(mappings, forKey: MAPPINGS_DEFAULTS_KEY) } private func is2Id(_ inputSource: TISInputSource) -> String? { return unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID))! } func unmanagedStringToString(_ p: UnsafeMutableRawPointer?) -> String? { if let cfValue = p { let value = Unmanaged.fromOpaque(cfValue).takeUnretainedValue() as CFString if CFGetTypeID(value) == CFStringGetTypeID() { return value as String } else { return nil } } else { return nil } } } // Nicer string interpolation of optional strings, see: https://oleb.net/blog/2016/12/optionals-string-interpolation/ infix operator ???: NilCoalescingPrecedence public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String { return optional.map { String(describing: $0) } ?? defaultValue() }
apache-2.0
b6349942d0b2e88b77662b4cd0772f47
42.327778
142
0.68496
5.287458
false
false
false
false
austinzheng/swift
benchmark/single-source/Phonebook.swift
3
2688
//===--- Phonebook.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is based on util/benchmarks/Phonebook, with modifications // for performance measuring. import TestsUtils public let Phonebook = BenchmarkInfo( name: "Phonebook", runFunction: run_Phonebook, tags: [.validation, .api, .String], setUpFunction: { blackHole(names) } ) let words = [ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony", "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott", "Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin", "Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter", "Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl", "Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy", "Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce", "Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan", "Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Craig" ] let names: [Record] = { // The list of names in the phonebook. var names = [Record]() names.reserveCapacity(words.count * words.count) for first in words { for last in words { names.append(Record(first, last)) } } return names }() // This is a phone book record. struct Record : Comparable { var first: String var last: String init(_ first_ : String,_ last_ : String) { first = first_ last = last_ } } func ==(lhs: Record, rhs: Record) -> Bool { return lhs.last == rhs.last && lhs.first == rhs.first } func <(lhs: Record, rhs: Record) -> Bool { if lhs.last < rhs.last { return true } if lhs.last > rhs.last { return false } if lhs.first < rhs.first { return true } return false } @inline(never) public func run_Phonebook(_ N: Int) { for _ in 1...N { var t = names t.sort() } }
apache-2.0
3b073b362abea5dbb4deb5e5464b2b78
30.255814
81
0.591146
3.270073
false
false
false
false
sendyhalim/Yomu
Yomu/Screens/MangaList/MangaItem.swift
1
1269
// // MangaCell.swift // Yomu // // Created by Sendy Halim on 6/15/16. // Copyright © 2016 Sendy Halim. All rights reserved. // import AppKit import RxSwift class MangaItem: NSCollectionViewItem { @IBOutlet weak var mangaImageView: NSImageView! @IBOutlet weak var titleContainerView: NSBox! @IBOutlet weak var titleTextField: NSTextField! @IBOutlet weak var categoryTextField: NSTextField! @IBOutlet weak var selectedIndicator: NSBox! var disposeBag = DisposeBag() func setup(withViewModel viewModel: MangaViewModel) { disposeBag = DisposeBag() viewModel .title .drive(titleTextField.rx.text.orEmpty) ==> disposeBag viewModel .previewUrl .drive(onNext: mangaImageView.setImageWithUrl) ==> disposeBag viewModel .categoriesString .drive(categoryTextField.rx.text.orEmpty) ==> disposeBag viewModel .selected .map(!) .drive(selectedIndicator.rx.isHidden) ==> disposeBag } override func viewDidLoad() { super.viewDidLoad() mangaImageView.kf.indicatorType = .activity } override func viewWillLayout() { super.viewWillLayout() let border = Border(position: .bottom, width: 1.0, color: Config.style.borderColor) titleContainerView.drawBorder(border) } }
mit
19380016f94ef2079251221e3cc56256
22.481481
87
0.712934
4.26936
false
false
false
false
Sweefties/FutureKit
FutureKit-4. Completion.playground/Contents.swift
3
5482
//: # Welcome to FutureKit! //: Make sure you opened this inside the FutureKit workspace. Opening the playground file directly, usually means it can't import FutureKit module correctly. import FutureKit import XCPlayground XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) //: # Completion //: Sometimes you want to create a dependent Future but conditionally decide inside the block whether the dependent block should Succeed or Fail, etc. For this we have use a handler block with a different generic signature: //: 'func onComplete<S>((Completion<T>) -> Completion<S>) -> Future<S>' //: Don't worry if that seems hard to understand. It's actually pretty straightforward. //: A Completion is a enumeration that is used to 'complete' a future. A Future has a var //: `completion : Completion<T>?` //: this var stores the completion value of the Future. Note that it's optional. That's because a Future may not be 'completed' yet. When it's in an uncompleted state, it's completion var will be nil. //: If you examine the contents of a completed Future<T>, you will find a Completion<T> enumeration that must be one of the 3 possible values: `.Success(Result<T>)`, `.Fail(NSError)`, `.Cancel(Any?)` let futureInt = Future(success: 5) switch futureInt.completion! { case let .Success(s): let x = s.result default: break } //: .Success uses an associated type of `Result<T>` is just a generic payload wrapper. Swift currently has a restriction on using generic associated values ( http://stackoverflow.com/questions/27257522/whats-the-exact-limitation-on-generic-associated-values-in-swift-enums). So we wrap the generic type T in a Generic 'box' called Result<T>. The plan will be to remove this in a future version of swift (that no longer has the limitation). //: To get around some of the pain of instanciating the enumerations, FutureKit defines a set of global functions that are easier to read. //: public func SUCCESS(t) -> Completion<T> //: public func FAIL(e) -> Completion<T> //: public func CANCELLED() -> Completion<T> //: But completion has a fourth enumeration case `.CompleteUsing(Future<T>)`. This is very useful when you have a handler that wants to use some other Future to complete itself. This completion value is only used as a return value from a handler method. //: public func COMPLETE_USING(Future<T>) //: First let's create an unreliable Future, that fails most of the time (80%) func iMayFailRandomly() -> Future<String> { let p = Promise<String>() Executor.Default.execute { () -> Void in // This is a random number from 0..4. // So we only have a 20% of success! let randomNumber = arc4random_uniform(5) if (randomNumber == 0) { p.completeWithSuccess("Yay") } else { p.completeWithFail("Not lucky Enough this time") } } return p.future } //: Here is a function that will call itself recurisvely until it finally succeeds. func iWillKeepTryingTillItWorks(attemptNo: Int) -> Future<Int> { let numberOfAttempts = attemptNo + 1 return iMayFailRandomly().onComplete { (completion) -> Completion<Int> in switch completion.state { case .Success: let s = completion.result return SUCCESS(numberOfAttempts) default: // we didn't succeed! let nextFuture = iWillKeepTryingTillItWorks(numberOfAttempts) return COMPLETE_USING(nextFuture) } } } let keepTrying = iWillKeepTryingTillItWorks(0) keepTrying.onSuccess { (tries) -> Void in let howManyTries = tries } //: If you select "Editor -> Execute Playground" you can see this number change. //: ## CompletionState //: since onComplete will get a Completion<Int>, the natural idea would be to use switch (completion) futureInt.onComplete { (completion : Completion<Int>) -> Void in switch completion { case let .Success(r): let five = r.result case let .Fail(error): let e = error case .Cancelled: break case let .CompleteUsing(f): assertionFailure("hey! FutureKit promised this wouldn't happen!") break; } } //: But it's annoying for a few reasons. //: 1. You have to add either `case .CompleteUsing`:, or a `default:`, because Swift requires switch to be complete. But it's illegal to receive that completion value, in this function. That case won't happen. //: 2. .Success currently uses an associated type of 'Result<T>'. Which has more to do with a bug/limitation in Swift Generic enumerations (that we expect will get fixed in the future). //: So the simpler and alternate is to look at the var 'state' on the completion value. It uses the related enumeration CompletionState. Which is a simpler enumeration. //: Let's rewrite the same handler using the var `state`. futureInt.onComplete { (completion : Completion<Int>) -> Void in switch completion.state { case .Success: let five = completion.result case .Fail: let e = completion.error case .Cancelled: break } } //: If all you care about is success or fail, you can use the isSuccess var futureInt.onComplete { (completion : Completion<Int>) -> Void in if completion.isSuccess { let five = completion.result } else { // must have failed or was cancelled } }
mit
4f756c586e28b77ee6cfd317be23ae79
42.856
442
0.687888
4.26283
false
false
false
false
roytornado/RSFloatInputView
RSFloatInputView/Classes/RSFloatInputView.swift
1
6097
import UIKit import CoreText open class RSFloatInputView: UIView { open static var stringTransformer: ((String) -> String?)! = { orginal in return orginal } open static var instanceTransformer: ((RSFloatInputView) -> Void)! = { orginal in } public enum State { case idle, float } @IBInspectable open var applyTransform: Bool = true @IBInspectable open var leftInset: CGFloat = 16 @IBInspectable open var rightInset: CGFloat = 16 @IBInspectable open var textInnerPadding: CGFloat = 2 @IBInspectable open var imageInnerPadding: CGFloat = 8 @IBInspectable open var iconImage: UIImage? = nil @IBInspectable open var iconSize: CGFloat = 30 @IBInspectable open var idlePlaceHolderColor: UIColor = UIColor.lightGray @IBInspectable open var floatPlaceHolderColor: UIColor = UIColor.blue @IBInspectable open var textColor: UIColor = UIColor.darkGray @IBInspectable open var placeHolderStringKey: String = "" { didSet { placeHolderLabel.string = RSFloatInputView.stringTransformer(placeHolderStringKey) } } @IBInspectable open var placeHolderFontKey: String = "HelveticaNeue" @IBInspectable open var idlePlaceHolderFontSize: CGFloat = 16 @IBInspectable open var floatPlaceHolderFontSize: CGFloat = 14 @IBInspectable open var inputFontName: String = "HelveticaNeue" @IBInspectable open var inputFontSize: CGFloat = 16 @IBInspectable open var separatorEnabled: Bool = true @IBInspectable open var separatorColor: UIColor = UIColor.lightGray @IBInspectable open var separatorLeftInset: CGFloat = 0 @IBInspectable open var separatorRightInset: CGFloat = 0 @IBInspectable open var animationDuration: Double = 0.45 open var iconImageView = UIImageView() open var placeHolderLabel = CATextLayer() open var textField = UITextField() open var separatorView = UIView() open var state: State = State.idle override open func awakeFromNib() { super.awakeFromNib() build() } open func build() { placeHolderLabel.contentsScale = UIScreen.main.scale addSubview(textField) addSubview(iconImageView) addSubview(separatorView) layer.addSublayer(placeHolderLabel) addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(focus))) textField.addTarget(self, action: #selector(editingDidEnd), for: .editingDidEnd) if applyTransform { RSFloatInputView.instanceTransformer(self) } configFontsAndColors() changeToIdle(animated: false) } open func configFontsAndColors() { placeHolderLabel.font = CGFont(placeHolderFontKey as CFString) textField.textColor = textColor textField.font = UIFont(name: inputFontName, size: inputFontSize) textField.tintColor = tintColor separatorView.backgroundColor = separatorColor } override open func layoutSubviews() { super.layoutSubviews() layout() } open func layout() { var currentX: CGFloat = leftInset if let iconImage = iconImage { iconImageView.isHidden = false iconImageView.image = iconImage iconImageView.frame = CGRect(x: currentX, y: viewHeight.half - iconSize.half, width: iconSize, height: iconSize) currentX += iconSize + imageInnerPadding } else { iconImageView.isHidden = true } let placeHolderUIFont = state == .idle ? UIFont(name: placeHolderFontKey, size: idlePlaceHolderFontSize) : UIFont(name: placeHolderFontKey, size: floatPlaceHolderFontSize) let placeHolderHeight: CGFloat = placeHolderUIFont!.lineHeight + 2 let textFieldHeight = textField.font!.lineHeight + 2 let inputHeight = placeHolderHeight + textInnerPadding + textFieldHeight let widthForInput = viewWidth - currentX - rightInset if state == .idle { placeHolderLabel.frame = CGRect(x: currentX, y: viewHeight.half - placeHolderHeight.half, width: widthForInput, height: idlePlaceHolderFontSize + 4) } else { placeHolderLabel.frame = CGRect(x: currentX, y: viewHeight.half - inputHeight.half, width: widthForInput, height: idlePlaceHolderFontSize + 4) } textField.frame = CGRect(x: currentX, y: viewHeight.half + inputHeight.half - textFieldHeight, width: widthForInput, height: textFieldHeight) separatorView.isHidden = !separatorEnabled separatorView.frame = CGRect(x: separatorLeftInset, y: viewHeight - 1, width: viewWidth - separatorLeftInset - separatorRightInset, height: 1) } open func changeToFloat(animated: Bool) { let animationDuration = animated ? self.animationDuration : 0.0 state = .float CATransaction.begin() CATransaction.setAnimationDuration(animationDuration) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)) placeHolderLabel.foregroundColor = floatPlaceHolderColor.cgColor placeHolderLabel.fontSize = floatPlaceHolderFontSize layout() CATransaction.commit() UIView.animate(withDuration: animationDuration, delay: 0.0, options: .curveEaseOut , animations: { self.textField.alpha = 1.0 } , completion: { _ in }) } open func changeToIdle(animated: Bool) { let animationDuration = animated ? self.animationDuration : 0.0 state = .idle CATransaction.begin() CATransaction.setAnimationDuration(animationDuration) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)) placeHolderLabel.foregroundColor = idlePlaceHolderColor.cgColor placeHolderLabel.fontSize = idlePlaceHolderFontSize layout() CATransaction.commit() UIView.animate(withDuration: animationDuration, delay: 0.0, options: .curveEaseOut , animations: { self.textField.alpha = 0.0 } , completion: { _ in }) } @objc open func focus() { textField.becomeFirstResponder() changeToFloat(animated: true) } @objc open func editingDidEnd() { if let text = textField.text, text.count > 0 { changeToFloat(animated: true) } else { changeToIdle(animated: true) } } }
mit
1b42937f01ac367e00606bf3c695707e
36.635802
175
0.730195
5.043011
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/_Shared/WaitBeatOverlay.swift
1
3409
import UIKit extension WaitBeatOverlay { class func addWaitBeatOverlay(toView: UIView, image: UIImage?, color: UIColor) { let overlay = WaitBeatOverlay(frame: toView.bounds, image: image, color: color) toView.addSubview(overlay) overlay.startAnimating() } class func removeWaitBeatOverlays(fromView: UIView) { let overlays = fromView.subviews.filter { $0 is WaitBeatOverlay } for overlay in overlays { overlay.removeFromSuperview() } } } class WaitBeatOverlay: UIView { var wrapper: UIView? var indicator: UIView? var wrapperWidth : CGFloat = 128.0 var wrapperHeight : CGFloat = 128.0 var wrapperCornerRadius: CGFloat = 8.0 var wrapperFrame : CGRect { let x = (self.bounds.size.width - wrapperWidth) * 0.5 let y = ((self.bounds.size.height - wrapperHeight) * 0.5) - wrapperHeight return CGRect(x: x, y: y, width: wrapperWidth, height: wrapperHeight) } var indicatorFrame : CGRect { guard let indicator = self.indicator else { return CGRect.zero } let indicatorWidth = indicator.frame.size.width let indicatorHeight = indicator.frame.size.height let x = (wrapperWidth - indicatorWidth) * 0.5 let y = (wrapperHeight - indicatorHeight) * 0.5 return CGRect(x: x, y: y, width: indicatorWidth, height: indicatorHeight) } init(frame: CGRect, image: UIImage?, color: UIColor) { super.init(frame: frame) self.createViewContent(image: image, color: color) } override init(frame: CGRect) { super.init(frame: frame) self.createViewContent(image: nil, color: UIColor.black) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.createViewContent(image: nil, color: UIColor.black) } override func layoutSubviews() { super.layoutSubviews() self.wrapper?.frame = wrapperFrame self.indicator?.frame = indicatorFrame } func startAnimating() { (self.indicator as? HeartThrobbable)?.startHeartBeatAnimation() } func stopAnimating() { (self.indicator as? HeartThrobbable)?.stopHeartBeatAnimation(resetSize: false, animated: true) } private func createViewContent(image: UIImage?, color: UIColor) { guard (self.bounds.size.width > 0), (self.bounds.size.height > 0) else { return } self.backgroundColor = UIColor.clear self.isUserInteractionEnabled = false let wrapper = self.createWrapper(color: color) let indicator = self.createActivityIndicator(image: image) indicator.center = wrapper.center wrapper.addSubview(indicator) self.addSubview(wrapper) self.wrapper = wrapper self.indicator = indicator } private func createWrapper(color: UIColor) -> UIView { let wrapper = UIView(frame: wrapperFrame) wrapper.backgroundColor = color wrapper.layer.cornerRadius = wrapperCornerRadius wrapper.clipsToBounds = true return wrapper } private func createActivityIndicator(image: UIImage?) -> UIView { if let image = image { return HeartThrobbableImageView(image: image) } else { return HeartThrobbableView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) } } }
apache-2.0
859d8d495c2d835de34d13406a2f1695
33.434343
102
0.647697
4.444589
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/Quick/Sources/Quick/Callsite.swift
147
759
import Foundation /** An object encapsulating the file and line number at which a particular example is defined. */ final public class Callsite: NSObject { /** The absolute path of the file in which an example is defined. */ public let file: String /** The line number on which an example is defined. */ public let line: UInt internal init(file: String, line: UInt) { self.file = file self.line = line } } /** Returns a boolean indicating whether two Callsite objects are equal. If two callsites are in the same file and on the same line, they must be equal. */ public func ==(lhs: Callsite, rhs: Callsite) -> Bool { return lhs.file == rhs.file && lhs.line == rhs.line }
apache-2.0
ad66d4af05ab10da6f7b3e958229b574
24.3
83
0.644269
4.216667
false
false
false
false
subinspathilettu/SJRefresh
SJRefresh/Classes/RefreshView.swift
1
11039
// // RefreshView.swift // Pods // // Created by Subins Jose on 05/10/16. // Copyright © 2016 Subins Jose. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit let contentOffsetKeyPath = "contentOffset" let contentSizeKeyPath = "contentSize" var kvoContext = "PullToRefreshKVOContext" typealias AnimationCompleteCallback = (_ percentage: CGFloat) -> Void typealias RefreshCompletionCallback = (Void) -> Void class RefreshView: UIView { // MARK: Variables var refreshCompletion: RefreshCompletionCallback? var animationCompletion: AnimationCompleteCallback? var pullImageView = UIImageView() var animationView = UIImageView() var animationPercentage: CGFloat = 0.0 let animationDuration: Double = 0.5 var scrollViewBounces = false var scrollViewInsets = UIEdgeInsets.zero var percentage: CGFloat = 0.0 { didSet { self.startAnimation() } } var isDefinite = false var state = SJRefreshState.pulling { didSet { if self.state == oldValue || animationView.animationImages?.count == 0 { return } switch self.state { case .stop: stopAnimating() case .finish: var time = DispatchTime.now() + Double(Int64(animationDuration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.stopAnimating() } time = DispatchTime.now() + Double(Int64((animationDuration * 2) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.removeFromSuperview() } case .refreshing: startAnimating() case .pulling, .triggered: break } } } var waveLayer: CAShapeLayer? // MARK: UIView override convenience init(frame: CGRect) { self.init(refreshCompletion: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(refreshCompletion: RefreshCompletionCallback?) { self.refreshCompletion = refreshCompletion precondition(SJRefresh.shared.theme != nil, "Provide a theme") var height: CGFloat = 0.0 if let viewHeight = SJRefresh.shared.theme?.heightForRefreshView() { height = viewHeight } let refreshViewFrame = CGRect(x: 0, y: -height, width: UIScreen.main.bounds.width, height: height) super.init(frame: refreshViewFrame) frame = refreshViewFrame setRefreshView() } func addPullWave() { backgroundColor = superview?.backgroundColor waveLayer = CAShapeLayer(layer: self.layer) waveLayer?.lineWidth = 1 waveLayer?.path = wavePath(amountX: 0.0, amountY: 0.0) waveLayer?.strokeColor = backgroundColor?.cgColor waveLayer?.fillColor = backgroundColor?.cgColor superview?.layer.addSublayer(waveLayer!) } func wavePath(amountX:CGFloat, amountY:CGFloat) -> CGPath { let w = self.frame.width let centerY:CGFloat = 0 let topLeftPoint = CGPoint(x: 0, y: centerY) let topMidPoint = CGPoint(x: w / 2 + amountX, y: centerY + amountY) let topRightPoint = CGPoint(x: w, y: centerY) let bezierPath = UIBezierPath() bezierPath.move(to: topLeftPoint) bezierPath.addQuadCurve(to: topRightPoint, controlPoint: topMidPoint) return bezierPath.cgPath } override func layoutSubviews() { super.layoutSubviews() let center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: self.frame.size.height / 2) pullImageView.center = center pullImageView.frame = pullImageView.frame.offsetBy(dx: 0, dy: 0) pullImageView.backgroundColor = .clear animationView.center = center } override func willMove(toSuperview superView: UIView!) { self.removeRegister() guard let scrollView = superView as? UIScrollView else { return } scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .initial, context: &kvoContext) } func setRefreshView() { loadBackgroundImageView() loadPullToRefreshArrowView() loadAnimationView() autoresizingMask = .flexibleWidth } func loadBackgroundImageView() { let backgroundView = UIImageView(frame: self.bounds) backgroundView.backgroundColor = SJRefresh.shared.theme?.backgroundColorForRefreshView() if let image = SJRefresh.shared.theme?.backgroundImageForRefreshView() { backgroundView.image = image } backgroundView.contentMode = .scaleAspectFill addSubview(backgroundView) } func loadPullToRefreshArrowView() { pullImageView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] addSubview(pullImageView) } func loadAnimationView() { if let animationImages = SJRefresh.shared.theme?.imagesForRefreshViewLoadingAnimation() { var animationframe = CGRect.zero if !animationImages.isEmpty { animationframe.size.width = animationImages[0].size.width animationframe.size.height = animationImages[0].size.height } animationView = UIImageView(frame: animationframe) animationView.animationImages = animationImages animationView.contentMode = .scaleAspectFit animationView.animationDuration = 0.5 animationView.isHidden = true animationView.backgroundColor = .clear addSubview(animationView) } } func animateImages(_ percentage: CGFloat) { if percentage != 0 && percentage > animationPercentage { startAnimation({ (percentage) in self.animationPercentage = percentage if percentage >= 100 { self.stopAnimating() } else { self.startAnimation() } }) } } func startAnimation() { if animationPercentage < percentage && percentage != 0 { startAnimation({ (percent) in self.animationPercentage = percent if percent >= 100 { self.stopAnimating() } else { self.startAnimation() } }) } } func removeRegister() { if let scrollView = superview as? UIScrollView { scrollView.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) } } deinit { self.removeRegister() } // MARK: KVO override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let scrollView = object as? UIScrollView else { return } if !(context == &kvoContext && keyPath == contentOffsetKeyPath) { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } // Pulling State Check let offsetY = scrollView.contentOffset.y if offsetY <= 0 { if abs(offsetY) < 80.0 { waveLayer?.path = wavePath(amountX: 0, amountY: abs(offsetY)) } if offsetY < -self.frame.size.height { // pulling or refreshing if scrollView.isDragging == false && self.state != .refreshing { //release the finger self.state = .refreshing //startAnimating } else if self.state != .refreshing { //reach the threshold self.state = .triggered } } else if self.state == .triggered { //starting point, start from pulling self.state = .pulling } if let pullImage = SJRefresh.shared.theme?.pullImageForRefreshView(state: state, pullPercentage: 0.0) { pullImageView.image = pullImage pullImageView.frame.size = pullImage.size } return //return for pull down } //push up let upHeight = offsetY + scrollView.frame.size.height - scrollView.contentSize.height if upHeight > 0 { return } } func startAnimating() { boundAnimation() animationView.isHidden = false startAnimation(nil) pullImageView.isHidden = true guard let scrollView = superview as? UIScrollView else { return } scrollViewBounces = scrollView.bounces scrollViewInsets = scrollView.contentInset var insets = scrollView.contentInset insets.top += frame.size.height scrollView.bounces = false UIView.animate(withDuration: animationDuration, delay: 0, options:[], animations: { scrollView.contentInset = insets }, completion: { _ in self.refreshCompletion?() }) } func boundAnimation() { waveLayer?.path = wavePath(amountX: 0, amountY: 0) let bounce = CAKeyframeAnimation(keyPath: "path") bounce.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) let values = [ self.wavePath(amountX: 0.0, amountY: 30), self.wavePath(amountX: 0.0, amountY: 20), self.wavePath(amountX: 0.0, amountY: 10), self.wavePath(amountX: 0.0, amountY: 0.0), self.wavePath(amountX: 0.0, amountY: -30), self.wavePath(amountX: 0.0, amountY: 25), self.wavePath(amountX: 0.0, amountY: -20), self.wavePath(amountX: 0.0, amountY: 15), self.wavePath(amountX: 0.0, amountY: -10), self.wavePath(amountX: 0.0, amountY: 5), self.wavePath(amountX: 0.0, amountY: 0.0) ] bounce.values = values bounce.duration = 1.0 bounce.isRemovedOnCompletion = true bounce.fillMode = kCAFillModeForwards bounce.delegate = self waveLayer?.add(bounce, forKey: "return") } func getAnimationStartIndex(_ completedPercentage: CGFloat) -> Int { var percentage = completedPercentage if percentage > self.percentage { percentage = self.percentage } let count = animationView.animationImages?.count let index = isDefinite ? Int(CGFloat(count!) * (percentage / 100.0)) : 0 return Int(index) } func getAnimationEndIndex(_ percentage: CGFloat) -> Int { let count = animationView.animationImages?.count let index = isDefinite ? Int(CGFloat(count!) * (percentage / 100.0)) : count! return Int(index) } func getAnimationImages(_ percentage: CGFloat) -> [CGImage] { var images = [CGImage]() let startIndex = getAnimationStartIndex(animationPercentage) let endIndex = getAnimationEndIndex(percentage) for index in startIndex..<endIndex { let image = animationView.animationImages?[index] images.append((image?.cgImage!)!) } return images } }
mit
8dc06e75d238bc62a3269109eed6907e
27.819843
99
0.697681
4.034357
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/EmailLogin/EmailLogin/EmailLoginReducer.swift
1
11499
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import ComposableArchitecture import ComposableNavigation import DIKit import FeatureAuthenticationDomain import Localization import ToolKit // MARK: - Type public enum EmailLoginAction: Equatable, NavigationAction { // MARK: - Alert public enum AlertAction: Equatable { case show(title: String, message: String) case dismiss } case alert(AlertAction) // MARK: - Transitions and Navigations case onAppear case route(RouteIntent<EmailLoginRoute>?) case continueButtonTapped // MARK: - Email case didChangeEmailAddress(String) // MARK: - Device Verification case sendDeviceVerificationEmail case didSendDeviceVerificationEmail(Result<EmptyValue, DeviceVerificationServiceError>) case setupSessionToken case setupSessionTokenReceived(Result<EmptyValue, SessionTokenServiceError>) // MARK: - Local Actions case verifyDevice(VerifyDeviceAction) // MARK: - Utils case none } private typealias EmailLoginLocalization = LocalizationConstants.FeatureAuthentication.EmailLogin // MARK: - Properties public struct EmailLoginState: Equatable, NavigationState { // MARK: - Navigation State public var route: RouteIntent<EmailLoginRoute>? // MARK: - Local States public var verifyDeviceState: VerifyDeviceState? // MARK: - Alert State var alert: AlertState<EmailLoginAction>? // MARK: - Email var emailAddress: String var isEmailValid: Bool // MARK: - Loading State var isLoading: Bool init() { route = nil emailAddress = "" isEmailValid = false isLoading = false verifyDeviceState = nil } } struct EmailLoginEnvironment { let app: AppProtocol let mainQueue: AnySchedulerOf<DispatchQueue> let sessionTokenService: SessionTokenServiceAPI let deviceVerificationService: DeviceVerificationServiceAPI let featureFlagsService: FeatureFlagsServiceAPI let errorRecorder: ErrorRecording let externalAppOpener: ExternalAppOpener let analyticsRecorder: AnalyticsEventRecorderAPI let walletRecoveryService: WalletRecoveryService let walletCreationService: WalletCreationService let walletFetcherService: WalletFetcherService let accountRecoveryService: AccountRecoveryServiceAPI let recaptchaService: GoogleRecaptchaServiceAPI let validateEmail: (String) -> Bool init( app: AppProtocol, mainQueue: AnySchedulerOf<DispatchQueue>, sessionTokenService: SessionTokenServiceAPI, deviceVerificationService: DeviceVerificationServiceAPI, featureFlagsService: FeatureFlagsServiceAPI, errorRecorder: ErrorRecording, externalAppOpener: ExternalAppOpener, analyticsRecorder: AnalyticsEventRecorderAPI, walletRecoveryService: WalletRecoveryService, walletCreationService: WalletCreationService, walletFetcherService: WalletFetcherService, accountRecoveryService: AccountRecoveryServiceAPI, recaptchaService: GoogleRecaptchaServiceAPI, validateEmail: @escaping (String) -> Bool = { $0.isEmail } ) { self.app = app self.mainQueue = mainQueue self.sessionTokenService = sessionTokenService self.deviceVerificationService = deviceVerificationService self.featureFlagsService = featureFlagsService self.errorRecorder = errorRecorder self.externalAppOpener = externalAppOpener self.analyticsRecorder = analyticsRecorder self.walletRecoveryService = walletRecoveryService self.walletCreationService = walletCreationService self.walletFetcherService = walletFetcherService self.accountRecoveryService = accountRecoveryService self.recaptchaService = recaptchaService self.validateEmail = validateEmail } } let emailLoginReducer = Reducer.combine( verifyDeviceReducer .optional() .pullback( state: \.verifyDeviceState, action: /EmailLoginAction.verifyDevice, environment: { VerifyDeviceEnvironment( app: $0.app, mainQueue: $0.mainQueue, deviceVerificationService: $0.deviceVerificationService, featureFlagsService: $0.featureFlagsService, errorRecorder: $0.errorRecorder, externalAppOpener: $0.externalAppOpener, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, accountRecoveryService: $0.accountRecoveryService, recaptchaService: $0.recaptchaService ) } ), Reducer< EmailLoginState, EmailLoginAction, EmailLoginEnvironment // swiftlint:disable closure_body_length > { state, action, environment in switch action { // MARK: - Alert case .alert(.show(let title, let message)): state.alert = AlertState( title: TextState(verbatim: title), message: TextState(verbatim: message), dismissButton: .default( TextState(LocalizationConstants.continueString), action: .send(.alert(.dismiss)) ) ) return .none case .alert(.dismiss): state.alert = nil return .none // MARK: - Transitions and Navigations case .onAppear: environment.analyticsRecorder.record( event: .loginViewed ) return .none case .route(let route): if let routeValue = route?.route { state.verifyDeviceState = .init(emailAddress: state.emailAddress) state.route = route return .none } else { state.verifyDeviceState = nil state.route = route return .none } case .continueButtonTapped: state.isLoading = true return Effect(value: .setupSessionToken) // MARK: - Email case .didChangeEmailAddress(let emailAddress): state.emailAddress = emailAddress state.isEmailValid = environment.validateEmail(emailAddress) return .none // MARK: - Device Verification case .sendDeviceVerificationEmail, .verifyDevice(.sendDeviceVerificationEmail): guard state.isEmailValid else { state.isLoading = false return .none } state.isLoading = true state.verifyDeviceState?.sendEmailButtonIsLoading = true return environment .deviceVerificationService .sendDeviceVerificationEmail(to: state.emailAddress) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> EmailLoginAction in switch result { case .success: return .didSendDeviceVerificationEmail(.success(.noValue)) case .failure(let error): return .didSendDeviceVerificationEmail(.failure(error)) } } case .didSendDeviceVerificationEmail(let response): state.isLoading = false state.verifyDeviceState?.sendEmailButtonIsLoading = false if case .failure(let error) = response { switch error { case .recaptchaError, .missingSessionToken: return Effect( value: .alert( .show( title: EmailLoginLocalization.Alerts.SignInError.title, message: EmailLoginLocalization.Alerts.SignInError.message ) ) ) case .networkError: // still go to verify device screen if there is network error break case .expiredEmailCode, .missingWalletInfo: // not errors related to send verification email break } } return Effect(value: .navigate(to: .verifyDevice)) case .setupSessionToken: return environment .sessionTokenService .setupSessionToken() .map { _ in EmptyValue.noValue } .receive(on: environment.mainQueue) .catchToEffect() .map(EmailLoginAction.setupSessionTokenReceived) case .setupSessionTokenReceived(.success): return Effect(value: .sendDeviceVerificationEmail) case .setupSessionTokenReceived(.failure(let error)): state.isLoading = false environment.errorRecorder.error(error) return Effect( value: .alert( .show( title: EmailLoginLocalization.Alerts.GenericNetworkError.title, message: EmailLoginLocalization.Alerts.GenericNetworkError.message ) ) ) // MARK: - Local Reducers case .verifyDevice(.deviceRejected): return .dismiss() case .verifyDevice: // handled in verify device reducer return .none // MARK: - Utils case .none: return .none } } ) .analytics() // MARK: - Private extension Reducer where Action == EmailLoginAction, State == EmailLoginState, Environment == EmailLoginEnvironment { /// Helper reducer for analytics tracking fileprivate func analytics() -> Self { combined( with: Reducer< EmailLoginState, EmailLoginAction, EmailLoginEnvironment > { _, action, environment in switch action { case .sendDeviceVerificationEmail: environment.analyticsRecorder.record( event: .loginClicked( origin: .navigation ) ) return .none case .didSendDeviceVerificationEmail(.success): environment.analyticsRecorder.record( event: .loginIdentifierEntered( identifierType: .email ) ) return .none case .didSendDeviceVerificationEmail(.failure(let error)): environment.analyticsRecorder.record( event: .loginIdentifierFailed( errorMessage: error.localizedDescription ) ) return .none default: return .none } } ) } }
lgpl-3.0
553b9c8b2be780bde56ac1d0bb77cd85
31.945559
97
0.587493
6.452301
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Feedbacks.swift
2
15547
// // Feedbacks.swift // RxExample // // Created by Krunoslav Zaher on 5/1/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa // Taken from RxFeedback repo /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter areEqual: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Query?, areEqual: @escaping (Query, Query) -> Bool, effects: @escaping (Query) -> Observable<Event> ) -> (ObservableSchedulerContext<State>) -> Observable<Event> { return { state in return state.map(query) .distinctUntilChanged { lhs, rhs in switch (lhs, rhs) { case (.none, .none): return true case (.none, .some): return false case (.some, .none): return false case (.some(let lhs), .some(let rhs)): return areEqual(lhs, rhs) } } .flatMapLatest { (control: Query?) -> Observable<Event> in guard let control = control else { return Observable<Event>.empty() } return effects(control) .enqueue(state.scheduler) } } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query: Equatable, Event>( query: @escaping (State) -> Query?, effects: @escaping (Query) -> Observable<Event> ) -> (ObservableSchedulerContext<State>) -> Observable<Event> { return react(query: query, areEqual: { $0 == $1 }, effects: effects) } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter areEqual: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Query?, areEqual: @escaping (Query, Query) -> Bool, effects: @escaping (Query) -> Signal<Event> ) -> (Driver<State>) -> Signal<Event> { return { state in let observableSchedulerContext = ObservableSchedulerContext<State>( source: state.asObservable(), scheduler: Signal<Event>.SharingStrategy.scheduler.async ) return react(query: query, areEqual: areEqual, effects: { effects($0).asObservable() })(observableSchedulerContext) .asSignal(onErrorSignalWith: .empty()) } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query: Equatable, Event>( query: @escaping (State) -> Query?, effects: @escaping (Query) -> Signal<Event> ) -> (Driver<State>) -> Signal<Event> { return { state in let observableSchedulerContext = ObservableSchedulerContext<State>( source: state.asObservable(), scheduler: Signal<Event>.SharingStrategy.scheduler.async ) return react(query: query, effects: { effects($0).asObservable() })(observableSchedulerContext) .asSignal(onErrorSignalWith: .empty()) } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Query?, effects: @escaping (Query) -> Observable<Event> ) -> (ObservableSchedulerContext<State>) -> Observable<Event> { return { state in return state.map(query) .distinctUntilChanged { $0 != nil } .flatMapLatest { (control: Query?) -> Observable<Event> in guard let control = control else { return Observable<Event>.empty() } return effects(control) .enqueue(state.scheduler) } } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns a value, that value is being passed into `effects` lambda to decide which effects should be performed. In case new `query` is different from the previous one, new effects are calculated by using `effects` lambda and then performed. When `query` returns `nil`, feedback loops doesn't perform any effect. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query result. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Query?, effects: @escaping (Query) -> Signal<Event> ) -> (Driver<State>) -> Signal<Event> { return { state in let observableSchedulerContext = ObservableSchedulerContext<State>( source: state.asObservable(), scheduler: Signal<Event>.SharingStrategy.scheduler.async ) return react(query: query, effects: { effects($0).asObservable() })(observableSchedulerContext) .asSignal(onErrorSignalWith: .empty()) } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns some set of values, each value is being passed into `effects` lambda to decide which effects should be performed. * Effects are not interrupted for elements in the new `query` that were present in the `old` query. * Effects are cancelled for elements present in `old` query but not in `new` query. * In case new elements are present in `new` query (and not in `old` query) they are being passed to the `effects` lambda and resulting effects are being performed. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query element. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Set<Query>, effects: @escaping (Query) -> Observable<Event> ) -> (ObservableSchedulerContext<State>) -> Observable<Event> { return { state in let query = state.map(query) .share(replay: 1) let newQueries = Observable.zip(query, query.startWith(Set())) { $0.subtracting($1) } let asyncScheduler = state.scheduler.async return newQueries.flatMap { controls in return Observable<Event>.merge(controls.map { control -> Observable<Event> in return effects(control) .enqueue(state.scheduler) .takeUntilWithCompletedAsync(query.filter { !$0.contains(control) }, scheduler: asyncScheduler) }) } } } extension ObservableType { // This is important to avoid reentrancy issues. Completed event is only used for cleanup fileprivate func takeUntilWithCompletedAsync<O>(_ other: Observable<O>, scheduler: ImmediateSchedulerType) -> Observable<Element> { // this little piggy will delay completed event let completeAsSoonAsPossible = Observable<Element>.empty().observeOn(scheduler) return other .take(1) .map { _ in completeAsSoonAsPossible } // this little piggy will ensure self is being run first .startWith(self.asObservable()) // this little piggy will ensure that new events are being blocked immediately .switchLatest() } } /** * State: State type of the system. * Query: Subset of state used to control the feedback loop. When `query` returns some set of values, each value is being passed into `effects` lambda to decide which effects should be performed. * Effects are not interrupted for elements in the new `query` that were present in the `old` query. * Effects are cancelled for elements present in `old` query but not in `new` query. * In case new elements are present in `new` query (and not in `old` query) they are being passed to the `effects` lambda and resulting effects are being performed. - parameter query: Part of state that controls feedback loop. - parameter effects: Chooses which effects to perform for certain query element. - returns: Feedback loop performing the effects. */ public func react<State, Query, Event>( query: @escaping (State) -> Set<Query>, effects: @escaping (Query) -> Signal<Event> ) -> (Driver<State>) -> Signal<Event> { return { (state: Driver<State>) -> Signal<Event> in let observableSchedulerContext = ObservableSchedulerContext<State>( source: state.asObservable(), scheduler: Signal<Event>.SharingStrategy.scheduler.async ) return react(query: query, effects: { effects($0).asObservable() })(observableSchedulerContext) .asSignal(onErrorSignalWith: .empty()) } } extension Observable { fileprivate func enqueue(_ scheduler: ImmediateSchedulerType) -> Observable<Element> { return self // observe on is here because results should be cancelable .observeOn(scheduler.async) // subscribe on is here because side-effects also need to be cancelable // (smooths out any glitches caused by start-cancel immediately) .subscribeOn(scheduler.async) } } /** Contains subscriptions and events. - `subscriptions` map a system state to UI presentation. - `events` map events from UI to events of a given system. */ public class Bindings<Event>: Disposable { fileprivate let subscriptions: [Disposable] fileprivate let events: [Observable<Event>] /** - parameters: - subscriptions: mappings of a system state to UI presentation. - events: mappings of events from UI to events of a given system */ public init(subscriptions: [Disposable], events: [Observable<Event>]) { self.subscriptions = subscriptions self.events = events } /** - parameters: - subscriptions: mappings of a system state to UI presentation. - events: mappings of events from UI to events of a given system */ public init(subscriptions: [Disposable], events: [Signal<Event>]) { self.subscriptions = subscriptions self.events = events.map { $0.asObservable() } } public func dispose() { for subscription in subscriptions { subscription.dispose() } } } /** Bi-directional binding of a system State to external state machine and events from it. */ public func bind<State, Event>(_ bindings: @escaping (ObservableSchedulerContext<State>) -> (Bindings<Event>)) -> (ObservableSchedulerContext<State>) -> Observable<Event> { return { (state: ObservableSchedulerContext<State>) -> Observable<Event> in return Observable<Event>.using({ () -> Bindings<Event> in return bindings(state) }, observableFactory: { (bindings: Bindings<Event>) -> Observable<Event> in return Observable<Event>.merge(bindings.events) .enqueue(state.scheduler) }) } } /** Bi-directional binding of a system State to external state machine and events from it. Strongify owner. */ public func bind<State, Event, WeakOwner>(_ owner: WeakOwner, _ bindings: @escaping (WeakOwner, ObservableSchedulerContext<State>) -> (Bindings<Event>)) -> (ObservableSchedulerContext<State>) -> Observable<Event> where WeakOwner: AnyObject { return bind(bindingsStrongify(owner, bindings)) } /** Bi-directional binding of a system State to external state machine and events from it. */ public func bind<State, Event>(_ bindings: @escaping (Driver<State>) -> (Bindings<Event>)) -> (Driver<State>) -> Signal<Event> { return { (state: Driver<State>) -> Signal<Event> in return Observable<Event>.using({ () -> Bindings<Event> in return bindings(state) }, observableFactory: { (bindings: Bindings<Event>) -> Observable<Event> in return Observable<Event>.merge(bindings.events) }) .enqueue(Signal<Event>.SharingStrategy.scheduler) .asSignal(onErrorSignalWith: .empty()) } } /** Bi-directional binding of a system State to external state machine and events from it. Strongify owner. */ public func bind<State, Event, WeakOwner>(_ owner: WeakOwner, _ bindings: @escaping (WeakOwner, Driver<State>) -> (Bindings<Event>)) -> (Driver<State>) -> Signal<Event> where WeakOwner: AnyObject { return bind(bindingsStrongify(owner, bindings)) } private func bindingsStrongify<Event, O, WeakOwner>(_ owner: WeakOwner, _ bindings: @escaping (WeakOwner, O) -> (Bindings<Event>)) -> (O) -> (Bindings<Event>) where WeakOwner: AnyObject { return { [weak owner] state -> Bindings<Event> in guard let strongOwner = owner else { return Bindings(subscriptions: [], events: [Observable<Event>]()) } return bindings(strongOwner, state) } }
mit
d287ed38757d42c7ccc03fdaf571ceaa
40.902965
172
0.676959
4.56698
false
false
false
false
apple/swift-nio-http2
Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift
1
101588
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore import NIOEmbedded import NIOHTTP1 @testable import NIOHPACK // for HPACKHeaders initializers @testable import NIOHTTP2 private extension Channel { /// Adds a simple no-op `HTTP2StreamMultiplexer` to the pipeline. func addNoOpMultiplexer(mode: NIOHTTP2Handler.ParserMode) { XCTAssertNoThrow(try self.pipeline.addHandler(HTTP2StreamMultiplexer(mode: mode, channel: self) { channel in self.eventLoop.makeSucceededFuture(()) }).wait()) } } private struct MyError: Error { } /// A handler that asserts the frames received match the expected set. private final class FramePayloadExpecter: ChannelInboundHandler { typealias InboundIn = HTTP2Frame.FramePayload typealias OutboundOut = HTTP2Frame.FramePayload private let expectedFrames: [HTTP2Frame.FramePayload] private var actualFrames: [HTTP2Frame.FramePayload] = [] private var inactive = false init(expectedPayload: [HTTP2Frame.FramePayload]) { self.expectedFrames = expectedPayload } func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertFalse(self.inactive) let frame = self.unwrapInboundIn(data) self.actualFrames.append(frame) } func channelInactive(context: ChannelHandlerContext) { XCTAssertFalse(self.inactive) self.inactive = true XCTAssertEqual(self.expectedFrames.count, self.actualFrames.count) for (idx, expectedFrame) in self.expectedFrames.enumerated() { let actualFrame = self.actualFrames[idx] expectedFrame.assertFramePayloadMatches(this: actualFrame) } } } final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { var channel: EmbeddedChannel! override func setUp() { self.channel = EmbeddedChannel() } override func tearDown() { self.channel = nil } private func activateStream(_ streamID: HTTP2StreamID) { let activated = NIOHTTP2StreamCreatedEvent(streamID: streamID, localInitialWindowSize: 16384, remoteInitialWindowSize: 16384) self.channel.pipeline.fireUserInboundEventTriggered(activated) } func testMultiplexerIgnoresFramesOnStream0() throws { self.channel.addNoOpMultiplexer(mode: .server) let simplePingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) XCTAssertNoThrow(try self.channel.finish()) } func testHeadersFramesCreateNewChannels() throws { var channelCount = 0 let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelCount += 1 return channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's send a bunch of headers frames. for streamID in stride(from: 1, to: 100, by: 2) { let frame = HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } XCTAssertEqual(channelCount, 50) XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseThemselvesWhenToldTo() throws { var completedChannelCount = 0 var closeFutures: [EventLoopFuture<Void>] = [] let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in closeFutures.append(channel.closeFuture) channel.closeFuture.whenSuccess { completedChannelCount += 1 } return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's send a bunch of headers frames with endStream on them. This should open some streams. let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } XCTAssertEqual(completedChannelCount, 0) // Now we send them all a clean exit. for streamID in streamIDs { let event = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(event) } (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage all the promises should be completed. XCTAssertEqual(completedChannelCount, 50) XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseAfterResetStreamFrameFirstThenEvent() throws { var closeError: Error? = nil XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTAssertNil(closeError) channel.closeFuture.whenFailure { closeError = $0 } return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload])) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) XCTAssertNil(closeError) // Now we can send a RST_STREAM frame. XCTAssertNoThrow(try self.channel.writeInbound(rstStreamFrame)) // Now we send the user event. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate error code. XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) XCTAssertNoThrow(try self.channel.finish()) } func testChannelsCloseAfterGoawayFrameFirstThenEvent() throws { var closeError: Error? = nil XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTAssertNil(closeError) channel.closeFuture.whenFailure { closeError = $0 } // The channel won't see the goaway frame. return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload])) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open the stream up. XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) XCTAssertNil(closeError) // Now we can send a GOAWAY frame. This will close the stream. XCTAssertNoThrow(try self.channel.writeInbound(goAwayFrame)) // Now we send the user event. let userEvent = StreamClosedEvent(streamID: streamID, reason: .refusedStream) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) (self.channel.eventLoop as! EmbeddedEventLoop).run() // At this stage the stream should be closed with the appropriate manufactured error code. XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .refusedStream)) XCTAssertNoThrow(try self.channel.finish()) } func testFramesForUnknownStreamsAreReported() throws { self.channel.addNoOpMultiplexer(mode: .server) var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let streamID = HTTP2StreamID(5) let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertThrowsError(try self.channel.writeInbound(dataFrame)) { error in XCTAssertEqual(streamID, (error as? NIOHTTP2Errors.NoSuchStream).map { $0.streamID }) } self.channel.assertNoFramesReceived() XCTAssertNoThrow(try self.channel.finish()) } func testFramesForClosedStreamsAreReported() throws { self.channel.addNoOpMultiplexer(mode: .server) // We need to open the stream, then close it. A headers frame will open it, and then the closed event will close it. let streamID = HTTP2StreamID(5) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) (self.channel.eventLoop as! EmbeddedEventLoop).run() // Ok, now we can send a DATA frame for the now-closed stream. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertThrowsError(try self.channel.writeInbound(dataFrame)) { error in XCTAssertEqual(streamID, (error as? NIOHTTP2Errors.NoSuchStream).map { $0.streamID }) } self.channel.assertNoFramesReceived() XCTAssertNoThrow(try self.channel.finish()) } func testClosingIdleChannels() throws { let frameReceiver = FrameWriteRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's send a bunch of headers frames. These will all be answered by RST_STREAM frames. let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } let expectedFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .rstStream(.cancel)) } XCTAssertEqual(expectedFrames.count, frameReceiver.flushedWrites.count) for (idx, expectedFrame) in expectedFrames.enumerated() { let actualFrame = frameReceiver.flushedWrites[idx] expectedFrame.assertFrameMatches(this: actualFrame) } XCTAssertNoThrow(try self.channel.finish()) } func testClosingActiveChannels() throws { let frameReceiver = FrameWriteRecorder() let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) // The channel should now be active. let childChannel = try channelPromise.futureResult.wait() XCTAssertTrue(childChannel.isActive) // Now we close it. This triggers a RST_STREAM frame. childChannel.close(promise: nil) XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) XCTAssertNoThrow(try self.channel.finish()) } func testClosePromiseIsSatisfiedWithTheEvent() throws { let frameReceiver = FrameWriteRecorder() let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) // The channel should now be active. let childChannel = try channelPromise.futureResult.wait() XCTAssertTrue(childChannel.isActive) // Now we close it. This triggers a RST_STREAM frame. The channel will not be closed at this time. var closed = false childChannel.close().whenComplete { _ in closed = true } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) XCTAssertFalse(closed) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertTrue(closed) XCTAssertNoThrow(try self.channel.finish()) } func testMultipleClosePromisesAreSatisfied() throws { let frameReceiver = FrameWriteRecorder() let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(1) // The channel should now be active. let childChannel = try channelPromise.futureResult.wait() XCTAssertTrue(childChannel.isActive) // Now we close it several times. This triggers one RST_STREAM frame. The channel will not be closed at this time. var firstClosed = false var secondClosed = false var thirdClosed = false childChannel.close().whenComplete { _ in XCTAssertFalse(firstClosed) XCTAssertFalse(secondClosed) XCTAssertFalse(thirdClosed) firstClosed = true } childChannel.close().whenComplete { _ in XCTAssertTrue(firstClosed) XCTAssertFalse(secondClosed) XCTAssertFalse(thirdClosed) secondClosed = true } childChannel.close().whenComplete { _ in XCTAssertTrue(firstClosed) XCTAssertTrue(secondClosed) XCTAssertFalse(thirdClosed) thirdClosed = true } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) XCTAssertFalse(thirdClosed) // Now send the stream closed event. This will satisfy the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertTrue(thirdClosed) XCTAssertNoThrow(try self.channel.finish()) } func testClosePromiseFailsWithError() throws { let frameReceiver = FrameWriteRecorder() let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) // The channel should now be active. let childChannel = try channelPromise.futureResult.wait() XCTAssertTrue(childChannel.isActive) // Now we close it. This triggers a RST_STREAM frame. The channel will not be closed at this time. var closeError: Error? = nil childChannel.close().whenFailure { closeError = $0 } XCTAssertEqual(frameReceiver.flushedWrites.count, 1) frameReceiver.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) XCTAssertNil(closeError) // Now send the stream closed event. This will fail the close promise. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) XCTAssertNoThrow(try self.channel.finish()) } func testFramesAreNotDeliveredUntilStreamIsSetUp() throws { let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let setupCompletePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { setupCompletePromise.futureResult } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(1) // The channel should now be available, but no frames should have been received on either the parent or child channel. let childChannel = try channelPromise.futureResult.wait() let frameRecorder = try childChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).wait() self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Send a few data frames for this stream, which should also not go through. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) for _ in 0..<5 { XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) } self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Use a PING frame to check that the channel is still functioning. let ping = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) XCTAssertNoThrow(try self.channel.writeInbound(ping)) try self.channel.assertReceivedFrame().assertPingFrameMatches(this: ping) self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Ok, complete the setup promise. This should trigger all the frames to be delivered. setupCompletePromise.succeed(()) self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 6) frameRecorder.receivedFrames[0].assertHeadersFramePayloadMatches(this: frame.payload) for idx in 1...5 { frameRecorder.receivedFrames[idx].assertDataFramePayloadMatches(this: dataFrame.payload) } XCTAssertNoThrow(try self.channel.finish()) } func testFramesAreNotDeliveredIfSetUpFails() throws { let writeRecorder = FrameWriteRecorder() let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() let setupCompletePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channelPromise.succeed(channel) return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { setupCompletePromise.futureResult } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's send a headers frame to open the stream, along with some DATA frames. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) for _ in 0..<5 { XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) } // The channel should now be available, but no frames should have been received on either the parent or child channel. let childChannel = try channelPromise.futureResult.wait() let frameRecorder = try childChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).wait() self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Ok, fail the setup promise. This should deliver a RST_STREAM frame, but not yet close the channel. // The channel should, however, be inactive. var channelClosed = false childChannel.closeFuture.whenComplete { _ in channelClosed = true } XCTAssertEqual(writeRecorder.flushedWrites.count, 0) XCTAssertFalse(channelClosed) setupCompletePromise.fail(MyError()) self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertFalse(childChannel.isActive) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) writeRecorder.flushedWrites[0].assertRstStreamFrame(streamID: streamID, errorCode: .cancel) // Even delivering a new DATA frame should do nothing. XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Now sending the stream closed event should complete the closure. All frames should be dropped. No new writes. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertFalse(childChannel.isActive) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) XCTAssertFalse(channelClosed) (childChannel.eventLoop as! EmbeddedEventLoop).run() XCTAssertTrue(channelClosed) XCTAssertNoThrow(try self.channel.finish()) } func testFlushingOneChannelDoesntFlushThemAll() throws { let writeTracker = FrameWriteRecorder() var channels: [Channel] = [] let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channels.append(channel) return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open two streams. let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) for streamID in [firstStreamID, secondStreamID] { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } XCTAssertEqual(channels.count, 2) // We will now write a headers frame to each channel. Neither frame should be written to the connection. To verify this // we will flush the parent channel. for (idx, _) in [firstStreamID, secondStreamID].enumerated() { let frame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) channels[idx].write(frame, promise: nil) } self.channel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 0) // Now we're going to flush only the first child channel. This should cause one flushed write. channels[0].flush() XCTAssertEqual(writeTracker.flushedWrites.count, 1) // Now the other. channels[1].flush() XCTAssertEqual(writeTracker.flushedWrites.count, 2) XCTAssertNoThrow(try self.channel.finish()) } func testUnflushedWritesFailOnClose() throws { var childChannel: Channel? = nil let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in childChannel = channel return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) // We will now write a headers frame to the channel, but don't flush it. var writeError: Error? = nil let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) childChannel!.write(responseFrame).whenFailure { writeError = $0 } XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertEqual(writeError as? ChannelError, ChannelError.eof) XCTAssertNoThrow(try self.channel.finish()) } func testUnflushedWritesFailOnError() throws { var childChannel: Channel? = nil let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in childChannel = channel return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) // We will now write a headers frame to the channel, but don't flush it. var writeError: Error? = nil let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) childChannel!.write(responseFrame).whenFailure { writeError = $0 } XCTAssertNil(writeError) // Now we're going to deliver a normal close to the stream. let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) XCTAssertNoThrow(try self.channel.finish()) } func testWritesFailOnClosedStreamChannels() throws { var childChannel: Channel? = nil let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in childChannel = channel return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertNotNil(channel) // Now let's close it. let userEvent = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) // We will now write a headers frame to the channel. This should fail immediately. var writeError: Error? = nil let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())) childChannel!.write(responseFrame).whenFailure { writeError = $0 } XCTAssertEqual(writeError as? ChannelError, ChannelError.ioOnClosedChannel) XCTAssertNoThrow(try self.channel.finish()) } func testReadPullsInAllFrames() throws { var childChannel: Channel? = nil let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture<Void> in childChannel = channel // We're going to disable autoRead on this channel. return channel.getOption(ChannelOptions.autoRead).map { XCTAssertTrue($0) }.flatMap { channel.setOption(ChannelOptions.autoRead, value: false) }.flatMap { channel.getOption(ChannelOptions.autoRead) }.map { XCTAssertFalse($0) }.flatMap { channel.pipeline.addHandler(frameRecorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(1) XCTAssertNotNil(childChannel) // Now we're going to deliver 5 data frames for this stream. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") for _ in 0..<5 { let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) } // These frames should not have been delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // We'll call read() on the child channel. childChannel!.read() // All frames should now have been delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 6) frameRecorder.receivedFrames[0].assertFramePayloadMatches(this: frame.payload) for idx in 1...5 { frameRecorder.receivedFrames[idx].assertDataFramePayload(endStream: false, payload: buffer) } XCTAssertNoThrow(try self.channel.finish()) } func testReadIsPerChannel() throws { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) // We don't have access to the streamID in the inbound stream initializer; we have to track // the expected ID here. var expectedStreamID = 1 var autoRead = false var frameRecorders: [HTTP2StreamID: InboundFramePayloadRecorder] = [:] let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture<Void> in let recorder = InboundFramePayloadRecorder() frameRecorders[HTTP2StreamID(expectedStreamID)] = recorder expectedStreamID += 2 // We'll disable auto read on the first channel only. let autoReadValue = autoRead autoRead = true return channel.setOption(ChannelOptions.autoRead, value: autoReadValue).flatMap { channel.pipeline.addHandler(recorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open two streams. for streamID in [firstStreamID, secondStreamID] { let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } XCTAssertEqual(frameRecorders.count, 2) // Stream 1 should not have received a frame, stream 3 should. XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 1) // Deliver a DATA frame to each stream, which should also have gone into stream 3 but not stream 1. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") for streamID in [firstStreamID, secondStreamID] { let frame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } // Stream 1 should not have received a frame, stream 3 should. XCTAssertEqual(frameRecorders[firstStreamID]!.receivedFrames.count, 0) XCTAssertEqual(frameRecorders[secondStreamID]!.receivedFrames.count, 2) XCTAssertNoThrow(try self.channel.finish()) } func testReadWillCauseAutomaticFrameDelivery() throws { var childChannel: Channel? = nil let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture<Void> in childChannel = channel // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { channel.pipeline.addHandler(frameRecorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) XCTAssertNotNil(childChannel) // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Call read, the header frame will come through. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Call read again, nothing happens. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered. XCTAssertEqual(frameRecorder.receivedFrames.count, 2) // Delivering another data frame does nothing. XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertEqual(frameRecorder.receivedFrames.count, 2) XCTAssertNoThrow(try self.channel.finish()) } func testReadWithNoPendingDataCausesReadOnParentChannel() throws { var childChannel: Channel? = nil let readCounter = ReadCounter() let frameRecorder = InboundFramePayloadRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture<Void> in childChannel = channel // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { channel.pipeline.addHandler(frameRecorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(readCounter).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) XCTAssertNotNil(childChannel) // This stream should have seen no frames. XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // There should be no calls to read. XCTAssertEqual(readCounter.readCount, 0) // Call read, the header frame will come through. No calls to read on the parent stream. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) XCTAssertEqual(readCounter.readCount, 0) // Call read again, read is called on the parent stream. No frames delivered. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) XCTAssertEqual(readCounter.readCount, 1) // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered. No extra call to read. XCTAssertEqual(frameRecorder.receivedFrames.count, 2) XCTAssertEqual(readCounter.readCount, 1) // Another call to read issues a read to the parent stream. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) XCTAssertEqual(readCounter.readCount, 2) // Another call to read, this time does not issue a read to the parent stream. childChannel!.read() XCTAssertEqual(frameRecorder.receivedFrames.count, 2) XCTAssertEqual(readCounter.readCount, 2) // Delivering two more frames does not cause another call to read, and only one frame // is delivered. XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertEqual(frameRecorder.receivedFrames.count, 3) XCTAssertEqual(readCounter.readCount, 2) XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosure() throws { var handlerRemoved = false let handlerRemovedPromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. XCTAssertFalse(handlerRemoved) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: nil) self.channel.pipeline.fireUserInboundEventTriggered(event) XCTAssertFalse(handlerRemoved) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertTrue(handlerRemoved) XCTAssertNoThrow(try self.channel.finish()) } func testHandlersAreRemovedOnClosureWithError() throws { var handlerRemoved = false let handlerRemovedPromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved = true } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) // No handlerRemoved so far. XCTAssertFalse(handlerRemoved) // Now we send the channel a clean exit. let event = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(event) XCTAssertFalse(handlerRemoved) // The handlers will only be removed after we spin the loop. (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertTrue(handlerRemoved) XCTAssertNoThrow(try self.channel.finish()) } func testCreatingOutboundChannel() throws { let configurePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() var createdChannelCount = 0 var configuredChannelCount = 0 var streamIDs = Array<HTTP2StreamID>() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) for _ in 0..<3 { let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() multiplexer.createStreamChannel(promise: channelPromise) { channel in createdChannelCount += 1 return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in configuredChannelCount += 1 // Write some headers: the flush will trigger a stream ID to be assigned to the channel. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in streamIDs.append(streamID) } } } } XCTAssertEqual(createdChannelCount, 0) XCTAssertEqual(configuredChannelCount, 0) XCTAssertEqual(streamIDs.count, 0) (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertEqual(createdChannelCount, 3) XCTAssertEqual(configuredChannelCount, 0) XCTAssertEqual(streamIDs.count, 0) configurePromise.succeed(()) XCTAssertEqual(createdChannelCount, 3) XCTAssertEqual(configuredChannelCount, 3) XCTAssertEqual(streamIDs, [2, 4, 6].map { HTTP2StreamID($0) }) XCTAssertNoThrow(try self.channel.finish()) } func testCreatingOutboundChannelClient() throws { let configurePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() var createdChannelCount = 0 var configuredChannelCount = 0 var streamIDs = Array<HTTP2StreamID>() let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) for _ in 0..<3 { let channelPromise: EventLoopPromise<Channel> = self.channel.eventLoop.makePromise() multiplexer.createStreamChannel(promise: channelPromise) { channel in createdChannelCount += 1 return configurePromise.futureResult } channelPromise.futureResult.whenSuccess { channel in configuredChannelCount += 1 // Write some headers: the flush will trigger a stream ID to be assigned to the channel. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in streamIDs.append(streamID) } } } } XCTAssertEqual(createdChannelCount, 0) XCTAssertEqual(configuredChannelCount, 0) XCTAssertEqual(streamIDs.count, 0) (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertEqual(createdChannelCount, 3) XCTAssertEqual(configuredChannelCount, 0) XCTAssertEqual(streamIDs.count, 0) configurePromise.succeed(()) XCTAssertEqual(createdChannelCount, 3) XCTAssertEqual(configuredChannelCount, 3) XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) XCTAssertNoThrow(try self.channel.finish()) } func testWritesOnCreatedChannelAreDelayed() throws { let configurePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() var childChannel: Channel? = nil XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in childChannel = channel return configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertNotNil(childChannel) childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())), promise: nil) XCTAssertEqual(writeRecorder.flushedWrites.count, 0) configurePromise.succeed(()) (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertEqual(writeRecorder.flushedWrites.count, 1) XCTAssertNoThrow(try self.channel.finish()) } func testWritesAreCancelledOnFailingInitializer() throws { let configurePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() var childChannel: Channel? = nil let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in childChannel = channel return configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() var writeError: Error? = nil childChannel!.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders()))).whenFailure { writeError = $0 } XCTAssertNil(writeError) configurePromise.fail(MyError()) XCTAssertNotNil(writeError) XCTAssertTrue(writeError is MyError) XCTAssertNoThrow(try self.channel.finish()) } func testFailingInitializerDoesNotWrite() throws { let configurePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in return configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() configurePromise.fail(MyError()) XCTAssertEqual(writeRecorder.flushedWrites.count, 0) XCTAssertNoThrow(try self.channel.finish()) } func testCreatedChildChannelDoesNotActivateEarly() throws { var activated = false let activePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { activated = true }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertFalse(activated) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) XCTAssertTrue(activated) XCTAssertNoThrow(try self.channel.finish()) } func testCreatedChildChannelActivatesIfParentIsActive() throws { var activated = false let activePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { activated = true }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8765)).wait()) XCTAssertFalse(activated) multiplexer.createStreamChannel(promise: nil) { channel in return channel.pipeline.addHandler(activeRecorder) } (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertTrue(activated) XCTAssertNoThrow(try self.channel.finish()) } func testInitiatedChildChannelActivates() throws { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) var activated = false let activePromise: EventLoopPromise<Void> = self.channel.eventLoop.makePromise() let activeRecorder = ActiveHandler(activatedPromise: activePromise) activePromise.futureResult.map { activated = true }.whenFailure { (_: Error) in XCTFail("Activation promise must not fail") } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in return channel.pipeline.addHandler(activeRecorder) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) self.channel.pipeline.fireChannelActive() // Open a new stream. XCTAssertFalse(activated) let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) XCTAssertTrue(activated) XCTAssertNoThrow(try self.channel.finish()) } func testMultiplexerIgnoresPriorityFrames() throws { self.channel.addNoOpMultiplexer(mode: .server) let simplePingFrame = HTTP2Frame(streamID: 106, payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15))) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) XCTAssertNoThrow(try self.channel.finish()) } func testMultiplexerForwardsActiveToParent() throws { self.channel.addNoOpMultiplexer(mode: .client) var didActivate = false let activePromise = self.channel.eventLoop.makePromise(of: Void.self) activePromise.futureResult.whenSuccess { didActivate = true } XCTAssertNoThrow(try self.channel.pipeline.addHandler(ActiveHandler(activatedPromise: activePromise)).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/nothing")).wait()) XCTAssertTrue(didActivate) XCTAssertNoThrow(try self.channel.finish()) } func testCreatedChildChannelCanBeClosedImmediately() throws { var closed = false let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertFalse(closed) multiplexer.createStreamChannel(promise: nil) { channel in channel.close().whenComplete { _ in closed = true } return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() XCTAssertTrue(closed) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { var closed = false let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { channel in return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) child.closeFuture.whenComplete { _ in closed = true } XCTAssertFalse(closed) child.close(promise: nil) self.channel.embeddedEventLoop.run() XCTAssertTrue(closed) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } func testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive() throws { var closed = false // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertFalse(closed) multiplexer.createStreamChannel(promise: nil) { channel in channel.close().whenComplete { _ in closed = true } return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() XCTAssertTrue(closed) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } func testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive() throws { var closed = false // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { channel in return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let child = try assertNoThrowWithValue(channelPromise.futureResult.wait()) child.closeFuture.whenComplete { _ in closed = true } XCTAssertFalse(closed) child.close(promise: nil) self.channel.embeddedEventLoop.run() XCTAssertTrue(closed) XCTAssertNoThrow(XCTAssertTrue(try self.channel.finish().isClean)) } func testMultiplexerCoalescesFlushCallsDuringChannelRead() throws { // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Add a flush counter. let flushCounter = FlushCounter() XCTAssertNoThrow(try self.channel.pipeline.addHandler(flushCounter).wait()) // Add a server-mode multiplexer that will add an auto-response handler. let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in channel.pipeline.addHandler(QuickFramePayloadResponseHandler()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We're going to send in 10 request frames. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) XCTAssertEqual(flushCounter.flushCount, 0) let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } for frame in framesToSend { self.channel.pipeline.fireChannelRead(NIOAny(frame)) } self.channel.embeddedEventLoop.run() // Response frames should have been written, but no flushes, so they aren't visible. XCTAssertEqual(try self.channel.sentFrames().count, 0) XCTAssertEqual(flushCounter.flushCount, 0) // Now send channel read complete. The frames should be flushed through. self.channel.pipeline.fireChannelReadComplete() XCTAssertEqual(try self.channel.sentFrames().count, 10) XCTAssertEqual(flushCounter.flushCount, 1) } func testMultiplexerDoesntFireReadCompleteForEachFrame() { // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) let frameRecorder = InboundFramePayloadRecorder() let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { childChannel in return childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) // Wake up and activate the stream. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let requestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: requestHeaders, endStream: false))) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(1) self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 1) XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) // Now we're going to send 9 data frames. var requestData = self.channel.allocator.buffer(capacity: 1024) requestData.writeBytes("Hello world!".utf8) let dataFrames = repeatElement(HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))), count: 9) for frame in dataFrames { self.channel.pipeline.fireChannelRead(NIOAny(frame)) } // We should have 1 read (the HEADERS), and one read complete. XCTAssertEqual(frameRecorder.receivedFrames.count, 1) XCTAssertEqual(readCompleteCounter.readCompleteCount, 1) // Fire read complete on the parent and it'll propagate to the child. This will trigger the reads. self.channel.pipeline.fireChannelReadComplete() // We should have 10 reads, and two read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 10) XCTAssertEqual(readCompleteCounter.readCompleteCount, 2) // If we fire a new read complete on the parent, the child doesn't see it this time, as it received no frames. self.channel.pipeline.fireChannelReadComplete() XCTAssertEqual(frameRecorder.receivedFrames.count, 10) XCTAssertEqual(readCompleteCounter.readCompleteCount, 2) } func testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete() { // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // These are deliberately getting inserted to all streams. The test above confirms the single-stream // behaviour is correct. let frameRecorder = InboundFramePayloadRecorder() let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { childChannel in return childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertEqual(frameRecorder.receivedFrames.count, 0) XCTAssertEqual(readCompleteCounter.readCompleteCount, 0) // Wake up and activate the streams. let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) for streamID in [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)] { let requestFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: false))) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(streamID) } self.channel.embeddedEventLoop.run() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) // Firing in readComplete does not cause a second readComplete for each stream, as no frames were delivered. self.channel.pipeline.fireChannelReadComplete() XCTAssertEqual(frameRecorder.receivedFrames.count, 3) XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) // Now we're going to send a data frame on stream 1. var requestData = self.channel.allocator.buffer(capacity: 1024) requestData.writeBytes("Hello world!".utf8) let frame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))) self.channel.pipeline.fireChannelRead(NIOAny(frame)) // We should have 3 reads, and 3 read completes. The frame is not delivered as we have no frame fast-path. XCTAssertEqual(frameRecorder.receivedFrames.count, 3) XCTAssertEqual(readCompleteCounter.readCompleteCount, 3) // Fire read complete on the parent and it'll propagate to the child, but only to the one // that saw a frame. self.channel.pipeline.fireChannelReadComplete() // We should have 4 reads, and 4 read completes. XCTAssertEqual(frameRecorder.receivedFrames.count, 4) XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) // If we fire a new read complete on the parent, the children don't see it. self.channel.pipeline.fireChannelReadComplete() XCTAssertEqual(frameRecorder.receivedFrames.count, 4) XCTAssertEqual(readCompleteCounter.readCompleteCount, 4) } func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens() throws { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, outboundBufferSizeLowWatermark: 50) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in return childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let childChannel = try assertNoThrowWithValue(childChannelPromise.futureResult.wait()) XCTAssertTrue(childChannel.isWritable) // We're going to write a HEADERS frame (9 bytes) and an 81 byte DATA frame (90 bytes). This will not flip the // writability state. let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let headersFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 81) dataBuffer.writeBytes(repeatElement(0, count: 81)) let dataFrame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(dataBuffer), endStream: false)) childChannel.write(headersFrame, promise: nil) childChannel.write(dataFrame, promise: nil) XCTAssertTrue(childChannel.isWritable) // Now we're going to send another HEADERS frame (for trailers). This should flip the channel writability. let trailers = HPACKHeaders([]) let trailersFrame = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true)) childChannel.write(trailersFrame, promise: nil) XCTAssertFalse(childChannel.isWritable) // Now we flush the writes. This flips the writability again. childChannel.flush() XCTAssertTrue(childChannel.isWritable) } func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Now we want to create a few new child streams. let promises = (0..<5).map { _ in self.channel.eventLoop.makePromise(of: Channel.self) } for promise in promises { multiplexer.createStreamChannel(promise: promise) { childChannel in return childChannel.eventLoop.makeSucceededFuture(()) } } self.channel.embeddedEventLoop.run() let channels = try assertNoThrowWithValue(promises.map { promise in try promise.futureResult.wait() }) // These are all writable. XCTAssertEqual(channels.map { $0.isWritable }, [true, true, true, true, true]) // We need to write (and flush) some data so that the streams get stream IDs. for childChannel in channels { XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).wait()) } // Mark the parent channel not writable. This currently changes nothing. self.channel.isWritable = false self.channel.pipeline.fireChannelWritabilityChanged() XCTAssertEqual(channels.map { $0.isWritable }, [true, true, true, true, true]) // Now activate each channel. As we do, we'll see its writability state change. for childChannel in channels { let streamID = try assertNoThrowWithValue(childChannel.getOption(HTTP2StreamChannelOptions.streamID).wait()) self.activateStream(streamID) XCTAssertFalse(childChannel.isWritable, "Channel \(streamID) is incorrectly writable") } // All are now non-writable. XCTAssertEqual(channels.map { $0.isWritable }, [false, false, false, false, false]) // And back again. self.channel.isWritable = true self.channel.pipeline.fireChannelWritabilityChanged() XCTAssertEqual(channels.map { $0.isWritable }, [true, true, true, true, true]) } func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability() throws { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, outboundBufferSizeLowWatermark: 50) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in return childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let childChannel = try assertNoThrowWithValue(childChannelPromise.futureResult.wait()) // We need to write (and flush) some data so that the streams get stream IDs. XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).wait()) self.activateStream(1) XCTAssertTrue(childChannel.isWritable) // We're going to write a HEADERS frame (9 bytes) and an 81 byte DATA frame (90 bytes). This will not flip the // writability state. let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 81) dataBuffer.writeBytes(repeatElement(0, count: 81)) let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(dataBuffer), endStream: false)) childChannel.write(headersPayload, promise: nil) childChannel.write(dataPayload, promise: nil) XCTAssertTrue(childChannel.isWritable) // Now we're going to send another HEADERS frame (for trailers). This should flip the channel writability. let trailers = HPACKHeaders([]) let trailersPayload = HTTP2Frame.FramePayload.headers(.init(headers: trailers, endStream: true)) childChannel.write(trailersPayload, promise: nil) XCTAssertFalse(childChannel.isWritable) // Now mark the channel not writable. self.channel.isWritable = false self.channel.pipeline.fireChannelWritabilityChanged() // Now we flush the writes. The channel remains not writable. childChannel.flush() XCTAssertFalse(childChannel.isWritable) // Now we mark the parent channel writable. This flips the writability state. self.channel.isWritable = true self.channel.pipeline.fireChannelWritabilityChanged() XCTAssertTrue(childChannel.isWritable) } func testStreamChannelToleratesFailingInitializer() { struct DummyError: Error {} let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, outboundBufferSizeHighWatermark: 100, outboundBufferSizeLowWatermark: 50) { _ in XCTFail("Must not be called") return self.channel.eventLoop.makeFailedFuture(MyError()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5)).wait()) // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in childChannel.close().flatMap { childChannel.eventLoop.makeFailedFuture(DummyError()) } } self.channel.embeddedEventLoop.run() } func testInboundChannelWindowSizeIsCustomisable() throws { let targetWindowSize = 1 << 18 let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, targetWindowSize: targetWindowSize) { channel in return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5)).wait()) // Ok, create an inbound channel. let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) // Now claim that the window got consumed. Nothing happens. XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) var windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2) + 1, outboundWindowSize: nil) channel.pipeline.fireUserInboundEventTriggered(windowEvent) XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) // Consume the last byte. windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2), outboundWindowSize: nil) channel.pipeline.fireUserInboundEventTriggered(windowEvent) guard let receivedFrame = try assertNoThrowWithValue(self.channel.readOutbound(as: HTTP2Frame.self)) else { XCTFail("No frame received") return } receivedFrame.assertWindowUpdateFrame(streamID: 1, windowIncrement: targetWindowSize / 2) XCTAssertNoThrow(try channel.finish(acceptAlreadyClosed: false)) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testWeCanCreateFrameAndPayloadBasedStreamsOnAMultiplexer() throws { let frameRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameRecorder).wait()) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, inboundStreamInitializer: nil) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Create a payload based stream. let streamAPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamAPromise) { channel in return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) // We haven't written on the stream yet: it shouldn't have a stream ID. XCTAssertThrowsError(try streamA.getOption(HTTP2StreamChannelOptions.streamID).wait()) { error in XCTAssert(error is NIOHTTP2Errors.NoStreamIDAvailable) } // Create a frame based stream. let streamBPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamBPromise) { channel, streamID in // stream A doesn't have an ID yet. XCTAssertEqual(streamID, HTTP2StreamID(1)) return channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) // Do some writes on A and B. let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) // (We checked the streamID above.) XCTAssertNoThrow(try streamB.writeAndFlush(HTTP2Frame(streamID: 1, payload: headersPayload)).wait()) // Write on stream A. XCTAssertNoThrow(try streamA.writeAndFlush(headersPayload).wait()) // Stream A must have an ID now. XCTAssertEqual(try streamA.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(3)) frameRecorder.flushedWrites.assertFramesMatch([HTTP2Frame(streamID: 1, payload: headersPayload), HTTP2Frame(streamID: 3, payload: headersPayload)]) } func testReadWhenUsingAutoreadOnChildChannel() throws { var childChannel: Channel? = nil let readCounter = ReadCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture<Void> in childChannel = channel // We're going to _enable_ autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: true).flatMap { channel.pipeline.addHandler(readCounter) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) XCTAssertNotNil(childChannel) // There should be two calls to read: the first, when the stream was activated, the second after the HEADERS // frame was delivered. XCTAssertEqual(readCounter.readCount, 2) // Now deliver a data frame. var buffer = self.channel.allocator.buffer(capacity: 12) buffer.writeStaticString("Hello, world!") let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(buffer)))) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered, _and_ a call to read should have happened. XCTAssertEqual(readCounter.readCount, 3) // Delivering two more frames causes two more calls to read. XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) XCTAssertEqual(readCounter.readCount, 5) XCTAssertNoThrow(try self.channel.finish()) } func testWindowUpdateIsNotEmittedAfterStreamIsClosed() throws { let targetWindowSize = 1024 let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, targetWindowSize: targetWindowSize) { channel in return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Write a headers frame. let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) self.channel.pipeline.fireChannelRead(NIOAny(headersFrame)) // Activate the stream. self.activateStream(1) // Send a window updated event. let windowUpdated = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: 128, outboundWindowSize: nil) self.channel.pipeline.fireUserInboundEventTriggered(windowUpdated) self.channel.pipeline.fireChannelReadComplete() // We expect the a WINDOW_UPDATE frame: our inbound window size is 128 but has a target of 1024. let frame = try assertNoThrowWithValue(try self.channel.readOutbound(as: HTTP2Frame.self))! frame.assertWindowUpdateFrame(streamID: 1, windowIncrement: 896) // The inbound window size should now be our target: 1024. Write enough bytes to consume the // inbound window. let data = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init(repeating: 0, count: targetWindowSize + 1)))) let dataFrame = HTTP2Frame(streamID: 1, payload: data) self.channel.pipeline.fireChannelRead(NIOAny(dataFrame)) self.channel.pipeline.fireUserInboundEventTriggered(StreamClosedEvent(streamID: 1, reason: nil)) self.channel.pipeline.fireChannelReadComplete() // We've consumed the inbound window: normally we'd expect a WINDOW_UPDATE frame but since // the stream has closed we don't expect to read anything out. XCTAssertNil(try self.channel.readOutbound(as: HTTP2Frame.self)) } func testWindowUpdateIsNotEmittedAfterStreamIsClosedEvenOnLaterFrame() throws { let targetWindowSize = 128 let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel, targetWindowSize: targetWindowSize) { channel in return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Write a headers frame. let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) self.channel.pipeline.fireChannelRead(NIOAny(headersFrame)) // Activate the stream. self.activateStream(1) // Send a window updated event. var windowUpdated = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: 128, outboundWindowSize: nil) self.channel.pipeline.fireUserInboundEventTriggered(windowUpdated) self.channel.pipeline.fireChannelReadComplete() // The inbound window size should now be our target: 128. Write enough bytes to consume the // inbound window as two frames: a 127-byte frame, followed by a 1-byte with END_STREAM set. let bytes = ByteBuffer(repeating: 0, count: targetWindowSize) let firstData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: targetWindowSize - 1)!))) let secondData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: 1)!), endStream: true)) let firstDataFrame = HTTP2Frame(streamID: 1, payload: firstData) let secondDataFrame = HTTP2Frame(streamID: 1, payload: secondData) self.channel.pipeline.fireChannelRead(NIOAny(firstDataFrame)) windowUpdated = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: 1, outboundWindowSize: nil) self.channel.pipeline.fireUserInboundEventTriggered(windowUpdated) self.channel.pipeline.fireChannelRead(NIOAny(secondDataFrame)) // This is nil here for a reason: it reflects what would actually be sent in the real code. Relevantly, the nil currently // does not actually propagate into the handler, which matters a lot. windowUpdated = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: nil, outboundWindowSize: nil) self.channel.pipeline.fireUserInboundEventTriggered(windowUpdated) self.channel.pipeline.fireChannelReadComplete() // We've consumed the inbound window: normally we'd expect a WINDOW_UPDATE frame but since // the stream has closed we don't expect to read anything out. XCTAssertNil(try self.channel.readOutbound(as: HTTP2Frame.self)) } func testStreamChannelSupportsSyncOptions() throws { let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTAssert(channel is HTTP2StreamChannel) if let sync = channel.syncOptions { do { let streamID = try sync.getOption(HTTP2StreamChannelOptions.streamID) XCTAssertEqual(streamID, HTTP2StreamID(1)) let autoRead = try sync.getOption(ChannelOptions.autoRead) try sync.setOption(ChannelOptions.autoRead, value: !autoRead) XCTAssertNotEqual(autoRead, try sync.getOption(ChannelOptions.autoRead)) } catch { XCTFail("Missing StreamID") } } else { XCTFail("syncOptions was nil but should be supported for HTTP2StreamChannel") } return channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } func testStreamErrorIsDeliveredToChannel() throws { let goodHeaders = HPACKHeaders([ (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost") ]) var badHeaders = goodHeaders badHeaders.add(name: "transfer-encoding", value: "chunked") let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Now create two child channels with error recording handlers in them. Save one, ignore the other. let errorRecorder = ErrorRecorder() var childChannel: Channel! multiplexer.createStreamChannel(promise: nil) { channel in childChannel = channel return channel.pipeline.addHandler(errorRecorder) } let secondErrorRecorder = ErrorRecorder() multiplexer.createStreamChannel(promise: nil) { channel in // For this one we'll do a write immediately, to bring it into existence and give it a stream ID. channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: goodHeaders)), promise: nil) return channel.pipeline.addHandler(secondErrorRecorder) } self.channel.embeddedEventLoop.run() // On this child channel, write and flush an invalid headers frame. XCTAssertEqual(errorRecorder.errors.count, 0) XCTAssertEqual(secondErrorRecorder.errors.count, 0) childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: badHeaders)), promise: nil) // Now, synthetically deliver the stream error that should have been produced. self.channel.pipeline.fireErrorCaught( NIOHTTP2Errors.streamError( streamID: 3, baseError: NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") ) ) // It should come through to the channel. XCTAssertEqual( errorRecorder.errors.first.flatMap { $0 as? NIOHTTP2Errors.ForbiddenHeaderField }, NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked") ) XCTAssertEqual(secondErrorRecorder.errors.count, 0) // Simulate closing the child channel in response to the error. childChannel.close(promise: nil) self.channel.embeddedEventLoop.run() // Only the HEADERS frames should have been written: we closed before the other channel became active, so // it should not have triggered an RST_STREAM frame. let frames = try self.channel.sentFrames() XCTAssertEqual(frames.count, 2) frames[0].assertHeadersFrame(endStream: false, streamID: 1, headers: goodHeaders, priority: nil, type: .request) frames[1].assertHeadersFrame(endStream: false, streamID: 3, headers: badHeaders, priority: nil, type: .doNotValidate) } func testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive() throws { let goodHeaders = HPACKHeaders([ (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost") ]) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Server push is unexpected") return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Now create two child channels with error recording handlers in them. Save one, ignore the other. let consumer = ReadAndFrameConsumer() var childChannel: Channel! multiplexer.createStreamChannel(promise: nil) { channel in childChannel = channel return channel.pipeline.addHandler(consumer) } self.channel.embeddedEventLoop.run() let streamID = HTTP2StreamID(1) let payload = HTTP2Frame.FramePayload.Headers(headers: goodHeaders, endStream: true) XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(payload)).wait()) let frames = try self.channel.sentFrames() XCTAssertEqual(frames.count, 1) frames.first?.assertHeadersFrameMatches(this: HTTP2Frame(streamID: streamID, payload: .headers(payload))) XCTAssertEqual(consumer.readCount, 1) // 1. pass header onwards let responseHeaderPayload = HTTP2Frame.FramePayload.headers(.init(headers: [":status": "200"])) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseHeaderPayload))) XCTAssertEqual(consumer.receivedFrames.count, 1) XCTAssertEqual(consumer.readCompleteCount, 1) XCTAssertEqual(consumer.readCount, 2) consumer.forwardRead = false // 2. pass body onwards let responseBody1 = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init(string: "foo")))) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseBody1))) XCTAssertEqual(consumer.receivedFrames.count, 2) XCTAssertEqual(consumer.readCompleteCount, 2) XCTAssertEqual(consumer.readCount, 3) XCTAssertEqual(consumer.readPending, true) // 3. pass on more body - should not change a thing, since read is pending in consumer let responseBody2 = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init(string: "bar")), endStream: true)) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseBody2))) XCTAssertEqual(consumer.receivedFrames.count, 2) XCTAssertEqual(consumer.readCompleteCount, 2) XCTAssertEqual(consumer.readCount, 3) XCTAssertEqual(consumer.readPending, true) // 4. signal stream is closed – this should force forward all pending frames XCTAssertEqual(consumer.channelInactiveCount, 0) self.channel.pipeline.fireUserInboundEventTriggered(StreamClosedEvent(streamID: streamID, reason: nil)) XCTAssertEqual(consumer.receivedFrames.count, 3) XCTAssertEqual(consumer.readCompleteCount, 3) XCTAssertEqual(consumer.readCount, 3) XCTAssertEqual(consumer.channelInactiveCount, 1) XCTAssertEqual(consumer.readPending, true) } } private final class ErrorRecorder: ChannelInboundHandler { typealias InboundIn = Any var errors: [Error] = [] func errorCaught(context: ChannelHandlerContext, error: Error) { self.errors.append(error) context.fireErrorCaught(error) } } private final class ReadAndFrameConsumer: ChannelInboundHandler, ChannelOutboundHandler { typealias InboundIn = HTTP2Frame.FramePayload typealias OutboundIn = HTTP2Frame.FramePayload private(set) var receivedFrames: [HTTP2Frame.FramePayload] = [] private(set) var readCount = 0 private(set) var readCompleteCount = 0 private(set) var channelInactiveCount = 0 private(set) var readPending = false var forwardRead = true { didSet { if self.forwardRead, self.readPending { self.context.read() self.readPending = false } } } var context: ChannelHandlerContext! func handlerAdded(context: ChannelHandlerContext) { self.context = context } func handlerRemoved(context: ChannelHandlerContext) { self.context = context } func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.receivedFrames.append(self.unwrapInboundIn(data)) context.fireChannelRead(data) } func channelReadComplete(context: ChannelHandlerContext) { self.readCompleteCount += 1 context.fireChannelReadComplete() } func channelInactive(context: ChannelHandlerContext) { self.channelInactiveCount += 1 context.fireChannelInactive() } func read(context: ChannelHandlerContext) { self.readCount += 1 if forwardRead { context.read() self.readPending = false } else { self.readPending = true } } }
apache-2.0
30ff0d2fb1bb7e48ed17b599dfa0d1a9
46.603561
178
0.681127
5.193558
false
true
false
false
tjw/swift
test/SILGen/writeback.swift
2
5798
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s struct Foo { mutating // used to test writeback. func foo() {} subscript(x: Int) -> Foo { get { return Foo() } set {} } } var x: Foo { get { return Foo() } set {} } var y: Foo { get { return Foo() } set {} } var z: Foo { get { return Foo() } set {} } var readonly: Foo { get { return Foo() } } func bar(x x: inout Foo) {} // Writeback to value type 'self' argument x.foo() // CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo // CHECK: [[GET_X:%.*]] = function_ref @$S9writeback1xAA3FooVvg : $@convention(thin) () -> Foo // CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: store [[X]] to [trivial] [[X_TEMP]] // CHECK: [[FOO:%.*]] = function_ref @$S9writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> () // CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> () // CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo // CHECK: [[SET_X:%.*]] = function_ref @$S9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> () // CHECK: dealloc_stack [[X_TEMP]] : $*Foo // Writeback to inout argument bar(x: &x) // CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo // CHECK: [[GET_X:%.*]] = function_ref @$S9writeback1xAA3FooVvg : $@convention(thin) () -> Foo // CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo // CHECK: [[BAR:%.*]] = function_ref @$S9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> () // CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> () // CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo // CHECK: [[SET_X:%.*]] = function_ref @$S9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> () // CHECK: dealloc_stack [[X_TEMP]] : $*Foo func zang(x x: Foo) {} // No writeback for pass-by-value argument zang(x: x) // CHECK: function_ref @$S9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> () // CHECK-NOT: @$S9writeback1xAA3FooVvs zang(x: readonly) // CHECK: function_ref @$S9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> () // CHECK-NOT: @$S9writeback8readonlyAA3FooVvs func zung() -> Int { return 0 } // Ensure that subscripts are only evaluated once. bar(x: &x[zung()]) // CHECK: [[ZUNG:%.*]] = function_ref @$S9writeback4zungSiyF : $@convention(thin) () -> Int // CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int // CHECK: [[GET_X:%.*]] = function_ref @$S9writeback1xAA3FooVvg : $@convention(thin) () -> Foo // CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @$S9writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo // CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo // CHECK: [[BAR:%.*]] = function_ref @$S9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> () // CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> () // CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @$S9writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> () // CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> () // CHECK: function_ref @$S9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> () protocol Fungible {} extension Foo : Fungible {} var addressOnly: Fungible { get { return Foo() } set {} } func funge(x x: inout Fungible) {} funge(x: &addressOnly) // CHECK: [[TEMP:%.*]] = alloc_stack $Fungible // CHECK: [[GET:%.*]] = function_ref @$S9writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out Fungible // CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible // CHECK: [[FUNGE:%.*]] = function_ref @$S9writeback5funge1xyAA8Fungible_pz_tF : $@convention(thin) (@inout Fungible) -> () // CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> () // CHECK: [[SET:%.*]] = function_ref @$S9writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in Fungible) -> () // CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> () // CHECK: dealloc_stack [[TEMP]] : $*Fungible // Test that writeback occurs with generic properties. // <rdar://problem/16525257> protocol Runcible { associatedtype Frob: Frobable var frob: Frob { get set } } protocol Frobable { associatedtype Anse var anse: Anse { get set } } // CHECK-LABEL: sil hidden @$S9writeback12test_generic{{[_0-9a-zA-Z]*}}F // CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1 // CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1 func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) { runce.frob.anse = anse } // We should *not* write back when referencing decls or members as rvalues. // <rdar://problem/16530235> // CHECK-LABEL: sil hidden @$S9writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out Fungible { func loadAddressOnly() -> Fungible { // CHECK: function_ref writeback.addressOnly.getter // CHECK-NOT: function_ref writeback.addressOnly.setter return addressOnly } // CHECK-LABEL: sil hidden @$S9writeback10loadMember{{[_0-9a-zA-Z]*}}F // CHECK: witness_method $Runce, #Runcible.frob!getter.1 // CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1 // CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1 // CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1 func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse { return runce.frob.anse }
apache-2.0
a689c1a3952fb836e2d1af2e44e18ce0
36.166667
136
0.614867
3.182217
false
false
false
false
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/model/system/SystemInfo.swift
1
2896
// // SystemInfo.swift // Emby.ApiClient // import Foundation public class SystemInfo: PublicSystemInfo { let operatingSystemDisplayName: String let isRunningAsService: Bool let supportsRunningAsService: Bool let macAddress: String let hasPendingRestart: Bool let supportsSync: Bool let isNetworkDeployed: Bool let inProgressInstallations: [InstallationInfo] let webSocketPortNumber: Int let completedInstallations: [InstallationInfo] let canSelfRestart: Bool let canSelfUpdate: Bool let failedPluginAssemblies: [String] let programDataPath: String let itemsByNamePath: String let cachePath: String let logPath: String let transcodingTempPath: String let httpServerPortNumber: Int let supportsHttps: Bool let hasUpdatesAvailable: Bool let supportsAutoRunAtStartup: Bool init(localAddress: String?, wanAddress: String?, serverName: String, version: String, operatingSystem: String, id: String, operatingSystemDisplayName: String, isRunningAsService: Bool, supportsRunningAsService: Bool, macAddress: String, hasPendingRestart: Bool, supportsSync: Bool, isNetworkDeployed: Bool,inProgressInstallations: [InstallationInfo], webSocketPortNumber: Int, completedInstallations: [InstallationInfo], canSelfRestart: Bool, canSelfUpdate: Bool, failedPluginAssemblies: [String], programDataPath: String, itemsByNamePath: String, cachePath: String, logPath: String, transcodingTempPath: String, httpServerPortNumber: Int, supportsHttps: Bool, hasUpdatesAvailable: Bool, supportsAutoRunAtStartup: Bool) { self.operatingSystemDisplayName = operatingSystemDisplayName self.isRunningAsService = isRunningAsService self.supportsRunningAsService = supportsRunningAsService self.macAddress = macAddress self.hasPendingRestart = hasPendingRestart self.supportsSync = supportsSync self.isNetworkDeployed = isNetworkDeployed self.inProgressInstallations = inProgressInstallations self.webSocketPortNumber = webSocketPortNumber self.completedInstallations = completedInstallations self.canSelfRestart = canSelfRestart self.canSelfUpdate = canSelfUpdate self.failedPluginAssemblies = failedPluginAssemblies self.programDataPath = programDataPath self.itemsByNamePath = itemsByNamePath self.cachePath = cachePath self.logPath = logPath self.transcodingTempPath = transcodingTempPath self.httpServerPortNumber = httpServerPortNumber self.supportsHttps = supportsHttps self.hasUpdatesAvailable = hasUpdatesAvailable self.supportsAutoRunAtStartup = supportsAutoRunAtStartup super.init(localAddress: localAddress, wanAddress: wanAddress, serverName: serverName, version: version, operatingSystem: operatingSystem, id: id) } }
mit
b9384e6afdb6b82bd08c793daabc7042
47.283333
725
0.765193
5.284672
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Charts/PieRadarChartViewBase.swift
5
31021
// // PieRadarChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base class of PieChartView and RadarChartView. public class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not public var rotationEnabled = true /// Sets the minimum offset (padding) around the chart, defaults to 0.0 public var minOffset = CGFloat(0.0) /// iOS && OSX only: Enabled multi-touch rotation using two fingers. private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) private var _rotationGestureRecognizer: NSUIRotationGestureRecognizer! #endif public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(PieRadarChartViewBase.tapGestureRecognized(_:))) self.addGestureRecognizer(_tapGestureRecognizer) #if !os(tvOS) _rotationGestureRecognizer = NSUIRotationGestureRecognizer(target: self, action: #selector(PieRadarChartViewBase.rotationGestureRecognized(_:))) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.enabled = rotationWithTwoFingers #endif } internal override func calcMinMax() { _xAxis.axisRange = Double((_data?.xVals.count ?? 0) - 1) } public override func notifyDataSetChanged() { calcMinMax() if let data = _data where _legend !== nil { _legendRenderer.computeLegend(data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if (_legend != nil && _legend.enabled) { var fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) fullLegendWidth += _legend.formSize + _legend.formToTextSpace if (_legend.position == .RightOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendRight = fullLegendWidth + spacing } else if (_legend.position == .RightOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomRight.x, y: bottomRight.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendRight = minOffset + diff } if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendRight = legendWidth } } else if (_legend.position == .LeftOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendLeft = fullLegendWidth + spacing } else if (_legend.position == .LeftOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let min = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendLeft = min + diff } if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendLeft = legendWidth } } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendBottom = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset legendTop = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = self.minOffset if (self.isKindOfClass(RadarChartView)) { let x = (self as! RadarChartView).xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(minOffset, x.labelRotatedWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: the angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... public func angleForPoint(x x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r * ChartUtils.Math.RAD2DEG if (x > c.x) { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if (angle > 360.0) { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. internal func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD), y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD)) } /// - returns: the distance of a certain point on the chart to the center of the chart. public func distanceToCenter(x x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if (x > c.x) { xDist = x - c.x } else { xDist = c.x - x } if (y > c.y) { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: the xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. public func indexForAngle(angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: will always return a normalized value, which will be between 0.0 < 360.0 public var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue) setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. public var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: the diameter of the pie- or radar-chart public var diameter: CGFloat { let content = _viewPortHandler.contentRect return min(content.width, content.height) } /// - returns: the radius of the chart in pixels. public var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: the required offset for the chart legend. internal var requiredLegendOffset: CGFloat { fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase") } /// - returns: the base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } public override var chartYMax: Double { return 0.0 } public override var chartYMin: Double { return 0.0 } /// The SelectionDetail objects give information about the value at the selected index and the DataSet it belongs to. /// - returns: an array of SelectionDetail objects for the given x-index. public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail] { var vals = [ChartSelectionDetail]() guard let data = _data else { return vals } for i in 0 ..< data.dataSetCount { guard let dataSet = data.getDataSetByIndex(i) else { continue } if !dataSet.isHighlightEnabled { continue } // extract all y-values from all DataSets at the given x-index let yVal = dataSet.yValForXIndex(xIndex) if (yVal.isNaN) { continue } vals.append(ChartSelectionDetail(value: yVal, dataSetIndex: i, dataSet: dataSet)) } return vals } public var isRotationEnabled: Bool { return rotationEnabled; } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false public var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue #if !os(tvOS) _rotationGestureRecognizer.enabled = _rotationWithTwoFingers #endif } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false public var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: ChartAnimator! /// Applys a spin animation to the Chart. public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if (_spinAnimator != nil) { _spinAnimator.stop() } _spinAnimator = ChartAnimator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil; } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } public func stopSpinAnimation() { if (_spinAnimator != nil) { _spinAnimator.stop() } } // MARK: - Gestures private var _rotationGestureStartPoint: CGPoint! private var _isRotating = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: NSTimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 internal final func processRotationGestureBegan(location location: CGPoint) { self.resetVelocity() if rotationEnabled { self.sampleVelocity(touchLocation: location) } self.setGestureStartAngle(x: location.x, y: location.y) _rotationGestureStartPoint = location } internal final func processRotationGestureMoved(location location: CGPoint) { if isDragDecelerationEnabled { sampleVelocity(touchLocation: location) } if !_isRotating && distance( eventX: location.x, startX: _rotationGestureStartPoint.x, eventY: location.y, startY: _rotationGestureStartPoint.y) > CGFloat(8.0) { _isRotating = true } else { self.updateGestureRotation(x: location.x, y: location.y) setNeedsDisplay() } } internal final func processRotationGestureEnded(location location: CGPoint) { if isDragDecelerationEnabled { stopDeceleration() sampleVelocity(touchLocation: location) _decelerationAngularVelocity = calculateVelocity() if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } internal final func processRotationGestureCancelled() { if (_isRotating) { _isRotating = false } } #if !os(OSX) public override func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { // if rotation by touch is enabled if (rotationEnabled) { stopDeceleration() if (!rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureBegan(location: touchLocation) } } if (!_isRotating) { super.nsuiTouchesBegan(touches, withEvent: event) } } public override func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureMoved(location: touchLocation) } if (!_isRotating) { super.nsuiTouchesMoved(touches, withEvent: event) } } public override func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if (!_isRotating) { super.nsuiTouchesEnded(touches, withEvent: event) } if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as NSUITouch! let touchLocation = touch.locationInView(self) processRotationGestureEnded(location: touchLocation) } if (_isRotating) { _isRotating = false } } public override func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.nsuiTouchesCancelled(touches, withEvent: event) processRotationGestureCancelled() } #endif #if os(OSX) public override func mouseDown(theEvent: NSEvent) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureBegan(location: location) } if !_isRotating { super.mouseDown(theEvent) } } public override func mouseDragged(theEvent: NSEvent) { if rotationEnabled { let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureMoved(location: location) } if !_isRotating { super.mouseDragged(theEvent) } } public override func mouseUp(theEvent: NSEvent) { if !_isRotating { super.mouseUp(theEvent) } if rotationEnabled { let location = self.convertPoint(theEvent.locationInWindow, fromView: nil) processRotationGestureEnded(location: location) } if _isRotating { _isRotating = false } } #endif private func resetVelocity() { _velocitySamples.removeAll(keepCapacity: false) } private func sampleVelocity(touchLocation touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds var i = 0, count = _velocitySamples.count while (i < count - 2) { if (currentTime - _velocitySamples[i].time > 1.0) { _velocitySamples.removeAtIndex(0) i -= 1 count -= 1 } else { break } i += 1 } } private func calculateVelocity() -> CGFloat { if (_velocitySamples.isEmpty) { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for i in (_velocitySamples.count - 1).stride(through: 0, by: -1) { beforeLastSample = _velocitySamples[i] if (beforeLastSample.angle != lastSample.angle) { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if (timeDelta == 0.0) { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if (lastSample.angle - firstSample.angle > 180.0) { firstSample.angle += 360.0 } else if (firstSample.angle - lastSample.angle > 180.0) { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if (!clockwise) { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: the distance between two points private func distance(eventX eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: the distance between two points private func distance(from from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: ChartHighlight! @objc private func tapGestureRecognized(recognizer: NSUITapGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } let location = recognizer.locationInView(self) let distance = distanceToCenter(x: location.x, y: location.y) // check if a slice was touched if (distance > self.radius) { // if no slice was touched, highlight nothing self.highlightValues(nil) if _lastHighlight == nil { self.highlightValues(nil) // do not call delegate } else { self.highlightValue(highlight: nil, callDelegate: true) // call delegate } _lastHighlight = nil } else { var angle = angleForPoint(x: location.x, y: location.y) if (self.isKindOfClass(PieChartView)) { angle /= _animator.phaseY } let index = indexForAngle(angle) // check if the index could be found if (index < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let valsAtIndex = getSelectionDetailsAtIndex(index) var dataSetIndex = 0 // get the dataset that is closest to the selection (PieChart only has one DataSet) if (self.isKindOfClass(RadarChartView)) { dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Double(distance / (self as! RadarChartView).factor), axis: nil) } if (dataSetIndex < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex) if (_lastHighlight !== nil && h == _lastHighlight) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { self.highlightValue(highlight: h, callDelegate: true) _lastHighlight = h } } } } } } #if !os(tvOS) @objc private func rotationGestureRecognized(recognizer: NSUIRotationGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Began) { stopDeceleration() _startAngle = self.rawRotationAngle } if (recognizer.state == NSUIGestureRecognizerState.Began || recognizer.state == NSUIGestureRecognizerState.Changed) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if (recognizer.state == NSUIGestureRecognizerState.Ended) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.nsuiRotation self.rotationAngle = _startAngle + angle setNeedsDisplay() if (isDragDecelerationEnabled) { stopDeceleration() _decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } } #endif }
apache-2.0
4b29eb2be47baa993324edc09967d3fd
31.479581
191
0.560273
5.555615
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/Styles/Plain/Cells/VoiceMessage/VoiceMessagePlainCell.swift
1
2417
// // Copyright 2021 New Vector Ltd // // 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 class VoiceMessagePlainCell: SizableBaseRoomCell, RoomCellReactionsDisplayable, RoomCellReadMarkerDisplayable, RoomCellThreadSummaryDisplayable { private(set) var playbackController: VoiceMessagePlaybackController! override func render(_ cellData: MXKCellData!) { super.render(cellData) guard let data = cellData as? RoomBubbleCellData else { return } guard data.attachment.type == .voiceMessage || data.attachment.type == .audio else { fatalError("Invalid attachment type passed to a voice message cell.") } if playbackController.attachment != data.attachment { playbackController.attachment = data.attachment } self.update(theme: ThemeService.shared().theme) } override func setupViews() { super.setupViews() roomCellContentView?.backgroundColor = .clear roomCellContentView?.showSenderInfo = true roomCellContentView?.showPaginationTitle = false guard let contentView = roomCellContentView?.innerContentView else { return } playbackController = VoiceMessagePlaybackController(mediaServiceProvider: VoiceMessageMediaServiceProvider.sharedProvider, cacheManager: VoiceMessageAttachmentCacheManager.sharedManager) contentView.vc_addSubViewMatchingParent(playbackController.playbackView) } override func update(theme: Theme) { super.update(theme: theme) guard let playbackController = playbackController else { return } playbackController.playbackView.update(theme: theme) } }
apache-2.0
e1d731130e43399e1a319b02966e3300
34.544118
145
0.665701
5.581986
false
false
false
false
uasys/swift
test/Interpreter/struct_resilience.swift
1
5200
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-module -parse-as-library -Xfrontend -enable-resilience %S/../Inputs/resilient_struct.swift -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct -emit-library -o %t/libresilient_struct.%target-dylib-extension // RUN: %target-build-swift %s -lresilient_struct -I %t -L %t -o %t/main -Xlinker -rpath -Xlinker %t // RUN: %target-codesign %t/libresilient_struct.%target-dylib-extension // RUN: %target-run %t/main // RUN: %target-build-swift -emit-module -parse-as-library -Xfrontend -enable-resilience %S/../Inputs/resilient_struct.swift -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct -emit-library -o %t/libresilient_struct.%target-dylib-extension -whole-module-optimization // RUN: %target-build-swift %s -lresilient_struct -I %t -L %t -o %t/main -Xlinker -rpath -Xlinker %t // RUN: %target-codesign %t/libresilient_struct.%target-dylib-extension // RUN: %target-run %t/main // REQUIRES: executable_test import StdlibUnittest import resilient_struct var ResilientStructTestSuite = TestSuite("ResilientStruct") ResilientStructTestSuite.test("ResilientValue") { for b in [false, true] { let r = ResilientBool(b: b) expectEqual(b, r.b) } for i in [-12, -1, 12] { let r = ResilientInt(i: i) expectEqual(i, r.i) } for d in [-1.0, 0.0, -0.0, 1.0] { let r = ResilientDouble(d: d) expectEqual(d, r.d) } } ResilientStructTestSuite.test("StaticLayout") { for b1 in [false, true] { for i in [-12, -1, 12] { for b2 in [false, true] { for d in [-1.0, 0.0, -0.0, 1.0] { let r = ResilientLayoutRuntimeTest(b1: ResilientBool(b: b1), i: ResilientInt(i: i), b2: ResilientBool(b: b2), d: ResilientDouble(d: d)) expectEqual(b1, r.b1.b) expectEqual(i, r.i.i) expectEqual(b2, r.b2.b) expectEqual(d, r.d.d) } } } } } // Make sure structs with dynamic layout are instantiated correctly, // and can conform to protocols. protocol MyResilientLayoutProtocol { var b1: ResilientBool { get } } struct MyResilientLayoutRuntimeTest : MyResilientLayoutProtocol { let b1: ResilientBool let i: ResilientInt let b2: ResilientBool let d: ResilientDouble init(b1: ResilientBool, i: ResilientInt, b2: ResilientBool, d: ResilientDouble) { self.b1 = b1 self.i = i self.b2 = b2 self.d = d } } @inline(never) func getMetadata() -> Any.Type { return MyResilientLayoutRuntimeTest.self } ResilientStructTestSuite.test("DynamicLayoutMetatype") { do { var output = "" let expected = "- main.MyResilientLayoutRuntimeTest #0\n" dump(getMetadata(), to: &output) expectEqual(output, expected) } do { expectEqual(true, getMetadata() == getMetadata()) } } ResilientStructTestSuite.test("DynamicLayout") { for b1 in [false, true] { for i in [-12, -1, 12] { for b2 in [false, true] { for d in [-1.0, 0.0, -0.0, 1.0] { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: b1), i: ResilientInt(i: i), b2: ResilientBool(b: b2), d: ResilientDouble(d: d)) expectEqual(b1, r.b1.b) expectEqual(i, r.i.i) expectEqual(b2, r.b2.b) expectEqual(d, r.d.d) } } } } } @inline(never) func getB(_ p: MyResilientLayoutProtocol) -> Bool { return p.b1.b } ResilientStructTestSuite.test("DynamicLayoutConformance") { do { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: true), i: ResilientInt(i: 0), b2: ResilientBool(b: false), d: ResilientDouble(d: 0.0)) expectEqual(getB(r), true) } } protocol ProtocolWithAssociatedType { associatedtype T: MyResilientLayoutProtocol func getT() -> T } struct StructWithDependentAssociatedType : ProtocolWithAssociatedType { let r: MyResilientLayoutRuntimeTest init(r: MyResilientLayoutRuntimeTest) { self.r = r } func getT() -> MyResilientLayoutRuntimeTest { return r } } @inline(never) func getAssociatedType<T : ProtocolWithAssociatedType>(_ p: T) -> MyResilientLayoutProtocol.Type { return T.T.self } ResilientStructTestSuite.test("DynamicLayoutAssociatedType") { do { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: true), i: ResilientInt(i: 0), b2: ResilientBool(b: false), d: ResilientDouble(d: 0.0)) let metatype: MyResilientLayoutProtocol.Type = MyResilientLayoutRuntimeTest.self let associated: MyResilientLayoutProtocol.Type = getAssociatedType(StructWithDependentAssociatedType(r: r)); expectEqual(true, metatype == associated) expectEqual(getB(r), true) } } runAllTests()
apache-2.0
f81e8ae36d9140b4b72cccdfea387837
30.90184
295
0.611154
3.906837
false
true
false
false
markspanbroek/Shhwift
Shhwift/Filter.swift
1
247
public struct Filter { public let id: Id public init(id: Id) { self.id = id } public typealias Id = UInt } extension Filter: Equatable {} public func == (lhs: Filter, rhs: Filter) -> Bool { return lhs.id == rhs.id }
mit
2996ef3a4033bcc8a883305694fa7b69
16.642857
51
0.591093
3.528571
false
false
false
false
alobanov/Dribbble
Dribbble/models/ponso/feed/FeedCellModel.swift
1
703
// // ShotCellModel.swift // Dribbble // // Created by Lobanov Aleksey on 29.01.17. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation struct FeedCellModel: ModelItemDatasourseble, PonsoUnicIdentifirable { var uid: Int = 1 var commnets = "" var views = "" var likes = "" var imagePath = "" var unic: String? init(shot: ShotModel) { commnets = " \(shot.comments)" likes = " \(shot.likes)" uid = shot.shotId views = " \(shot.views)" if !shot.animated { imagePath = shot.image!.hidpi ?? shot.image!.normal! } else { imagePath = shot.image!.teaser ?? "" } unic = "\(shot.str_updated_at!)\(uid)" } }
mit
5c267afff14f8175b7c12aa99ccd38c9
20.272727
70
0.602564
3.42439
false
false
false
false
hyperoslo/Catalog
Demos/CampaignReady/CampaignReady/ContentGenerator.swift
1
2921
import Wall import Catalog import Faker struct ContentGenerator { let faker = Faker() func listing() -> Listing { let title = faker.commerce.productName() let publishDate = NSDate() let startDate = NSDate() let endDate = NSDate() let status = Listing.Status.Open let listing = Listing( title: title, publishDate: publishDate, startDate: startDate, endDate: endDate, status: status) var index = 1 let contentSectionCount = 2 let productSectionCount = 1 var contentSections = [ContentSection]() var productSections = [CardSection]() for _ in 0..<contentSectionCount { contentSections.append(contentSection(index)) index++ } for _ in 0..<productSectionCount { productSections.append(productSection(&index)) index++ } listing.contentSections = contentSections listing.cardSections = productSections return listing } func contentSection(index: Int) -> ContentSection { let title = faker.commerce.productName() let publishDate = NSDate() let attachments = images(index) let section = ContentSection( date: publishDate, attachments: attachments) section.title = title if index % 2 == 0 { section.read = true } return section } func productSection(inout index: Int) -> CardSection { let title = faker.commerce.productName() let publishDate = NSDate() let attachments = images(index) let section = CardSection( date: publishDate, attachments: attachments) section.title = title let count = 5 var productCards = [Card]() for _ in 0..<count { productCards.append(productCard(&index)) index++ } section.cards = productCards return section } func productCard(inout index: Int) -> Card { let count = 4 var relatedProducts = [Item]() for _ in 0..<count { relatedProducts.append(product(index)) index++ } let productCard = Card( item: product(index), relatedItems: relatedProducts) return productCard } func product(index: Int) -> Item { let title = faker.commerce.productName() let attachments = images(index) let serialNumber = faker.commerce.productName() let text = faker.lorem.sentences(amount: 4) let price = 899.0 let oldPrice = 1005.2 let discount = "10%" let product = Item( title: title, serialNumber: serialNumber, attachments: attachments, price: price, oldPrice: oldPrice, discount: discount) return product } func images(index: Int) -> [Attachment] { var images = [Attachment]() var count = 1 if index % 2 == 0 { count = 4 } for x in 0..<count { images.append( Image("http://lorempixel.com/%d/%d/?type=attachment&id=\(index)\(x)")) } return images } }
mit
042275245eaaaa7e02ef2b5fd1a57aaf
20.014388
78
0.627867
4.353204
false
false
false
false
mdpianelli/ios-shopfinder
ShopFinder/ShopFinder/ShopDetailController.swift
1
14742
// // ShopDetailController.swift // ShopFinder // // Created by Marcos Pianelli on 15/07/15. // Copyright (c) 2015 Barkala Studios. All rights reserved. // import UIKit import SVProgressHUD import FontAwesomeKit import SDWebImage import MapKit import Spring import GoogleMobileAds class ShopDetailController: BaseController, MKMapViewDelegate, GADBannerViewDelegate, UITableViewDelegate, UITableViewDataSource { var shop : NSDictionary? var shopInfo : [TableSection]? var shopAnnotation : ShopAnnotation? @IBOutlet weak var imageView: SpringImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var table: UITableView! @IBOutlet weak var header: ParallaxHeaderView! var descriptionExpanded = false var adBanner: GADBannerView? let descriptionFieldHeight = 120 //MARK: UIViewController Methods @IBAction func dismiss(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() initialSetup() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationItem.title = NSLocalizedString("Shop", comment: "shop") scrollViewDidScroll(table) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) adBanner?.delegate = nil } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() header.refreshBlurViewForNewImage() } //MARK: Initial Setup Methods func initialSetup(){ adBannerSetup() shopInfoSetup() } func shopInfoSetup(){ //set title titleLabel.text = shop!.objectForKey("name") as? String ratingLabel.text = shop!.objectForKey("rating") as? String //initialize table sections and rows shopInfo = [TableSection(sectionName:"",rows:[])] if let address = shop!.objectForKey("address") as? String { shopInfo![0].rows?.append(TableRow(title:address ,icon:Icon(type:0,index:215,color:UIColor(hex: "#0091FF")),action:Action(type:.Location,data:nil),height:60,type:.Standard)) } if let phoneNumber = shop!.objectForKey("phone_number") as? String { shopInfo![0].rows?.append(TableRow(title:phoneNumber ,icon:Icon(type:0,index:372,color:UIColor(hex: "#0091FF")),action:Action(type:.Call,data:phoneNumber),height:60,type:.Standard)) } if let website = shop!.objectForKey("website") as? String { shopInfo![0].rows?.append(TableRow(title:website,icon:Icon(type:2,index:221,color:UIColor(hex: "#0091FF")),action:Action(type:.Link,data:website),height:60,type:.Standard)) } if let description = shop!.objectForKey("description") as? String { shopInfo![0].rows?.append(TableRow(title:description,icon:nil,action:Action(type:.Expand,data:description),height:descriptionFieldHeight,type:.Text)) } if let openingHours = shop!.objectForKey("opening_hours") as? NSDictionary { let weekdayArray = openingHours.objectForKey("weekday_text") as! NSArray shopInfo?.append( TableSection(sectionName:"Opening Hours",rows:[ TableRow(title:weekdayArray[0] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[1] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[2] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[3] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[4] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[5] as! String,icon:nil,action:nil,height:40,type:.Standard), TableRow(title:weekdayArray[6] as! String,icon:nil,action:nil,height:40,type:.Standard), ]) ) } header.frame.size.height = 170 if let photos = shop!.objectForKey("photos") as? [String] { let imageURL = photos[0] let key = SDWebImageManager.sharedManager().cacheKeyForURL(NSURL(string: imageURL)) let img = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key) header.headerImage = img } table.tableHeaderView = header if let loc: AnyObject = shop!.objectForKey("geolocation"){ if let geoloc : AnyObject = loc.objectForKey("location"){ let lat = geoloc.objectForKey("lat") as! Double let long = geoloc.objectForKey("lng") as! Double let annotation = ShopAnnotation(title: titleLabel.text, subtitle:shop!.objectForKey("address") as! String, lat: lat, lon: long, row: 0) mapView.addAnnotation(annotation) mapView.showAnnotations(mapView.annotations, animated: true) shopAnnotation = annotation } } table.reloadData() } func adBannerSetup(){ adBanner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) adBanner?.adSize = kGADAdSizeSmartBannerPortrait adBanner?.adUnitID = Ads.bannerId adBanner?.rootViewController = self adBanner?.autoloadEnabled = true; adBanner?.delegate = self adBanner?.loadRequest(GADRequest()) } //MARK: - GADBannerViewDelegate func adViewDidReceiveAd(view: GADBannerView!) { var frame = adBanner!.frame frame.origin.y = self.view.frame.size.height - frame.size.height adBanner?.frame = frame self.view.addSubview(adBanner!) //FadeIn banner adBanner?.alpha = 0 SpringAnimation.spring(1,animations: { self.adBanner?.alpha = 1 }) table.contentInset = UIEdgeInsetsMake(0,0,50,0) } func adView(view: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!){ //println(error) } //MARK: UITableView Methods func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let row = shopInfo![indexPath.section].rows![indexPath.row] as TableRow return CGFloat(row.height) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return shopInfo![section].sectionName } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return shopInfo!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shopInfo![section].rows!.count } // for table parallax effect func scrollViewDidScroll(scrollView: UIScrollView) { let header: ParallaxHeaderView = table.tableHeaderView as! ParallaxHeaderView header.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset) // table.tableHeaderView = header } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let data = shopInfo![indexPath.section].rows![indexPath.row] as TableRow switch(data.type){ case .Standard : let cell = tableView.dequeueReusableCellWithIdentifier("Standard") as! ShopDetailCell cell.infoLabel!.text = data.title // if data.icon != nil { cell.iconButton!.icon = data.icon // } //print("\(cell.iconButton!.frame)") // cell.contentView.addSubview(cell.iconButton!) // print("\(data.icon?.type) + \(data.icon?.index) + \(data.icon?.color)", terminator: "") if data.action == nil { cell.selectionStyle = .None cell.separatorInset = UIEdgeInsetsMake(0,table.frame.size.width,0,0); }else{ cell.selectionStyle = .Default cell.separatorInset = UIEdgeInsetsMake(0,0, 0, 0) } return cell case .Text : let cell = tableView.dequeueReusableCellWithIdentifier("Text") as! ShopDetailDescriptionCell cell.descriptionLabel!.text = data.title cell.selectionStyle = .None return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = shopInfo![indexPath.section].rows![indexPath.row] as TableRow if row.action == nil { return } switch(row.action!.type){ case .Expand : expandAction(row.title,indexPath: indexPath) case .Location: locationAction(row) case .Call: callAction(row) case .Link: openLinkAction(row) case .DLink: openDlinkAction(row) default : break; } } //MARK: Actions func expandAction( text: String, indexPath : NSIndexPath){ //mofidy row height var height = 0 if descriptionExpanded { height = descriptionFieldHeight }else{ height = calculateHeightForString(text) } table.beginUpdates() shopInfo![indexPath.section].rows![indexPath.row].height = height table.endUpdates() descriptionExpanded = !descriptionExpanded } func calculateHeightForString(inString:String) -> Int { let messageString = inString let attributes = [NSFontAttributeName : UIFont.systemFontOfSize(17.0)] let attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes) let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(table.frame.width,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )//hear u will get nearer height not the exact value let requredSize:CGRect = rect return Int(requredSize.height+80) //to include button's in your tableview } func locationAction(row : TableRow?){ let address = "\(shopAnnotation!.coordinate.latitude),\(shopAnnotation!.coordinate.longitude)" let actionController = UIAlertController(title:NSLocalizedString("Show Directions:", comment: ""), message: nil, preferredStyle: .ActionSheet) //Create and add the Cancel action let cancelAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action -> Void in //Just dismiss the action sheet // self.dismissViewControllerAnimated(true, completion: nil) } // if UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!){ let googleAction = UIAlertAction(title: NSLocalizedString("Open in Google Maps", comment: ""), style: .Default) { (action) -> Void in let url = NSURL(string: "comgooglemaps://?daddr=\(address)&directionsmode=transit") UIApplication.sharedApplication().openURL(url!) } actionController.addAction(googleAction) // } let mapsAction = UIAlertAction(title: NSLocalizedString("Open in Maps", comment: ""), style: .Default) { (action) -> Void in let url = NSURL(string: "http://maps.apple.com/?daddr=\(address)&dirflg=r") UIApplication.sharedApplication().openURL(url!) } actionController.addAction(mapsAction) actionController.addAction(cancelAction) self.presentViewController(actionController, animated: true, completion: nil) } //MARK: Map View Delegate func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) as UIView } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { locationAction(nil) } } class ShopDetailDescriptionCell : UITableViewCell { @IBOutlet weak var descriptionLabel: UILabel! } class ShopDetailCell : UITableViewCell { @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var iconButton: FADesignableIconButton! } class ShopAnnotation : NSObject, MKAnnotation { // Center latitude and longitude of the annotation view. // The implementation of this property must be KVO compliant. var coordinate : CLLocationCoordinate2D; // Title and subtitle for use by selection UI. var title: String? var subtitle: String? var row: Int! init(title:String!,subtitle:String!,lat:CLLocationDegrees!,lon:CLLocationDegrees!,row:Int!) { self.title = title self.subtitle = subtitle self.coordinate = CLLocationCoordinate2DMake(lat, lon) self.row = row super.init() } }
mit
8d4395e21242f2f30c18f749251e6483
29.648649
222
0.588658
5.419853
false
false
false
false
kumabook/FeedlyKit
Source/Origin.swift
1
831
// // Origin.swift // FeedlyKit // // Created by Hiroki Kumamoto on 1/18/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import SwiftyJSON open class Origin: ParameterEncodable { open var streamId: String! open var title: String! open var htmlUrl: String! public init(streamId: String, title: String, htmlUrl: String) { self.streamId = streamId self.title = title self.htmlUrl = htmlUrl } public init?(json: JSON) { if json == JSON.null { return nil } self.streamId = json["streamId"].stringValue self.title = json["title"].stringValue self.htmlUrl = json["htmlUrl"].stringValue } open func toParameters() -> [String : Any] { return ["title": title, "htmlUrl": htmlUrl] } }
mit
245d57dc1a537f6d8c1a534a74eb1ea9
24.96875
67
0.620939
4.033981
false
false
false
false
Alloc-Studio/Hypnos
Hypnos/Hypnos/Controller/MusicHall/MusicHallViewController.swift
1
2499
// // MusicHallViewController.swift // Hypnos // // Created by Fay on 16/5/23. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SVProgressHUD class MusicHallViewController: UIViewController { var songs:[HotSongsModel] = [] override func viewDidLoad() { super.viewDidLoad() SVProgressHUD.showWithStatus("正在玩命加载中...") DataTool.getHotSongList { (obj) in self.songs = obj as![HotSongsModel] self.tableView.reloadData() self.tableView.frame.size.height = self.tableView.contentSize.height SVProgressHUD.dismiss() self.view.addSubview(self.tableView) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = view.bounds } private lazy var tableView:UITableView = { let tv: UITableView = UITableView(frame:self.view.bounds) tv.tableFooterView = UIView() tv.delegate = self tv.dataSource = self MusicListCell.registerCell(tv) return tv }() private lazy var musicPlayerVc:MusicPlayerController = { let vc:MusicPlayerController = MusicPlayerController() return vc }() } extension MusicHallViewController:UITableViewDataSource,UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(id_MusicListCell) as! MusicListCell cell.number.text = "\(indexPath.row + 1) " cell.musicList = songs[indexPath.row] return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 56.0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { Player.sharedPlayer().view.frame = view.bounds Player.sharedPlayer().musicModel = songs[indexPath.row] Player.sharedPlayer().musics = songs navigationController?.pushViewController(Player.sharedPlayer(), animated: true) } }
mit
b56ccb34543c71e31000ae70f7eb50f2
27.860465
109
0.656326
5.117526
false
false
false
false
ustwo/formvalidator-swift
Tests/Unit Tests/Conditions/RangeConditionTests.swift
1
1986
// // RangeConditionTests.swift // FormValidatorSwift // // Created by Aaron McTavish on 13/01/2016. // Copyright © 2016 ustwo. All rights reserved. // import XCTest @testable import FormValidatorSwift final class RangeConditionTests: XCTestCase { // MARK: - Properties let condition = RangeCondition(configuration: ConfigurationSeeds.RangeSeeds.threeToThirteen) // MARK: - Test Initializers func testRangeCondition_DefaultInit() { // Given let condition = RangeCondition() let expectedRange = 0..<1 // When let actualRange = condition.configuration.range // Test XCTAssertEqual(actualRange, expectedRange, "Expected range to be: \(expectedRange) but found: \(actualRange)") } // MARK: - Test Success func testRangeCondition_Success() { // Given let testInput = "1A2B3D4C5D" let expectedResult = true // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } // MARK: - Test Failure func testRangeCondition_Start_Failure() { // Given let testInput = "1A" let expectedResult = false // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } func testRangeCondition_Length_Failure() { // Given let testInput = "1A2B3D4C5D6E" let expectedResult = false // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } func testRangeCondition_Nil_Failure() { // Given let testInput: String? = nil let expectedResult = false // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } }
mit
8f4ac696baee9591b784df0af48d8b34
23.8125
102
0.589421
5.115979
false
true
false
false
groue/GRMustache.swift
Tests/Public/ServicesTests/FormatterTests.swift
2
12804
// 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 XCTest import Mustache class FormatterTests: XCTestCase { func testFormatterIsAFilterForProcessableValues() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") // test that number is processable XCTAssertEqual(percentFormatter.string(from: 0.5)!, "50%") // test filtering a number let template = try! Template(string: "{{ percent(number) }}") let value: [String: Any] = ["number": 0.5, "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "50%") } func testFormatterIsAFilterForUnprocessableValues() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") // test that number is processable XCTAssertTrue(percentFormatter.string(for: "foo") == nil) // test filtering a string let template = try! Template(string: "{{ percent(string) }}") let value: [String: Any] = ["string": "foo", "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "") } func testFormatterSectionFormatsInnerVariableTags() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let template = try! Template(string: "{{# percent }}{{ number }} {{ number }}{{/ percent }}") let value: [String: Any] = ["number": 0.5, "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "50% 50%") } func testFormatterSectionDoesNotFormatUnprocessableInnerVariableTags() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let template = try! Template(string: "{{# percent }}{{ value }}{{/ percent }}") let value: [String: Any] = ["value": "foo", "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "foo") } func testFormatterAsSectionFormatsDeepInnerVariableTags() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let template = try! Template(string: "{{# percent }}{{# number }}Number is {{ number }}.{{/ number }}{{/ percent }}") let value: [String: Any] = ["number": 0.5, "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "Number is 50%.") } func testFormatterAsSectionDoesNotFormatInnerSectionTags() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let template = try! Template(string: "NO is {{ NO }}. {{^ NO }}NO is false.{{/ NO }} percent(NO) is {{ percent(NO) }}. {{# percent(NO) }}percent(NO) is true.{{/ percent(NO) }} {{# percent }}{{^ NO }}NO is now {{ NO }} and is still false.{{/ NO }}{{/ percent }}") let value: [String: Any] = ["number": 0.5, "NO": 0, "percent": percentFormatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "NO is 0. NO is false. percent(NO) is 0%. percent(NO) is true. NO is now 0% and is still false.") } func testFormatterIsTruthy() { let formatter = Formatter() let template = try! Template(string: "{{# formatter }}Formatter is true.{{/ formatter }}{{^ formatter }}Formatter is false.{{/ formatter }}") let value = ["formatter": formatter] let rendering = try! template.render(value) XCTAssertEqual(rendering, "Formatter is true.") } func testFormatterRendersSelfAsSomething() { let formatter = Formatter() let template = try! Template(string: "{{ formatter }}") let value = ["formatter": formatter] let rendering = try! template.render(value) XCTAssertTrue(rendering.count > 0) } func testNumberFormatterRendersNothingForMissingValue() { // Check that NSNumberFormatter does not have surprising behavior, and // does not format nil. let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let value = ["format": percentFormatter] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSNull() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let value: [String: Any] = ["format": percentFormatter, "value": NSNull()] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSString() { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") var value: [String: Any] = ["format": percentFormatter, "value": "1"] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") value = ["format": percentFormatter, "value": "YES"] template = try! Template(string: "<{{format(value)}}>") rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") value = ["format": percentFormatter, "value": "foo"] template = try! Template(string: "<{{format(value)}}>") rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testNumberFormatterRendersNothingForNSDate() { // Check that NSNumberFormatter does not have surprising behavior, and // does not format NSDate. let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent percentFormatter.locale = Locale(identifier: "en_US_POSIX") let value: [String: Any] = ["format": percentFormatter, "value": Date()] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForMissingValue() { // Check that NSDateFormatter does not have surprising behavior, and // does not format nil. let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full let value = ["format": dateFormatter] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSNull() { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full let value: [String: Any] = ["format": dateFormatter, "value": NSNull()] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSString() { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full var value: [String: Any] = ["format": dateFormatter, "value": "1"] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") value = ["format": dateFormatter, "value": "YES"] template = try! Template(string: "<{{format(value)}}>") rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") value = ["format": dateFormatter, "value": "foo"] template = try! Template(string: "<{{format(value)}}>") rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } func testDateFormatterRendersNothingForNSNumber() { // Check that NSDateFormatter does not have surprising behavior, and // does not format NSNumber. let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full let value: [String: Any] = ["format": dateFormatter, "value": 0] var template = try! Template(string: "<{{format(value)}}>") var rendering = try! template.render(value) XCTAssertEqual(rendering, "<>") template = try! Template(string: "{{#format(value)}}YES{{/}}{{^format(value)}}NO{{/}}") rendering = try! template.render(value) XCTAssertEqual(rendering, "NO") } }
mit
ef073e3c98c62eb38b275bf42add732a
42.547619
270
0.616262
4.981712
false
true
false
false
BirdBrainTechnologies/Hummingbird-iOS-Support
BirdBlox/BirdBlox/SettingsRequests.swift
1
1246
// // SettingsRequests.swift // BirdBlox // // Created by birdbrain on 4/27/17. // Copyright © 2017 Birdbrain Technologies LLC. All rights reserved. // import Foundation //import Swifter class SettingsManager: NSObject { func loadRequests(server: BBTBackendServer){ //settings/getSetting?key=foo server["/settings/get"] = self.getSettingRequest //settings/setSetting?key=foo&value=bar server["/settings/set"] = self.setSettingRequest } func getSettingRequest(request: HttpRequest) -> HttpResponse { let queries = BBTSequentialQueryArrayToDict(request.queryParams) if let key = (queries["key"]) { let value = DataModel.shared.getSetting(key) if let nullCheckedValue = value { return .ok(.text(nullCheckedValue)) } else { return .notFound } } return .badRequest(.text("Malformed request")) } func setSettingRequest(request: HttpRequest) -> HttpResponse { let captured = BBTSequentialQueryArrayToDict(request.queryParams) if let key = (captured["key"]), let value = (captured["value"]) { DataModel.shared.addSetting(key, value: value) return .ok(.text("Setting saved")) } return .badRequest(.text("Malformed request")) } }
mit
b8d3c06f08b403e354ebc4e8ee5f165f
24.9375
69
0.684337
3.75
false
false
false
false
telldus/telldus-live-mobile-v3
ios/Constants/Constants.swift
1
668
// // Constants.swift // TelldusLiveApp // // Created by Rimnesh Fernandez on 19/10/20. // Copyright © 2020 Telldus Technologies AB. All rights reserved. // import Foundation struct Constants { static var telldusAPIServer: String = Constants.variable(named: "TELLDUS_API_SERVER") ?? CI.telldusAPIServer static let supportedMethods = 4023 static let DEEP_LINK_PURCHASE_PREMIUM = "widget-deeplink://purchase-premium" // NOTE: IMP: Do not change static func variable(named name: String) -> String? { let processInfo = ProcessInfo.processInfo guard let value = processInfo.environment[name] else { return nil } return value } }
gpl-3.0
5e9729e15012895c12fd8ddd07c7973e
28
110
0.713643
3.833333
false
false
false
false
lanstonpeng/Focord2
Focord2/TransitionManager.swift
1
3720
// // TransitionManager.swift // CustomTransition // // Created by Lanston Peng on 7/22/14. // Copyright (c) 2014 Vtm. All rights reserved. // import UIKit class TransitionManager:NSObject, UIViewControllerAnimatedTransitioning { var isPresent:Bool = true init(isPresent:Bool) { self.isPresent = isPresent super.init() } func animateTransition(transitionContext: UIViewControllerContextTransitioning!) { if isPresent { self.animationForPresentTransition(transitionContext) } else { self.animationForDismissTransition(transitionContext) } } func printPaperControllerView(containerView:UIView) { for view in containerView.subviews { println(view.tag) } } func animationForDismissTransition(transitionContext:UIViewControllerContextTransitioning!) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toViewContrller = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let containerView = transitionContext.containerView() let duration = self.transitionDuration(transitionContext) let screenBounds = UIScreen.mainScreen().bounds let finalFrame = transitionContext.finalFrameForViewController(toViewContrller) toViewContrller.view.frame = CGRectOffset(finalFrame,-screenBounds.size.width,0) self.printPaperControllerView(containerView) containerView.insertSubview(toViewContrller.view, aboveSubview: fromViewController.view) self.printPaperControllerView(containerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {()->Void in toViewContrller.view.frame = finalFrame fromViewController.view.frame = CGRectOffset(fromViewController.view.frame, 160, 0); }, completion: {(completed:Bool) -> Void in transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } func animationForPresentTransition(transitionContext:UIViewControllerContextTransitioning!) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toViewContrller = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let containerView = transitionContext.containerView() let duration = self.transitionDuration(transitionContext) let screenBounds = UIScreen.mainScreen().bounds let finalFrame = transitionContext.finalFrameForViewController(toViewContrller) toViewContrller.view.frame = CGRectOffset(finalFrame,screenBounds.size.width,0) containerView.addSubview(toViewContrller.view) self.printPaperControllerView(containerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {()->Void in toViewContrller.view.frame = finalFrame fromViewController.view.frame = CGRectOffset(fromViewController.view.frame, -160, 0); }, completion: {(completed:Bool) -> Void in transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } func transitionDuration(transitionContext: UIViewControllerContextTransitioning!) -> NSTimeInterval { return 0.5; } }
mit
ee103033af857dd3dc8edf81a4035a7c
38.157895
126
0.692473
6.348123
false
false
false
false
kpiteira/MobileAzureDevDays
Swift/MobileAzureDevDays/MobileAzureDevDays/SentimentResponse.swift
2
1827
// // SentimentDoc.swift // MobileAzureDevDays // // Created by Colby Williams on 9/23/17. // Copyright © 2017 Colby Williams. All rights reserved. // import Foundation class SentimentResponse { let errorsKey = "errors" let documentsKey = "documents" let errorMessageKey = "message" let errorStatusCodeKey = "statusCode" var errors = [SentimentError]() var documents = [SentimentDocument]() var errorMessage:String? var errorStatusCode:Int? var hasErrors: Bool { return !errors.isEmpty } var hasDocuments: Bool { return !documents.isEmpty } init(fromJson dict: [String:Any]) { if let errorsDict = dict[errorsKey] as? [[String:Any]] { for errorDict in errorsDict { if let error = SentimentError(fromJson: errorDict) { self.errors.append(error) } } } if let documentsDict = dict[documentsKey] as? [[String:Any]] { for documentDict in documentsDict { if let document = SentimentDocument(fromJson: documentDict) { self.documents.append(document) } } } if let errorMessage = dict[errorMessageKey] as? String, let errorStatusCode = dict[errorStatusCodeKey] as? Int { self.errorMessage = errorMessage self.errorStatusCode = errorStatusCode } } } class SentimentError { let idKey = "id" let messageKey = "message" var id:String! var message:String! init?(fromJson dict: [String:Any]) { if let id = dict[idKey] as? String, let message = dict[messageKey] as? String { self.id = id self.message = message } else { return nil } } } class SentimentDocument { let idKey = "id" let scoreKey = "score" var id:String! var score:Double! init?(fromJson dict: [String:Any]) { if let id = dict[idKey] as? String, let score = dict[scoreKey] as? Double { self.id = id self.score = score } else { return nil } } }
mit
bb938c8b1d511661e9c6f2f2ba630103
21.268293
114
0.682913
3.29009
false
false
false
false
russbishop/swift
benchmark/single-source/BitCount.swift
1
1197
//===--- BitCount.swift ---------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This test checks performance of Swift bit count. // and mask operator. // rdar://problem/22151678 import Foundation import TestsUtils func countBitSet(_ num: Int) -> Int { let bits = sizeof(Int.self) * 8 var cnt: Int = 0 var mask: Int = 1 for _ in 0...bits { if num & mask != 0 { cnt += 1 } mask <<= 1 } return cnt } @inline(never) public func run_BitCount(_ N: Int) { for _ in 1...100*N { // Check some results. CheckResults(countBitSet(1) == 1, "Incorrect results in BitCount.") CheckResults(countBitSet(2) == 1, "Incorrect results in BitCount.") CheckResults(countBitSet(2457) == 6, "Incorrect results in BitCount.") } }
apache-2.0
08bdcf1d22c7fe099c0c4c031a1c2ab4
28.925
80
0.588972
4.170732
false
false
false
false
eburns1148/CareKit
Sample/OCKSampleWatch Extension/ComplicationController.swift
1
8178
/* Copyright (c) 2016, Apple Inc. 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 ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler(CLKComplicationTimeTravelDirections()) } func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { handler(.hideOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping((CLKComplicationTimelineEntry?) -> Void)) { // Call the handler with the current timeline entry let template = getTemplate(forCompletionPercentage: getCurrentCompletionPercentage(), complication: complication) if template != nil { handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template!)) } else { handler(nil) } } func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Placeholder Templates func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(getTemplate(forCompletionPercentage: nil, complication: complication)) } // MARK: Rendering Templates func getTemplate(forCompletionPercentage completionPercentage : Int?, complication : CLKComplication) -> CLKComplicationTemplate? { var textToDisplay : String if completionPercentage == nil || completionPercentage == -1 { // completionPercentage of -1 indicates request for nil to be displayed by InterfaceController textToDisplay = "--%" } else { textToDisplay = "\(completionPercentage!)%" } switch complication.family { case .modularLarge: let template = CLKComplicationTemplateModularLargeStandardBody() template.headerTextProvider = CLKSimpleTextProvider(text: "Care Completion") template.tintColor = InterfaceController.watchTintColor template.body1TextProvider = CLKSimpleTextProvider(text: textToDisplay) if completionPercentage != nil && completionPercentage != -1 { let eventsRemaining = getEventsRemaining() switch eventsRemaining { case 0: template.body2TextProvider = CLKSimpleTextProvider(text: "Care Plan complete") case 1: template.body2TextProvider = CLKSimpleTextProvider(text: "1 event remaining") default: template.body2TextProvider = CLKSimpleTextProvider(text: "\(getEventsRemaining()) events remaining") } } return template case .modularSmall: let template = CLKComplicationTemplateModularSmallStackImage() template.line1ImageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Modular")!) template.line2TextProvider = CLKSimpleTextProvider(text: textToDisplay) template.tintColor = InterfaceController.watchTintColor return template case .utilitarianSmall: let template = CLKComplicationTemplateUtilitarianSmallFlat() template.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Utilitarian")!) template.textProvider = CLKSimpleTextProvider(text: textToDisplay) template.tintColor = InterfaceController.watchTintColor return template case .utilitarianLarge: let template = CLKComplicationTemplateUtilitarianLargeFlat() if completionPercentage == nil && completionPercentage != -1 { template.textProvider = CLKSimpleTextProvider(text: "Care Plan") } else { switch completionPercentage! { case 100: template.textProvider = CLKSimpleTextProvider(text: "Care Complete") default: template.textProvider = CLKSimpleTextProvider(text: "Care Plan: " + textToDisplay) } } template.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Utilitarian")!) template.tintColor = InterfaceController.watchTintColor return template case .circularSmall: let template = CLKComplicationTemplateCircularSmallStackImage() template.line1ImageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Circular")!) template.line2TextProvider = CLKSimpleTextProvider(text: textToDisplay) template.tintColor = InterfaceController.watchTintColor return template case .extraLarge: let template = CLKComplicationTemplateExtraLargeStackImage() template.line1ImageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/X-Large")!) template.line2TextProvider = CLKSimpleTextProvider(text: textToDisplay) template.tintColor = InterfaceController.watchTintColor template.highlightLine2 = false return template default: return nil } } // MARK: Updates func getCurrentCompletionPercentage() -> Int { let defaults = UserDefaults.standard return defaults.integer(forKey: "currentCompletionPercentage") } func getEventsRemaining() -> Int { let defaults = UserDefaults.standard return defaults.integer(forKey: "eventsRemaining") } }
bsd-3-clause
7d0560eb8dee89505772e3b763b3dbd3
46.824561
171
0.685375
6.252294
false
false
false
false
archagon/tasty-imitation-keyboard
Keyboard/ForwardingView.swift
1
7122
// // ForwardingView.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit class ForwardingView: UIView { var touchToView: [UITouch:UIView] = [:] override init(frame: CGRect) { super.init(frame: frame) self.contentMode = UIViewContentMode.redraw self.isMultipleTouchEnabled = true self.isUserInteractionEnabled = true self.isOpaque = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } // Why have this useless drawRect? Well, if we just set the backgroundColor to clearColor, // then some weird optimization happens on UIKit's side where tapping down on a transparent pixel will // not actually recognize the touch. Having a manual drawRect fixes this behavior, even though it doesn't // actually do anything. override func draw(_ rect: CGRect) {} override func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? { if self.isHidden || self.alpha == 0 || !self.isUserInteractionEnabled { return nil } else { return (self.bounds.contains(point) ? self : nil) } } func handleControl(_ view: UIView?, controlEvent: UIControlEvents) { if let control = view as? UIControl { let targets = control.allTargets for target in targets { if let actions = control.actions(forTarget: target, forControlEvent: controlEvent) { for action in actions { let selectorString = action let selector = Selector(selectorString) control.sendAction(selector, to: target, for: nil) } } } } } // TODO: there's a bit of "stickiness" to Apple's implementation func findNearestView(_ position: CGPoint) -> UIView? { if !self.bounds.contains(position) { return nil } var closest: (UIView, CGFloat)? = nil for anyView in self.subviews { let view = anyView if view.isHidden { continue } view.alpha = 1 let distance = distanceBetween(view.frame, point: position) if closest != nil { if distance < closest!.1 { closest = (view, distance) } } else { closest = (view, distance) } } if closest != nil { return closest!.0 } else { return nil } } // http://stackoverflow.com/questions/3552108/finding-closest-object-to-cgpoint b/c I'm lazy func distanceBetween(_ rect: CGRect, point: CGPoint) -> CGFloat { if rect.contains(point) { return 0 } var closest = rect.origin if (rect.origin.x + rect.size.width < point.x) { closest.x += rect.size.width } else if (point.x > rect.origin.x) { closest.x = point.x } if (rect.origin.y + rect.size.height < point.y) { closest.y += rect.size.height } else if (point.y > rect.origin.y) { closest.y = point.y } let a = pow(Double(closest.y - point.y), 2) let b = pow(Double(closest.x - point.x), 2) return CGFloat(sqrt(a + b)); } // reset tracked views without cancelling current touch func resetTrackedViews() { for view in self.touchToView.values { self.handleControl(view, controlEvent: .touchCancel) } self.touchToView.removeAll(keepingCapacity: true) } func ownView(_ newTouch: UITouch, viewToOwn: UIView?) -> Bool { var foundView = false if viewToOwn != nil { for (touch, view) in self.touchToView { if viewToOwn == view { if touch == newTouch { break } else { self.touchToView[touch] = nil foundView = true } break } } } self.touchToView[newTouch] = viewToOwn return foundView } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let position = touch.location(in: self) let view = findNearestView(position) let viewChangedOwnership = self.ownView(touch, viewToOwn: view) if !viewChangedOwnership { self.handleControl(view, controlEvent: .touchDown) if touch.tapCount > 1 { // two events, I think this is the correct behavior but I have not tested with an actual UIControl self.handleControl(view, controlEvent: .touchDownRepeat) } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let position = touch.location(in: self) let oldView = self.touchToView[touch] let newView = findNearestView(position) if oldView != newView { self.handleControl(oldView, controlEvent: .touchDragExit) let viewChangedOwnership = self.ownView(touch, viewToOwn: newView) if !viewChangedOwnership { self.handleControl(newView, controlEvent: .touchDragEnter) } else { self.handleControl(newView, controlEvent: .touchDragInside) } } else { self.handleControl(oldView, controlEvent: .touchDragInside) } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let view = self.touchToView[touch] let touchPosition = touch.location(in: self) if self.bounds.contains(touchPosition) { self.handleControl(view, controlEvent: .touchUpInside) } else { self.handleControl(view, controlEvent: .touchCancel) } self.touchToView[touch] = nil } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let view = self.touchToView[touch] self.handleControl(view, controlEvent: .touchCancel) self.touchToView[touch] = nil } } }
bsd-3-clause
1fe9237e6c030ae4b3b3ea7680887fbc
31.372727
118
0.518113
5.213763
false
false
false
false
mssun/pass-ios
pass/Controllers/SSHKeyFileImportTableViewController.swift
2
2721
// // SSHKeyFileImportTableViewController.swift // pass // // Created by Danny Moesch on 15.02.20. // Copyright © 2020 Bob Sun. All rights reserved. // import passKit import SVProgressHUD class SSHKeyFileImportTableViewController: AutoCellHeightUITableViewController { @IBOutlet var sshPrivateKeyFile: UITableViewCell! private var privateKey: String? @IBAction private func doneButtonTapped(_: Any) { performSegue(withIdentifier: "importSSHKeySegue", sender: self) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) let picker = UIDocumentPickerViewController(documentTypes: ["public.data"], in: .open) cell?.isSelected = false guard cell == sshPrivateKeyFile else { return } picker.delegate = self if #available(iOS 13.0, *) { picker.shouldShowFileExtensions = true } present(picker, animated: true, completion: nil) } } extension SSHKeyFileImportTableViewController: UIDocumentPickerDelegate { func documentPicker(_: UIDocumentPickerViewController, didPickDocumentsAt url: [URL]) { guard let url = url.first else { return } let fileName = url.lastPathComponent do { // Start accessing a security-scoped resource. guard url.startAccessingSecurityScopedResource() else { // Handle the failure here. throw AppError.readingFile(fileName: fileName) } // Make sure you release the security-scoped resource when you are done. defer { url.stopAccessingSecurityScopedResource() } privateKey = try String(contentsOf: url, encoding: .ascii) sshPrivateKeyFile.textLabel?.text = fileName } catch { let message = "FileCannotBeImported.".localize(fileName) | "UnderlyingError".localize(error.localizedDescription) Utils.alert(title: "CannotImportFile".localize(), message: message, controller: self) } } } extension SSHKeyFileImportTableViewController: KeyImporter { static let keySource = KeySource.file static let label = "LoadFromFiles".localize() func isReadyToUse() -> Bool { guard privateKey != nil else { Utils.alert(title: "CannotSave".localize(), message: "SetPrivateKeyUrl.".localize(), controller: self) return false } return true } func importKeys() throws { guard let privateKey = privateKey else { return } try KeyFileManager.PrivateSSH.importKey(from: privateKey) } }
mit
fea59fef69c78d7bb7f0e84733ac8573
33
125
0.654779
5.141777
false
false
false
false
sarvex/SwiftRecepies
Gestures/Detecting Screen Edge Pan Gestures/Detecting Screen Edge Pan Gestures/ViewController.swift
1
2428
// // ViewController.swift // Detecting Screen Edge Pan Gestures // // Created by Vandad Nahavandipoor on 7/8/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import Twitter class ViewController: UIViewController { var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer! /* Just a little method to help us display alert dialogs to the user */ func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(controller, animated: true, completion: nil) } func handleScreenEdgePan(sender: UIScreenEdgePanGestureRecognizer){ if sender.state == .Ended{ displayAlertWithTitle("Detected", message: "Edge swipe was detected") } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) /* Create the Pinch Gesture Recognizer */ screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleScreenEdgePan:") /* Detect pans from left edge to the inside of the view */ screenEdgeRecognizer.edges = .Left } override func viewDidLoad() { super.viewDidLoad() view.addGestureRecognizer(screenEdgeRecognizer) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) displayAlertWithTitle("Instructions", message: "Start swiping from the left edge of the screen " + "to the right, please!") } }
isc
af26a37ff0552c529610b38ab1e701ba
29.734177
83
0.708402
4.513011
false
false
false
false
JOCR10/iOS-Curso
Clases/CleanSwiftExample/CleanSwiftExample/Scenes/ToDoTasksList/ToDoTasksListViewController.swift
1
2881
// // ToDoTasksListViewController.swift // CleanSwiftExample // // Created by Local User on 6/6/17. // Copyright (c) 2017 Local User. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol ToDoTasksListViewControllerInput{ func displayTestInformation(viewModel: ToDoTasksList.TestInformation.ViewModel) func displayDataSource(viewModel: ToDoTasksList.DataSource.ViewModel) } protocol ToDoTasksListViewControllerOutput{ func requestTestInformation(request: ToDoTasksList.TestInformation.Request) func requestDataSource(request: ToDoTasksList.DataSource.Request) } class ToDoTasksListViewController: UIViewController, ToDoTasksListViewControllerInput{ var output: ToDoTasksListViewControllerOutput! var router: ToDoTasksListRouter! @IBOutlet weak var tableView: UITableView! // MARK: Object lifecycle var myStruct : [ToDoTasksList.TaskModelCell] = [] override func awakeFromNib(){ super.awakeFromNib() ToDoTasksListConfigurator.sharedInstance.configure(viewController: self) } // MARK: View lifecycle override func viewDidLoad(){ super.viewDidLoad() requestTestInformation(number: "15") requestDataSource() tableView.registerCustomCell(identifier: ToDoTaskListCustomCell.getTableViewCellIdentifier()) } // MARK: Event handling func requestTestInformation(number: String) { let request = ToDoTasksList.TestInformation.Request(numberText: number) output.requestTestInformation(request: request) } func requestDataSource() { let request = ToDoTasksList.DataSource.Request() output.requestDataSource(request: request) } //display logic func displayTestInformation(viewModel: ToDoTasksList.TestInformation.ViewModel) { print("El resultado es \(viewModel.numberText)") } func displayDataSource(viewModel: ToDoTasksList.DataSource.ViewModel) { myStruct = viewModel.arrayTask } } extension ToDoTasksListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myStruct.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ToDoTaskListCustomCell.getTableViewCellIdentifier()) as! ToDoTaskListCustomCell let item = myStruct[indexPath.row] cell.setUpCell(task: item) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } }
mit
0dbeafe9aa3d52743e32e42316fb01e4
30.315217
144
0.724401
5.508604
false
true
false
false
500LABS/HotBox
HotBoxService/HotBoxService.swift
1
8566
// // HotBoxService.swift // hotbox // // Created by George Lim on 2017-08-08. // Copyright © 2017 George Lim. All rights reserved. // import Foundation import RxSwift enum Events: String { case sessionDidConnect, sessionDidDisconnect, sessionConnectionCreated, sessionConnectionDestroyed, sessionStreamCreated, sessionStreamDidFailWithError, sessionStreamDestroyed, sessionReceivedSignal, publisherStreamCreated, publisherStreamDidFailWithError, publisherStreamDestroyed, subscriberDidConnect, subscriberDidFailWithError, subscriberDidDisconnect, subscriberVideoEnabled, subscriberVideoDisabled } func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) } if next.hashValue != i { return nil } i += 1 return next } } @objc(HotBoxService) class HotBoxService: RCTEventEmitter { var disposeBag = DisposeBag() override func supportedEvents() -> [String]! { return iterateEnum(Events.self).map({ (e) -> String in return e.rawValue }) } @objc func bindSignals() { disposeBag = DisposeBag() HotBoxNativeService.shared.sessionDidConnect.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionDidConnect.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionDidDisconnect.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionDidDisconnect.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionConnectionCreated.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionConnectionCreated.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionConnectionDestroyed.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionConnectionDestroyed.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionStreamCreated.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionStreamCreated.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionStreamDidFailWithError.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in if let signal = signal { self?.sendEvent(withName: Events.sessionStreamDidFailWithError.rawValue, body: signal) print(signal) } }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionStreamDestroyed.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionStreamDestroyed.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.sessionReceivedSignal.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.sessionReceivedSignal.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.publisherStreamCreated.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.publisherStreamCreated.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.publisherStreamDidFailWithError.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in if let signal = signal { self?.sendEvent(withName: Events.publisherStreamDidFailWithError.rawValue, body: signal) print(signal) } }).addDisposableTo(disposeBag) HotBoxNativeService.shared.publisherStreamDestroyed.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.publisherStreamDestroyed.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.subscriberDidConnect.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.subscriberDidConnect.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.subscriberDidFailWithError.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in if let signal = signal { self?.sendEvent(withName: Events.subscriberDidFailWithError.rawValue, body: signal) print(signal) } }).addDisposableTo(disposeBag) HotBoxNativeService.shared.subscriberDidDisconnect.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.subscriberDidDisconnect.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.subscriberVideoEnabled.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.subscriberVideoEnabled.rawValue, body: signal) }).addDisposableTo(disposeBag) HotBoxNativeService.shared.subscriberVideoDisabled.asObservable().skip(1).subscribe(onNext: { [weak self] (signal) in self?.sendEvent(withName: Events.subscriberVideoDisabled.rawValue, body: signal) }).addDisposableTo(disposeBag) } @objc func disconnectAllSessions(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.disconnectAllSessions() { resolve(nil) } else { reject("1", "", nil) } } @objc func createNewSession(_ apiKey: String, sessionId: String, token: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.createNewSession(apiKey: apiKey, sessionId: sessionId, token: token) { resolve(nil) } else { reject("1", "", nil) } } @objc func createPublisher(resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.createPublisher() { resolve(nil) } else { reject("1", "", nil) } } @objc func createSubscriber(streamId: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.createSubscriber(streamId: streamId) { resolve(nil) } else { reject("1", "", nil) } } @objc func modifySubscriberStream(_ streamIds: NSArray, resolution: NSDictionary? = nil, frameRate: NSNumber? = nil, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { var resolutionSize: CGSize? = nil if let resolution = resolution, let width = (resolution["width"] as? NSNumber)?.doubleValue, let height = (resolution["height"] as? NSNumber)?.doubleValue { resolutionSize = CGSize(width: CGFloat(width), height: CGFloat(height)) } if HotBoxNativeService.shared.modifySubscriberStream(streamIds: streamIds as! [String], resolution: resolutionSize, frameRate: frameRate?.floatValue) { resolve(nil) } else { reject("1", "", nil) } } @objc func sendSignal(_ type: String?, string: String?, to connectionId: String?, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.sendSignal(type: type, string: string, to: connectionId) { resolve(nil) } else { reject("1", "", nil) } } @objc func requestVideoStream(_ streamId: String? = nil, on: Bool, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.requestVideoStream(for: streamId, on: on) { resolve(nil) } else { reject("1", "", nil) } } @objc func requestAudioStream(_ streamId: String? = nil, on: Bool, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.requestAudioStream(for: streamId, on: on) { resolve(nil) } else { reject("1", "", nil) } } @objc func requestCameraSwap(_ toBack: Bool, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) { if HotBoxNativeService.shared.requestCameraSwap(toBack: toBack) { resolve(nil) } else { reject("1", "", nil) } } }
mit
b2df1faeb0a2071a197ac0a1033b9bb7
37.236607
407
0.706713
4.713814
false
false
false
false
Donny8028/Swift-Animation
SideMenu/SideMenu/MenuViewController.swift
1
1902
// // MenuViewController.swift // SideMenu // // Created by 賢瑭 何 on 2016/5/22. // Copyright © 2016年 Donny. All rights reserved. // import UIKit class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AnimationManagerDelegate { @IBOutlet weak var tableView: UITableView! let menu = ["Everyday Moments", "Popular", "Editors", "Upcoming", "Fresh", "Stock-photos", "Trending"] var currentItem = "Everyday Moments" override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = menu[indexPath.row] cell.textLabel?.textColor = (menu[indexPath.row] == currentItem) ? UIColor.whiteColor() : UIColor.grayColor() return cell } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowMain" { if segue.sourceViewController is MenuViewController{ let index = tableView.indexPathForSelectedRow currentItem = menu[index!.row] print("1") } } } }
mit
a08bedee9bac7b8f3e29a9d2cb9bff28
30.55
118
0.651347
5.347458
false
false
false
false
DayLogger/ADVOperation
Source/UIUserNotifications+Operations.swift
6
1692
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A convenient extension to UIKit.UIUserNotificationSettings. */ #if os(iOS) import UIKit extension UIUserNotificationSettings { /// Check to see if one Settings object is a superset of another Settings object. func contains(settings: UIUserNotificationSettings) -> Bool { // our types must contain all of the other types if !types.contains(settings.types) { return false } let otherCategories = settings.categories ?? [] let myCategories = categories ?? [] return myCategories.isSupersetOf(otherCategories) } /** Merge two Settings objects together. `UIUserNotificationCategories` with the same identifier are considered equal. */ func settingsByMerging(settings: UIUserNotificationSettings) -> UIUserNotificationSettings { let mergedTypes = types.union(settings.types) let myCategories = categories ?? [] var existingCategoriesByIdentifier = Dictionary(sequence: myCategories) { $0.identifier } let newCategories = settings.categories ?? [] let newCategoriesByIdentifier = Dictionary(sequence: newCategories) { $0.identifier } for (newIdentifier, newCategory) in newCategoriesByIdentifier { existingCategoriesByIdentifier[newIdentifier] = newCategory } let mergedCategories = Set(existingCategoriesByIdentifier.values) return UIUserNotificationSettings(forTypes: mergedTypes, categories: mergedCategories) } } #endif
unlicense
df08185d35655d208a968a1eb37a32fe
33.489796
97
0.687574
5.671141
false
false
false
false
alessiobrozzi/firefox-ios
ReadingListTests/ReadingListStorageTestCase.swift
9
8782
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import ReadingList import Foundation import Shared import XCTest class ReadingListStorageTestCase: XCTestCase { var storage: ReadingListStorage! override func setUp() { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! if FileManager.default.fileExists(atPath: "\(path)/ReadingList.db") { do { try FileManager.default.removeItem(atPath: "\(path)/ReadingList.db") } catch _ { XCTFail("Cannot remove old \(path)/ReadingList.db") } } storage = ReadingListSQLStorage(path: "\(path)/ReadingList.db") } func testCreateRecord() { let result = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result { case .failure(let error): XCTFail(error.description) case .success(let result): XCTAssertEqual(result.value.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(result.value.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(result.value.addedBy, "Stefan's iPhone") XCTAssertEqual(result.value.unread, true) XCTAssertEqual(result.value.archived, false) XCTAssertEqual(result.value.favorite, false) } } func testGetRecordWithURL() { let result1 = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result1 { case .failure(let error): XCTFail(error.description) case .success( _): break } let result2 = storage.getRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") switch result2 { case .failure(let error): XCTFail(error.description) case .success( _): XCTAssert(result1.successValue == result2.successValue!) } } func testGetUnreadRecords() { // Create 3 records, mark the 2nd as read. let _ = createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let createResult2 = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") if let record = createResult2.successValue { let _ = updateRecord(record, unread: false) } // Get all unread records, make sure we only get the first and last let getUnreadResult = storage.getUnreadRecords() if let records = getUnreadResult.successValue { XCTAssertEqual(2, records.count) for record in records { XCTAssert(record.title == "Test 1" || record.title == "Test 3") XCTAssertEqual(record.unread, true) } } } func testGetAllRecords() { let _ = createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let createResult2 = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") if let record = createResult2.successValue { let _ = updateRecord(record, unread: false) } let getAllResult = storage.getAllRecords() if let records = getAllResult.successValue { XCTAssertEqual(3, records.count) } } func testGetNewRecords() { let _ = createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") let getAllResult = getAllRecords() if let records = getAllResult.successValue { XCTAssertEqual(3, records.count) } // TODO When we are able to create records coming from the server, we can extend this test to see if we query correctly } func testDeleteRecord() { let result1 = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result1 { case .failure(let error): XCTFail(error.description) case .success(_): break } let result2 = storage.deleteRecord(result1.successValue!) switch result2 { case .failure(let error): XCTFail(error.description) case .success: break } let result3 = storage.getRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") switch result3 { case .failure(let error): XCTFail(error.description) case .success(let result): XCTAssert(result.value == nil) } } func testDeleteAllRecords() { let _ = createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") let _ = createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") let getAllResult1 = storage.getAllRecords() if let records = getAllResult1.successValue { XCTAssertEqual(3, records.count) } let _ = deleteAllRecords() let getAllResult2 = getAllRecords() if let records = getAllResult2.successValue { XCTAssertEqual(0, records.count) } } func testUpdateRecord() { let result = createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") if let record = result.successValue { XCTAssertEqual(record.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(record.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(record.addedBy, "Stefan's iPhone") XCTAssertEqual(record.unread, true) XCTAssertEqual(record.archived, false) XCTAssertEqual(record.favorite, false) let result = updateRecord(record, unread: false) if let record = result.successValue! { XCTAssertEqual(record.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(record.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(record.addedBy, "Stefan's iPhone") XCTAssertEqual(record.unread, false) XCTAssertEqual(record.archived, false) XCTAssertEqual(record.favorite, false) } } } // Helpers that croak if the storage call was not succesful func createRecordWithURL(_ url: String, title: String, addedBy: String) -> Maybe<ReadingListClientRecord> { let result = storage.createRecordWithURL(url, title: title, addedBy: addedBy) XCTAssertTrue(result.isSuccess) return result } func deleteAllRecords() -> Maybe<Void> { let result = storage.deleteAllRecords() XCTAssertTrue(result.isSuccess) return result } func getAllRecords() -> Maybe<[ReadingListClientRecord]> { let result = storage.getAllRecords() XCTAssertTrue(result.isSuccess) return result } func updateRecord(_ record: ReadingListClientRecord, unread: Bool) -> Maybe<ReadingListClientRecord?> { let result = storage.updateRecord(record, unread: unread) XCTAssertTrue(result.isSuccess) return result } }
mpl-2.0
80121e9b4c48ee0531b1ea32c1a6014b
44.035897
239
0.643703
4.641649
false
true
false
false
hejunbinlan/actor-platform
actor-apps/app-ios/Actor/Controllers/Conversation/ConversationMessagesViewController.swift
2
10484
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation import UIKit; class ConversationBaseViewController: SLKTextViewController, MessagesLayoutDelegate, AMDisplayList_AndroidChangeListener { private var displayList: AMBindedDisplayList! private var applyingUpdate: AMAndroidListUpdate? private var isStarted: Bool = isIPad private var isUpdating: Bool = false private var isVisible: Bool = false private var isLoaded: Bool = false private var isLoadedAfter: Bool = false private var unreadIndex: Int? = nil private let layout = MessagesLayout() let peer: AMPeer init(peer: AMPeer) { self.peer = peer super.init(collectionViewLayout: layout) } required init!(coder decoder: NSCoder!) { fatalError("Not implemented"); } // Controller and UI lifecycle override func viewDidLoad() { if (self.displayList == nil) { self.displayList = displayListForController() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.collectionView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 200, right: 0) isVisible = true // Hack for delaying collection view init from first animation frame // This dramatically speed up controller opening if (isStarted) { self.willUpdate() self.collectionView.reloadData() self.displayList.addAndroidListener(self) self.didUpdate() return } else { self.collectionView.alpha = 0 } dispatch_async(dispatch_get_main_queue(),{ // What if controller is already closed? if (!self.isVisible) { return } self.isStarted = true UIView.animateWithDuration(0.15, animations: { () -> Void in self.collectionView.alpha = 1 }) self.willUpdate() self.collectionView.reloadData() self.displayList.addAndroidListener(self) self.didUpdate() }); } func buildCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UICollectionViewCell { fatalError("Not implemented") } func bindCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UICollectionViewCell) { fatalError("Not implemented") } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, gravityForItemAtIndexPath indexPath: NSIndexPath) -> MessageGravity { fatalError("Not implemented") } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, idForItemAtIndexPath indexPath: NSIndexPath) -> Int64 { fatalError("Not implemented") } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { fatalError("Not implemented") } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return isStarted ? getCount() : 0 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var item: AnyObject? = objectAtIndexPath(indexPath) var cell = buildCell(collectionView, cellForRowAtIndexPath:indexPath, item:item) bindCell(collectionView, cellForRowAtIndexPath: indexPath, item: item, cell: cell) displayList.touchWithIndex(jint(indexPath.row)) // cell.contentView.transform = collectionView.transform // cell.transform = collectionView.transform return cell } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) isVisible = false // Remove listener on exit self.displayList.removeAndroidListener(self) } // Model updates func displayListForController() -> AMBindedDisplayList { fatalError("Not implemented"); } func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? { return objectAtIndex(indexPath.row) } func objectAtIndex(index: Int) -> AnyObject? { if (isUpdating) { return applyingUpdate!.getItemWithInt(jint(index)) } return displayList.itemWithIndex(jint(index)) } func getCount() -> Int { if (isUpdating) { return Int(applyingUpdate!.getSize()) } return Int(displayList.size()) } func needFullReload(item: AnyObject?, cell: UICollectionViewCell) -> Bool { return false } func onItemsAdded(indexes: [Int]) { } func onItemsRemoved(indexes: [Int]) { } func onItemsUpdated(indexes: [Int]) { } func onItemMoved(fromIndex: Int, toIndex: Int) { } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willRotateToInterfaceOrientation(toInterfaceOrientation, duration: duration) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.collectionView.collectionViewLayout.invalidateLayout() }) } func onCollectionChangedWithChanges(modification: AMAndroidListUpdate!) { self.willUpdate() isUpdating = true applyingUpdate = modification if modification.isLoadMore() { UIView.setAnimationsEnabled(false) } self.layout.beginUpdates(modification.isLoadMore()) self.collectionView.performBatchUpdates({ () -> Void in var mod = modification.next() println("doUpdate \(mod)") while(mod != nil) { switch(UInt(mod.getOperationType().ordinal())) { case AMChangeDescription_OperationType.ADD.rawValue: var startIndex = Int(mod.getIndex()) var rows = [NSIndexPath]() var indexes = [Int]() for ind in 0..<mod.getLength() { indexes.append(Int(startIndex + ind)) rows.append(NSIndexPath(forRow: Int(startIndex + ind), inSection: 0)) } self.collectionView.insertItemsAtIndexPaths(rows) // self.onItemsAdded(indexes) break case AMChangeDescription_OperationType.REMOVE.rawValue: var startIndex = Int(mod.getIndex()) var rows = [NSIndexPath]() for ind in 0..<mod.getLength() { rows.append(NSIndexPath(forRow: Int(startIndex + ind), inSection: 0)) } self.collectionView.deleteItemsAtIndexPaths(rows) break case AMChangeDescription_OperationType.MOVE.rawValue: self.collectionView.moveItemAtIndexPath(NSIndexPath(forItem: Int(mod.getIndex()), inSection: 0), toIndexPath: NSIndexPath(forItem: Int(mod.getDestIndex()), inSection: 0)) break case AMChangeDescription_OperationType.UPDATE.rawValue: var rows = [Int]() var startIndex = Int(mod.getIndex()) for ind in 0..<mod.getLength() { rows.append(Int(startIndex + ind)) } self.updateRows(rows) break default: break } mod = modification.next() } }, completion: nil) if modification.isLoadMore() { UIView.setAnimationsEnabled(true) } isUpdating = false applyingUpdate = nil self.didUpdate() } func updateRows(indexes: [Int]) { var forcedRows = [NSIndexPath]() var visibleIndexes = self.collectionView.indexPathsForVisibleItems() as! [NSIndexPath] for ind in indexes { var indexPath = NSIndexPath(forRow: ind, inSection: 0) if visibleIndexes.contains(indexPath) { var cell = self.collectionView.cellForItemAtIndexPath(indexPath) var item: AnyObject? = self.objectAtIndexPath(indexPath) if !self.needFullReload(item, cell: cell!) { self.bindCell(self.collectionView, cellForRowAtIndexPath: indexPath, item: item, cell: cell!) continue } } forcedRows.append(indexPath) } if (forcedRows.count > 0) { self.layout.beginUpdates(false) self.collectionView.reloadItemsAtIndexPaths(forcedRows) // self.layout.endUpdates() } } func willUpdate() { isLoadedAfter = false if getCount() > 0 && !isLoaded { isLoaded = true isLoadedAfter = true var readState = MSG.loadLastReadState(peer) if readState > 0 { for i in 0..<getCount() { var ind = getCount() - 1 - i var item = objectAtIndex(ind)! if item.getSenderId() != MSG.myUid() { if readState < item.getSortDate() { unreadIndex = ind setUnread(item.getRid()) break } } } } } } func didUpdate() { if isLoadedAfter { if unreadIndex != nil { self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: unreadIndex!, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: false) } } } func setUnread(rid: jlong) { } }
mit
9ebbf8babf12302557ad52fd997b32ba
34.422297
195
0.577928
5.732094
false
false
false
false
emiscience/Prephirences
Prephirences/DictionaryPreferences.swift
1
7098
// // DictionaryPreferences.swift // Prephirences /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation // MARK: Dictionary Adapter // Adapt Dictionary to PreferencesType (with adapter pattern) public class DictionaryPreferences: PreferencesType, SequenceType, DictionaryLiteralConvertible { internal var dico : Dictionary<String,AnyObject> // MARK: init public init(dictionary: Dictionary<String,AnyObject>) { self.dico = dictionary } public init?(filePath: String) { if let d = NSDictionary(contentsOfFile: filePath) as? Dictionary<String,AnyObject> { self.dico = d } else { self.dico = [:] return nil } } public init?(filename: String?, ofType ext: String?, bundle: NSBundle = NSBundle.mainBundle()) { if let filePath = bundle.pathForResource(filename, ofType: ext) { if let d = NSDictionary(contentsOfFile: filePath) as? Dictionary<String,AnyObject> { self.dico = d } else { self.dico = [:] return nil } } else { self.dico = [:] return nil } } public init(preferences: PreferencesType) { self.dico = preferences.dictionary() } // MARK: DictionaryLiteralConvertibles public typealias Key = String public typealias Value = AnyObject public typealias Element = (Key, Value) public required convenience init(dictionaryLiteral elements: Element...) { self.init(dictionary: [:]) for (key, value) in elements { dico[key] = value } } // MARK: SequenceType public func generate() -> DictionaryGenerator<Key, Value> { return self.dico.generate() } public typealias Index = DictionaryIndex<Key, Value> public subscript (position: DictionaryIndex<Key, Value>) -> Element { get { return dico[position] } } public subscript(key : Key?) -> Value? { get { if key != nil { return dico[key!] } return nil } } // MARK: PreferencesType public subscript(key: String) -> AnyObject? { get { return dico[key] } } public func objectForKey(key: String) -> AnyObject? { return dico[key] } public func hasObjectForKey(key: String) -> Bool { return dico[key] != nil } public func stringForKey(key: String) -> String? { return dico[key] as? String } public func arrayForKey(key: String) -> [AnyObject]? { return dico[key] as? [AnyObject] } public func dictionaryForKey(key: String) -> [NSObject : AnyObject]? { return dico[key] as? [String: AnyObject] } public func dataForKey(key: String) -> NSData? { return dico[key] as? NSData } public func stringArrayForKey(key: String) -> [AnyObject]? { return self.arrayForKey(key) as? [String] } public func integerForKey(key: String) -> Int { return dico[key] as? Int ?? 0 } public func floatForKey(key: String) -> Float { return dico[key] as? Float ?? 0 } public func doubleForKey(key: String) -> Double { return dico[key] as? Double ?? 0 } public func boolForKey(key: String) -> Bool { return dico[key] as? Bool ?? false } public func URLForKey(key: String) -> NSURL? { return dico[key] as? NSURL } public func unarchiveObjectForKey(key: String) -> AnyObject? { return Prephirences.unarchiveObject(self, forKey: key) } public func dictionary() -> [String : AnyObject] { return self.dico } // MARK: specifics methods public func writeToFile(path: String, atomically: Bool = true) -> Bool { return (self.dico as NSDictionary).writeToFile(path, atomically: atomically) } } // MARK: - Mutable Dictionary Adapter public class MutableDictionaryPreferences: DictionaryPreferences, MutablePreferencesType { // MARK: MutablePreferencesType public override subscript(key: String) -> AnyObject? { get { return dico[key] } set { dico[key] = newValue } } public func setObject(value: AnyObject?, forKey key: String) { dico[key] = value } public func removeObjectForKey(key: String) { dico[key] = nil } public func setInteger(value: Int, forKey key: String){ dico[key] = value } public func setFloat(value: Float, forKey key: String){ dico[key] = value } public func setDouble(value: Double, forKey key: String) { setObject(NSNumber(double: value), forKey: key) } public func setBool(value: Bool, forKey key: String) { dico[key] = value } public func setURL(url: NSURL, forKey key: String) { dico[key] = url } public func setObjectToArchive(value: AnyObject?, forKey key: String) { Prephirences.archiveObject(value, preferences: self, forKey: key) } public func setObjectsForKeysWithDictionary(dictionary: [String:AnyObject]) { dico += dictionary } public func clearAll() { dico.removeAll() } } // MARK: - Buffered preferences public class BufferPreferences: MutableDictionaryPreferences { var buffered: MutablePreferencesType public init(_ buffered: MutablePreferencesType) { self.buffered = buffered super.init(dictionary: buffered.dictionary()) } public required convenience init(dictionaryLiteral elements: (Key, Value)...) { fatalError("init(dictionaryLiteral:) has not been implemented") } // MARK: specifics methods func commit() { buffered.setObjectsForKeysWithDictionary(self.dictionary()) } func rollback() { self.dico = buffered.dictionary() } }
mit
057ad3ff9c93cb94de34351af377d091
28.953586
100
0.628205
4.697551
false
false
false
false
okerivy/Coursera
Coursera/Coursera/Classes/Module/Profile/ProfileTableViewController.swift
1
3242
// // ProfileTableViewController.swift // Coursera // // Created by okerivy on 15/9/30. // Copyright © 2015年 okerivy. All rights reserved. // import UIKit class ProfileTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
71d91d1e74db8568ade88604e942461c
33.094737
157
0.687867
5.603806
false
false
false
false
alexth/VIPER-test
ViperTest/ViperTest/AppDelegate.swift
1
1455
// // AppDelegate.swift // ViperTest // // Created by Alex Golub on 10/27/16. // Copyright © 2016 Alex Golub. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.delegate = self return true } // MARK: App Lifecycle func applicationWillTerminate(_ application: UIApplication) { DataManager.sharedInstance.saveContext() } // MARK: Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.event == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
ff279ae67be57779a37f712e49420134
38.297297
189
0.740028
6.213675
false
false
false
false
alafighting/NetworkForSwift
NetworkForSwift/String.swift
1
2678
/* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2014 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com) * * Contributors: * Kåre Morstøl, https://github.com/kareman - initial API and implementation. */ import Foundation extension String { public func replace (oldString: String, _ newString: String) -> String { return self.stringByReplacingOccurrencesOfString(oldString, withString: newString) } /** Replace the first `limit` occurrences of oldString with newString. */ public func replace (oldString: String, _ newString: String, limit: Int) -> String { let ranges = self.findAll(oldString) |> take(limit) return ranges.count == 0 ? self : self.stringByReplacingOccurrencesOfString(oldString, withString: newString, range: ranges.first!.startIndex ..< ranges.last!.endIndex) } public func split (sep: String) -> [String] { return self.componentsSeparatedByString(sep) } public func trim () -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } public func countOccurrencesOf (substring: String) -> Int { return (self.findAll(substring) |> toArray).count } /** A lazy sequence of the ranges of `findstring` in this string. */ public func findAll (findstring: String) -> AnySequence<Range<String.Index>> { var rangeofremainder: Range = self.startIndex..<self.endIndex return AnySequence (anyGenerator { if let foundrange = self.rangeOfString(findstring, range:rangeofremainder) { rangeofremainder = foundrange.endIndex..<self.endIndex return foundrange } else { return nil } }) } /** Split the string at the first occurrence of separator, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. */ public func partition (separator: String) -> (String, String, String) { if let separatorRange = self.rangeOfString(separator) { if !separatorRange.isEmpty { let firstpart = self[self.startIndex ..< separatorRange.startIndex] let secondpart = self[separatorRange.endIndex ..< self.endIndex] return (firstpart, separator, secondpart) } } return (self,"","") } }
gpl-2.0
dde9de5584380ffe5e265fd27e5a6c67
37.753623
102
0.642857
4.792115
false
false
false
false
umich-software-prototyping-clinic/ios-app
iOS app/resetPasswordViewController.swift
1
9860
import UIKit class resetPasswordViewController: UIViewController,PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UITextFieldDelegate { let button = UIButton() let resetPasswordButton = UIButton() let printButton = UIButton() let userListButton = UIButton() let exampleTitle = UILabel() let newPasswordTitle = UILabel() let confirmPasswordTitle = UILabel() let newPasswordField = UITextField() let confirmPasswordField = UITextField() let changePasswordButton = UIButton() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(exampleTitle) exampleTitle.backgroundColor = UIColor.lightGrayColor() exampleTitle.sizeToHeight(30) exampleTitle.sizeToWidth(600) exampleTitle.pinToTopEdgeOfSuperview(20) exampleTitle.centerHorizontallyInSuperview() exampleTitle.font = UIFont(name: "AvenirNext-DemiBold", size: 30) exampleTitle.textAlignment = NSTextAlignment.Center exampleTitle.text = "Example App" exampleTitle.textColor = UIColor.whiteColor() self.view.addSubview(newPasswordTitle) newPasswordTitle.sizeToHeight(40) newPasswordTitle.sizeToWidth(150) newPasswordTitle.centerVerticallyInSuperview() newPasswordTitle.pinToLeftEdgeOfSuperview(30) newPasswordTitle.text = "New Password: " self.view.addSubview(newPasswordField) newPasswordField.delegate = self newPasswordField.sizeToHeight(40) newPasswordField.sizeToWidth(200) newPasswordField.positionToTheRightOfItem(newPasswordTitle, offset: 10) newPasswordField.centerVerticallyInSuperview() newPasswordField.layer.borderWidth = 1 newPasswordField.layer.borderColor = UIColor.blackColor().CGColor self.view.addSubview(confirmPasswordTitle) confirmPasswordTitle.sizeToHeight(40) confirmPasswordTitle.sizeToWidth(200) confirmPasswordTitle.positionBelowItem(newPasswordTitle, offset: 20) confirmPasswordTitle.pinToLeftEdgeOfSuperview(30) confirmPasswordTitle.text = "Confirm Password: " self.view.addSubview(confirmPasswordField) confirmPasswordField.delegate = self confirmPasswordField.sizeToHeight(40) confirmPasswordField.sizeToWidth(200) confirmPasswordField.positionBelowItem(newPasswordField, offset: 20) confirmPasswordField.pinLeftEdgeToLeftEdgeOfItem(newPasswordField) confirmPasswordField.layer.borderWidth = 1 confirmPasswordField.layer.borderColor = UIColor.blackColor().CGColor self.view.addSubview(changePasswordButton) changePasswordButton.backgroundColor = UIColor.purpleColor() changePasswordButton.sizeToHeight(40) changePasswordButton.sizeToWidth(200) changePasswordButton.centerHorizontallyInSuperview() changePasswordButton.positionBelowItem(confirmPasswordField, offset: 30) changePasswordButton.setTitle("Change Password", forState: UIControlState.Normal) changePasswordButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) changePasswordButton.addTarget(self, action: "passwordCheck", forControlEvents: .TouchUpInside) self.view.addSubview(button) button.backgroundColor = UIColor.darkGrayColor() button.sizeToHeight(40) button.sizeToWidth(100) button.pinToBottomEdgeOfSuperview() button.setTitle("Logout", forState: UIControlState.Normal) button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) button.addTarget(self, action: "logoutAction", forControlEvents: .TouchUpInside) self.view.addSubview(resetPasswordButton) resetPasswordButton.backgroundColor = UIColor.darkGrayColor() resetPasswordButton.pinToBottomEdgeOfSuperview() resetPasswordButton.sizeToHeight(40) resetPasswordButton.sizeToWidth(100) resetPasswordButton.positionToTheRightOfItem(button, offset: 5) resetPasswordButton.setTitle("Reset Pswd", forState: UIControlState.Normal) resetPasswordButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) resetPasswordButton.addTarget(self, action: "resetAction", forControlEvents: .TouchUpInside) self.view.addSubview(printButton) printButton.backgroundColor = UIColor.darkGrayColor() printButton.sizeToHeight(40) printButton.sizeToWidth(100) printButton.pinToRightEdgeOfSuperview() printButton.pinToBottomEdgeOfSuperview() printButton.setTitle("Print Text", forState: UIControlState.Normal) printButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) printButton.addTarget(self, action: "printAction", forControlEvents: .TouchUpInside) self.view.addSubview(userListButton) userListButton.backgroundColor = UIColor.darkGrayColor() userListButton.sizeToHeight(40) userListButton.sizeToWidth(100) userListButton.positionToTheLeftOfItem(printButton, offset: 5) userListButton.pinToBottomEdgeOfSuperview() userListButton.setTitle("User List", forState: UIControlState.Normal) userListButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) userListButton.addTarget(self, action: "userListAction", forControlEvents: .TouchUpInside) }//viewDidLoad func loginSetup() { if (PFUser.currentUser() == nil) { let loginViewController = PFLogInViewController() loginViewController.delegate = self let signupViewController = PFSignUpViewController() signupViewController.delegate = self loginViewController.signUpController = signupViewController loginViewController.fields = ([PFLogInFields.LogInButton, PFLogInFields.SignUpButton, PFLogInFields.UsernameAndPassword, PFLogInFields.PasswordForgotten , PFLogInFields.DismissButton]) // let signupTitle = UILabel() // signupTitle.text = "Barter Signup" //loginLogo let loginLogoImageView = UIImageView() loginLogoImageView.image = UIImage(named: "swap") loginLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit //signupLogo let signupLogoImageView = UIImageView() signupLogoImageView.image = UIImage(named: "swap") signupLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit loginViewController.view.backgroundColor = UIColor.whiteColor() signupViewController.view.backgroundColor = UIColor.whiteColor() loginViewController.logInView?.logo = loginLogoImageView signupViewController.signUpView?.logo = signupLogoImageView self.presentViewController(loginViewController, animated: true, completion: nil) }//if }//func //Checks if username and password are empty func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { if (!username.isEmpty || !password.isEmpty) { return true }//if else { return false }//else }//func //Closes login view after user logs in func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for login error func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { print("Failed to login....") }//func //MARK: Parse SignUp //Closes signup view after user signs in func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for signup error func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { print("Failed to signup") }//func //Checks if user cancelled signup func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { print("User dismissed signup") }//func //Logs out user func logoutAction() { print("logging out") PFUser.logOut() self.loginSetup() }//func func printAction() { print("clicked") let PVC = printViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func userListAction() { print("clicked") let PVC = LoginViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func resetAction() { print("clicked") let RVC = resetPasswordViewController() self.presentViewController(RVC, animated: false, completion: nil) }//func func passwordCheck() { print("clicked") if (self.newPasswordField.text == self.confirmPasswordField.text) { print("password matches") let CVC = confirmPageViewController() self.presentViewController(CVC, animated: false, completion: nil) } else { print("passwords did not match") } } }
mit
19c250fec904f53db10ee034ed4fb01d
39.413934
197
0.680629
5.950513
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-422/SafeRide/Pods/CryptoSwift/Sources/CryptoSwift/PKCS7.swift
8
1627
// // PKCS7.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 28/02/15. // Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. // // PKCS is a group of public-key cryptography standards devised // and published by RSA Security Inc, starting in the early 1990s. // public struct PKCS7: Padding { public enum Error: ErrorType { case InvalidPaddingValue } public init() { } public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] { let padding = UInt8(blockSize - (bytes.count % blockSize)) var withPadding = bytes if (padding == 0) { // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added. for _ in 0..<blockSize { withPadding.appendContentsOf([UInt8(blockSize)]) } } else { // The value of each added byte is the number of bytes that are added for _ in 0..<padding { withPadding.appendContentsOf([UInt8(padding)]) } } return withPadding } public func remove(bytes: [UInt8], blockSize:Int?) -> [UInt8] { assert(bytes.count > 0, "Need bytes to remove padding") guard bytes.count > 0, let lastByte = bytes.last else { return bytes } let padding = Int(lastByte) // last byte let finalLength = bytes.count - padding if finalLength < 0 { return bytes } if padding >= 1 { return Array(bytes[0..<finalLength]) } return bytes } }
gpl-3.0
4daf8e60c227d3d98af0bb34d3d85cde
27.561404
113
0.56976
4.409214
false
false
false
false
GeoThings/LakestoneCore
Source/Threading.swift
1
5769
// // Threading.swift // geoBingAnCore // // Created by Taras Vozniuk on 6/7/16. // Copyright © 2016 GeoThings. All rights reserved. // // -------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // Threading-related set of abstractions // The abstractions is alligned to correspond to PerfectThread API naming // // PerfectThread.Threading.Lock has been coppied here to provide the corresponding // iOS Lock implementation for a sake of not having PerfectThread as iOS dependency // #if COOPER import android.os import java.util.concurrent #else import Foundation import Dispatch #endif //TODO: GeoThings/LakestoneCore: Issue #5: Reconsider Threading abstractions //link: https://github.com/GeoThings/LakestoneCore/issues/5 #if COOPER public typealias ThreadQueue = ExecutorService public typealias ConstraintConcurrentThreadQueue = ExecutorService public typealias Semaphore = java.util.concurrent.Semaphore // ReentrantLock provides the corresponding functionaly with matching lock()/tryLock()/unlock() naming public typealias Lock = java.util.concurrent.locks.ReentrantLock #else public typealias ThreadQueue = DispatchQueue public typealias ConstraintConcurrentThreadQueue = OperationQueue public typealias Semaphore = DispatchSemaphore public class Lock { var mutex = pthread_mutex_t() /// Initialize a new lock object. public init() { var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, Int32(PTHREAD_MUTEX_RECURSIVE)) pthread_mutex_init(&mutex, &attr) } deinit { pthread_mutex_destroy(&mutex) } /// Attempt to grab the lock. /// Returns true if the lock was successful. @discardableResult public func lock() -> Bool { return 0 == pthread_mutex_lock(&self.mutex) } /// Attempt to grab the lock. /// Will only return true if the lock was not being held by any other thread. /// Returns false if the lock is currently being held by another thread. public func tryLock() -> Bool { return 0 == pthread_mutex_trylock(&self.mutex) } /// Unlock. Returns true if the lock was held by the current thread and was successfully unlocked. ior the lock count was decremented. @discardableResult public func unlock() -> Bool { return 0 == pthread_mutex_unlock(&self.mutex) } /// Acquire the lock, execute the closure, release the lock. public func doWithLock(closure: () throws -> ()) rethrows { let _ = self.lock() defer { let _ = self.unlock() } try closure() } } #endif /// Executes the closure synchronized on given reentrant mutual exlusion lock public func synchronized(on lock: Lock, closure: () -> Void){ lock.lock() closure() lock.unlock() } /// Utilities for threading public class Threading { public class func dispatchOnMainQueue(_ closure: @escaping () -> Void){ #if COOPER Handler(Looper.getMainLooper()).post { closure() } #else DispatchQueue.main.async(execute: closure) #endif } } extension ThreadQueue { public func dispatch(_ closure: @escaping () -> Void){ #if COOPER self.execute { closure() } #else self.async(execute: closure) #endif } } #if !COOPER extension ConstraintConcurrentThreadQueue { public func dispatch(_ closure: @escaping () -> Void){ self.addOperation { closure() } } } #endif extension Threading { /// creates a new serial queue, exception is Linux/OSX, /// where if queue with a given label exists already, existing queue will be returned public static func serialQueue(withLabel label: String) -> ThreadQueue { #if COOPER return Executors.newSingleThreadExecutor() #else return DispatchQueue(label: label, qos: DispatchQoS.default) #endif } public static func concurrentQueue(withMaximumConcurrentThreads threadCount: Int) -> ConstraintConcurrentThreadQueue { #if COOPER //corePoolSize: Integer, maximumPoolSize: Integer, keepAliveTime: Int64, unit: TimeUnit!, workQueue: BlockingQueue<Runnable>! return ThreadPoolExecutor(threadCount, threadCount, 60, TimeUnit.SECONDS, LinkedBlockingQueue<Runnable>()) #else let concurrentQueue = OperationQueue() concurrentQueue.maxConcurrentOperationCount = threadCount return concurrentQueue #endif } } #if COOPER extension Semaphore { public init(value: Int){ self.init(value) } public func signal(){ self.release() } } #else extension Semaphore { public func acquire(){ self.wait() } } #endif #if COOPER public func dispatch(on looper: android.os.Looper, closure: @escaping () -> Void){ Handler(looper).post { closure() } } #else public func dispatch(on queue: DispatchQueue, closure: @escaping () -> Void){ queue.dispatch(closure) } #endif
apache-2.0
9a2f5ff72a5df31fb74ca838719516bf
26.079812
142
0.656553
4.343373
false
false
false
false
tsolomko/SWCompression
Sources/TAR/TarParser.swift
1
3237
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData // While it is tempting to make Provider conform to `IteratorProtocol` and `Sequence` protocols, it is in fact // impossible to do so, since `TarHeader.init(...)` is throwing and `IteratorProtocol.next()` cannot be throwing. struct TarParser { enum ParsingResult { case truncated case eofMarker case finished case specialEntry(TarHeader.SpecialEntryType) case entryInfo(TarEntryInfo, Int, TarContainer.Format) } private let reader: LittleEndianByteReader private var lastGlobalExtendedHeader: TarExtendedHeader? private var lastLocalExtendedHeader: TarExtendedHeader? private var longLinkName: String? private var longName: String? init(_ data: Data) { self.reader = LittleEndianByteReader(data: data) self.lastGlobalExtendedHeader = nil self.lastLocalExtendedHeader = nil self.longLinkName = nil self.longName = nil } mutating func next() throws -> ParsingResult { if reader.isFinished { return .finished } else if reader.bytesLeft >= 1024 && reader.data[reader.offset..<reader.offset + 1024] == Data(count: 1024) { return .eofMarker } else if reader.bytesLeft < 512 { return .truncated } let header = try TarHeader(reader) // For header we read at most 512 bytes. assert(reader.offset - header.blockStartIndex <= 512) // Check, just in case, since we use blockStartIndex = -1 when creating TAR containers. assert(header.blockStartIndex >= 0) let dataStartIndex = header.blockStartIndex + 512 if case .special(let specialEntryType) = header.type { switch specialEntryType { case .globalExtendedHeader: let dataEndIndex = dataStartIndex + header.size lastGlobalExtendedHeader = try TarExtendedHeader(reader.data[dataStartIndex..<dataEndIndex]) case .sunExtendedHeader: fallthrough case .localExtendedHeader: let dataEndIndex = dataStartIndex + header.size lastLocalExtendedHeader = try TarExtendedHeader(reader.data[dataStartIndex..<dataEndIndex]) case .longLinkName: reader.offset = dataStartIndex longLinkName = reader.tarCString(maxLength: header.size) case .longName: reader.offset = dataStartIndex longName = reader.tarCString(maxLength: header.size) } reader.offset = dataStartIndex + header.size.roundTo512() return .specialEntry(specialEntryType) } else { let info = TarEntryInfo(header, lastGlobalExtendedHeader, lastLocalExtendedHeader, longName, longLinkName) // Skip file data. reader.offset = dataStartIndex + header.size.roundTo512() lastLocalExtendedHeader = nil longName = nil longLinkName = nil return .entryInfo(info, header.blockStartIndex, header.format) } } }
mit
6e36f580d9d76daad5cba2abe58770fa
38.962963
118
0.647822
5.129952
false
false
false
false
black-lotus/dnCalendar-iOS
dnCalendar/DNCalendarExtension.swift
1
2103
// // DNCalendarExtension.swift // dnCalendar // // Created by romdoni agung purbayanto on 5/11/16. // Copyright © 2016 romdoni agung purbayanto. All rights reserved. // import UIKit extension NSDate { func startOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() let currentDateComponents = calendar.components([.Year, .Month, .Day], fromDate: self) return calendar.dateFromComponents(currentDateComponents) } func endOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() let dayRange = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self) let dayCount = dayRange.length let comp = calendar.components([.Year, .Month, .Day], fromDate: self) comp.day = dayCount return calendar.dateFromComponents(comp)! } func dayIndex() -> Int { let dayFormatter: NSDateFormatter = NSDateFormatter() dayFormatter.dateFormat = "EEEE" dayFormatter.locale = NSLocale(localeIdentifier: "en-US") let strDayName: String = dayFormatter.stringFromDate(self) var index: Int = 0 switch strDayName { case "Sunday": index = 0 case "Monday": index = 1 case "Tuesday": index = 2 case "Wednesday": index = 3 case "Thursday": index = 4 case "Friday": index = 5 case "Saturday": index = 6 default: print("not found") } return index } class func parseStringIntoDate(input: String, format: String) -> NSDate { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format return dateFormatter.dateFromString(input)! } } extension UIView { public func removeAllSubviews() { for subview in subviews { subview.removeFromSuperview() } } }
apache-2.0
15a418e4de61856fba87db8c9ff2803c
25.2875
94
0.55471
5.114355
false
false
false
false
gottesmm/swift
test/SILGen/dynamic_self.swift
2
13504
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s protocol P { func f() -> Self } protocol CP : class { func f() -> Self } class X : P, CP { required init(int i: Int) { } // CHECK-LABEL: sil hidden @_T012dynamic_self1XC1f{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed X) -> @owned func f() -> Self { return self } // CHECK-LABEL: sil hidden @_T012dynamic_self1XC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type): // CHECK: [[CTOR:%[0-9]+]] = class_method [[SELF]] : $@thick X.Type, #X.init!allocator.1 : (X.Type) -> (Int) -> X , $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: apply [[CTOR]]([[I]], [[SELF]]) : $@convention(method) (Int, @thick X.Type) -> @owned X class func factory(i: Int) -> Self { return self.init(int: i) } } class Y : X { required init(int i: Int) { } } class GX<T> { func f() -> Self { return self } } class GY<T> : GX<[T]> { } // CHECK-LABEL: sil hidden @_T012dynamic_self23testDynamicSelfDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Y) -> () func testDynamicSelfDispatch(y: Y) { // CHECK: bb0([[Y:%[0-9]+]] : $Y): // CHECK: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK: [[Y_AS_X_COPY:%[0-9]+]] = upcast [[Y_COPY]] : $Y to $X // CHECK: [[X_F:%[0-9]+]] = class_method [[Y_AS_X_COPY]] : $X, #X.f!1 : (X) -> () -> @dynamic_self X , $@convention(method) (@guaranteed X) -> @owned X // CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[Y_AS_X_COPY]]) : $@convention(method) (@guaranteed X) -> @owned X // CHECK: destroy_value [[Y_AS_X_COPY]] // CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y // CHECK: destroy_value [[Y_RESULT]] : $Y // CHECK: destroy_value [[Y]] : $Y y.f() } // CHECK-LABEL: sil hidden @_T012dynamic_self30testDynamicSelfDispatchGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned GY<Int>) -> () func testDynamicSelfDispatchGeneric(gy: GY<Int>) { // CHECK: bb0([[GY:%[0-9]+]] : $GY<Int>): // CHECK: [[GY_COPY:%.*]] = copy_value [[GY]] // CHECK: [[GY_AS_GX_COPY:%[0-9]+]] = upcast [[GY_COPY]] : $GY<Int> to $GX<Array<Int>> // CHECK: [[GX_F:%[0-9]+]] = class_method [[GY_AS_GX_COPY]] : $GX<Array<Int>>, #GX.f!1 : <T> (GX<T>) -> () -> @dynamic_self GX<T> , $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[GY_AS_GX_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: destroy_value [[GY_AS_GX_COPY]] // CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int> // CHECK: destroy_value [[GY_RESULT]] : $GY<Int> // CHECK: destroy_value [[GY]] gy.f() } // CHECK-LABEL: sil hidden @_T012dynamic_self21testArchetypeDispatch{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P> (@in T) -> () func testArchetypeDispatch<T: P>(t: T) { // CHECK: bb0([[T:%[0-9]+]] : $*T): // CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 t.f() } // CHECK-LABEL: sil hidden @_T012dynamic_self23testExistentialDispatch{{[_0-9a-zA-Z]*}}F func testExistentialDispatch(p: P) { // CHECK: bb0([[P:%[0-9]+]] : $*P): // CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr [[P]] : $*P to $*@opened([[N:".*"]]) P // CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P // CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P // CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: destroy_addr [[P_RESULT]] : $*P // CHECK: dealloc_stack [[P_RESULT]] : $*P // CHECK: destroy_addr [[P]] : $*P p.f() } // CHECK-LABEL: sil hidden @_T012dynamic_self28testExistentialDispatchClass{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned CP) -> () func testExistentialDispatchClass(cp: CP) { // CHECK: bb0([[CP:%[0-9]+]] : $CP): // CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[CP]] : $CP to $@opened([[N:".*"]]) CP // CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1, [[CP_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP // CHECK: destroy_value [[CP_F_RESULT]] : $@opened([[N]]) CP cp.f() } @objc class ObjC { @objc func method() -> Self { return self } } // CHECK-LABEL: sil hidden @_T012dynamic_self21testAnyObjectDispatchys0dE0_p1o_tF : $@convention(thin) (@owned AnyObject) -> () { func testAnyObjectDispatch(o: AnyObject) { // CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject): // CHECK: [[O_OBJ_COPY:%.*]] = copy_value [[O_OBJ]] // CHECK: [[VAR_9:%[0-9]+]] = partial_apply [[METHOD]]([[O_OBJ_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject var x = o.method } // CHECK: } // end sil function '_T012dynamic_self21testAnyObjectDispatchys0dE0_p1o_tF' // <rdar://problem/16270889> Dispatch through ObjC metatypes. class ObjCInit { dynamic required init() { } } // CHECK: sil hidden @_T012dynamic_self12testObjCInit{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@thick ObjCInit.Type) -> () func testObjCInit(meta: ObjCInit.Type) { // CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type): // CHECK: [[O:%[0-9]+]] = alloc_box ${ var ObjCInit } // CHECK: [[PB:%.*]] = project_box [[O]] // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type // CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit // CHECK: [[INIT:%[0-9]+]] = class_method [volatile] [[OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : (ObjCInit.Type) -> () -> ObjCInit , $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: store [[RESULT_OBJ]] to [init] [[PB]] : $*ObjCInit // CHECK: destroy_value [[O]] : ${ var ObjCInit } // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() var o = meta.init() } class OptionalResult { func foo() -> Self? { return self } } // CHECK-LABEL: sil hidden @_T012dynamic_self14OptionalResultC3fooACXDSgyF : $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> { // CHECK: bb0([[SELF:%.*]] : $OptionalResult): // CHECK-NEXT: debug_value [[SELF]] : $OptionalResult // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.some!enumelt.1, [[SELF_COPY]] : $OptionalResult // CHECK-NEXT: return [[T0]] : $Optional<OptionalResult> // CHECK: } // end sil function '_T012dynamic_self14OptionalResultC3fooACXDSgyF' class OptionalResultInheritor : OptionalResult { func bar() {} } func testOptionalResult(v : OptionalResultInheritor) { v.foo()?.bar() } // CHECK-LABEL: sil hidden @_T012dynamic_self18testOptionalResultyAA0dE9InheritorC1v_tF : $@convention(thin) (@owned OptionalResultInheritor) -> () { // CHECK: bb0([[ARG:%.*]] : $OptionalResultInheritor): // CHECK: [[COPY_ARG:%.*]] = copy_value [[ARG]] // CHECK: [[CAST_COPY_ARG:%.*]] = upcast [[COPY_ARG]] // CHECK: [[T0:%.*]] = class_method [[CAST_COPY_ARG]] : $OptionalResult, #OptionalResult.foo!1 : (OptionalResult) -> () -> @dynamic_self OptionalResult? , $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> // CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[CAST_COPY_ARG]]) // CHECK: select_enum [[RES]] // CHECK: [[T1:%.*]] = unchecked_enum_data [[RES]] // CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[T1]] : $OptionalResult to $OptionalResultInheritor // CHECK-NEXT: enum $Optional<OptionalResultInheritor>, #Optional.some!enumelt.1, [[T4]] class Z { // CHECK-LABEL: sil hidden @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tF : $@convention(method) (Int, @guaranteed Z) -> @owned Z { func testDynamicSelfCaptures(x: Int) -> Self { // CHECK: bb0({{.*}}, [[SELF:%.*]] : $Z): // Single capture of 'self' type // CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU_ : $@convention(thin) (@owned Z) -> () // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z // CHECK-NEXT: partial_apply [[FN]]([[SELF_COPY]]) let fn1 = { _ = self } fn1() // Capturing 'self', but it's not the last capture. Make sure it ends // up at the end of the list anyway // CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU0_ : $@convention(thin) (Int, @owned Z) -> () // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z // CHECK-NEXT: partial_apply [[FN]]({{.*}}, [[SELF_COPY]]) let fn2 = { _ = self _ = x } fn2() // Capturing 'self' weak, so we have to pass in a metatype explicitly // so that IRGen can recover metadata. // CHECK: [[WEAK_SELF:%.*]] = alloc_box ${ var @sil_weak Optional<Z> } // CHECK: [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU1_ : $@convention(thin) (@owned { var @sil_weak Optional<Z> }, @thick Z.Type) -> () // CHECK: [[WEAK_SELF_COPY:%.*]] = copy_value [[WEAK_SELF]] : ${ var @sil_weak Optional<Z> } // CHECK-NEXT: [[DYNAMIC_SELF:%.*]] = metatype $@thick @dynamic_self Z.Type // CHECK-NEXT: [[STATIC_SELF:%.*]] = upcast [[DYNAMIC_SELF]] : $@thick @dynamic_self Z.Type to $@thick Z.Type // CHECK: partial_apply [[FN]]([[WEAK_SELF_COPY]], [[STATIC_SELF]]) : $@convention(thin) (@owned { var @sil_weak Optional<Z> }, @thick Z.Type) -> () let fn3 = { [weak self] in _ = self } fn3() return self } } // Unbound reference to a method returning Self. class Factory { func newInstance() -> Self {} class func classNewInstance() -> Self {} static func staticNewInstance() -> Self {} } // CHECK-LABEL: sil hidden @_T012dynamic_self22partialApplySelfReturnyAA7FactoryC1c_ADm1ttF : $@convention(thin) (@owned Factory, @thick Factory.Type) -> () func partialApplySelfReturn(c: Factory, t: Factory.Type) { // CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory _ = c.newInstance // CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory _ = Factory.newInstance // CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_owned () -> @owned Factory _ = t.newInstance _ = type(of: c).newInstance // CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = t.classNewInstance // CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = type(of: c).classNewInstance // CHECK: function_ref @_T012dynamic_self7FactoryC16classNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = Factory.classNewInstance // CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = t.staticNewInstance // CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = type(of: c).staticNewInstance // CHECK: function_ref @_T012dynamic_self7FactoryC17staticNewInstanceACXDyFZTc : $@convention(thin) (@thick Factory.Type) -> @owned @callee_owned () -> @owned Factory _ = Factory.staticNewInstance } // CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self { // CHECK: method #P.f!1: @_T012dynamic_self1XCAA1PAaaDP1f{{[_0-9a-zA-Z]*}}FTW // CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self { // CHECK: method #CP.f!1: @_T012dynamic_self1XCAA2CPAaaDP1f{{[_0-9a-zA-Z]*}}FTW
apache-2.0
35fcb00c78c66f659f7ecdddd76c3136
53.550607
244
0.614739
3.129122
false
true
false
false
simonbs/Emcee
Emcee/Source/Views/StatusItemView.swift
1
2952
// // StatusItemView.swift // NowScrobbling // // Created by Simon Støvring on 22/03/15. // Copyright (c) 2015 SimonBS. All rights reserved. // import Cocoa @objc protocol StatusItemViewDelegate { optional func statusItemViewClicked(view: StatusItemView) optional func statusItemViewRightClicked(view: StatusItemView) } class StatusItemView: NSView { enum Style: String { case Dark = "dark" case Light = "light" } internal let item: NSStatusItem internal weak var delegate: StatusItemViewDelegate? internal var style: Style = .Dark { didSet { needsDisplay = true } } internal var text: NSAttributedString? { didSet { needsDisplay = true } } internal var isSelected: Bool = false { didSet { if (isSelected != oldValue) { self.needsDisplay = true } } } init(item: NSStatusItem) { self.item = item let thickness = NSStatusBar.systemStatusBar().thickness let rect = CGRectMake(0, 0, thickness, thickness) super.init(frame: rect) item.view = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(dirtyRect: NSRect) { item.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: isSelected) let thickness = NSStatusBar.systemStatusBar().thickness if let text = text { let mutableText = NSMutableAttributedString(attributedString: text) let entireRange = NSMakeRange(0, mutableText.length) if style == .Light { mutableText.addAttribute(NSForegroundColorAttributeName, value: NSColor.whiteColor(), range: entireRange) } else { mutableText.addAttribute(NSForegroundColorAttributeName, value: NSColor.blackColor(), range: entireRange) } let maxSize = NSSize(width: CGFloat(MAXFLOAT), height: thickness) let textSize = text.boundingRectWithSize(maxSize, options: []) let yOffset = (thickness - textSize.height) / 2 let rect = NSRect(x: 0, y: yOffset + 1, width: textSize.width, height: textSize.height) text.drawInRect(rect) item.length = rect.width } else { let image = NSImage(named: "statusbar-\(style.rawValue)")! let yOffset = (thickness - image.size.height) / 2 let rect = CGRectMake(0, yOffset, image.size.width, image.size.height) image.drawInRect(rect) item.length = image.size.width } } override func mouseDown(theEvent: NSEvent) { delegate?.statusItemViewClicked?(self) } override func rightMouseDown(theEvent: NSEvent) { delegate?.statusItemViewRightClicked?(self) } }
mit
59a7cff613d9c9b030373fa6a89ed97d
31.076087
121
0.608946
4.934783
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Vendor/Kingsfisher/CacheSerializer.swift
1
3739
// // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. internal protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. internal struct DefaultCacheSerializer: CacheSerializer { internal static let `default` = DefaultCacheSerializer() private init() {} internal func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } internal func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } }
apache-2.0
b795b0d1a9b25ad29dd605ffa9fc70f7
41.977011
85
0.681198
4.72096
false
false
false
false
rudkx/swift
test/decl/protocol/recursive_requirement.swift
1
2283
// RUN: %target-typecheck-verify-swift // ----- protocol Foo { associatedtype Bar : Foo } struct Oroborous : Foo { typealias Bar = Oroborous } // ----- protocol P { associatedtype A : P } struct X<T: P> { } func f<T : P>(_ z: T) { _ = X<T.A>() } // ----- protocol PP2 { associatedtype A : P2 = Self } protocol P2 : PP2 { associatedtype A = Self } struct X2<T: P2> { } struct Y2 : P2 { typealias A = Y2 } func f<T : P2>(_ z: T) { _ = X2<T.A>() } // ----- protocol P3 { associatedtype A: P4 = Self } protocol P4 : P3 {} protocol DeclaredP : P3, // expected-warning{{redundant conformance constraint 'Self' : 'P3'}} P4 {} // expected-note{{conformance constraint 'Self' : 'P3' implied here}} struct Y3 : DeclaredP { } struct X3<T:P4> {} func f2<T:P4>(_ a: T) { _ = X3<T.A>() } f2(Y3()) // ----- protocol Alpha { associatedtype Beta: Gamma } protocol Gamma { associatedtype Delta: Alpha } struct Epsilon<T: Alpha, // expected-note{{conformance constraint 'U' : 'Gamma' implied here}} U: Gamma> // expected-warning{{redundant conformance constraint 'U' : 'Gamma'}} where T.Beta == U, U.Delta == T {} // ----- protocol AsExistentialA { var delegate : AsExistentialB? { get } } protocol AsExistentialB { func aMethod(_ object : AsExistentialA) } protocol AsExistentialAssocTypeA { var delegate : AsExistentialAssocTypeB? { get } // expected-warning {{use of protocol 'AsExistentialAssocTypeB' as a type must be written 'any AsExistentialAssocTypeB'}} } protocol AsExistentialAssocTypeB { func aMethod(_ object : AsExistentialAssocTypeA) associatedtype Bar } protocol AsExistentialAssocTypeAgainA { var delegate : AsExistentialAssocTypeAgainB? { get } associatedtype Bar } protocol AsExistentialAssocTypeAgainB { func aMethod(_ object : AsExistentialAssocTypeAgainA) // expected-warning {{use of protocol 'AsExistentialAssocTypeAgainA' as a type must be written 'any AsExistentialAssocTypeAgainA'}} } // SR-547 protocol A { associatedtype B1: B associatedtype C1: C mutating func addObserver(_ observer: B1, forProperty: C1) } protocol C { } protocol B { associatedtype BA: A associatedtype BC: C func observeChangeOfProperty(_ property: BC, observable: BA) }
apache-2.0
73f9f192489b2dc0f9be0ff22abf14d0
17.119048
187
0.665353
3.427928
false
false
false
false
DanielFulton/ImageLibraryTests
Pods/MapleBacon/Library/MapleBacon/MapleBacon/ImageGifExtension.swift
3
3392
// // Copyright (c) 2015 Zalando SE. All rights reserved. // import UIKit import ImageIO extension UIImage { class func imageWithCachedData(data: NSData) -> UIImage? { guard data.length > 0 else { return nil } return isAnimatedImage(data) ? animatedImageWithData(data) : UIImage(data: data) } private class func animatedImageWithData(data: NSData) -> UIImage? { let source = CGImageSourceCreateWithData(data as CFDataRef, nil) return UIImage.animatedImageWithSource(source) } private class func isAnimatedImage(data: NSData) -> Bool { var length = UInt16(0) data.getBytes(&length, range: NSRange(location: 0, length: 2)) return CFSwapInt16(length) == 0x4749 } private class func animatedImageWithSource(source: CGImageSourceRef!) -> UIImage? { let (images, delays) = createImagesAndDelays(source) let gifDuration = delays.reduce(0, combine: +) let frames = framesFromImages(images, delays: delays) return UIImage.animatedImageWithImages(frames, duration: Double(gifDuration) / 1000.0) } private class func framesFromImages(images: [CGImageRef], delays: [Int]) -> [UIImage] { let gcd = DivisionMath.greatestCommonDivisor(delays) var frames = [UIImage]() for i in 0..<images.count { let frame = UIImage(CGImage: images[Int(i)]) let frameCount = abs(Int(delays[Int(i)] / gcd)) for _ in 0..<frameCount { frames.append(frame) } } return frames } private class func createImagesAndDelays(source: CGImageSourceRef) -> ([CGImageRef], [Int]) { let count = Int(CGImageSourceGetCount(source)) var images = [CGImageRef]() var delayCentiseconds = [Int]() for i in 0 ..< count { if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { images.append(image) delayCentiseconds.append(delayCentisecondsForImageAtIndex(source, index: i)) } } return (images, delayCentiseconds) } private class func delayCentisecondsForImageAtIndex(let source: CGImageSourceRef, let index: Int) -> Int { if let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil), properties: NSDictionary = cfProperties, gifProperties = properties[kCGImagePropertyGIFDictionary as String] as? NSDictionary { var delayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as String] as! NSNumber if delayTime.doubleValue == 0 { delayTime = gifProperties[kCGImagePropertyGIFDelayTime as String] as! NSNumber } return Int(delayTime.doubleValue * 1000) } return -1 } private class DivisionMath { class func greatestCommonDivisor(array: [Int]) -> Int { return array.reduce(array[0]) { self.greatestCommonDivisorForPair($0, $1) } } class func greatestCommonDivisorForPair(a: Int?, _ b: Int?) -> Int { switch (a, b) { case (.None, .None): return 0 case (let a, .Some(0)): return a! default: return greatestCommonDivisorForPair(b!, a! % b!) } } } }
mit
c57eef703f7b8209f44e7d790a47bd40
34.705263
110
0.612028
4.777465
false
true
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Mapping/MSDashboard+Convertible.swift
1
2341
// // MSDashboard+Convertible.swift // MoyskladNew // // Created by Anton Efimenko on 11.11.16. // Copyright © 2016 Andrey Parshakov. All rights reserved. // import Foundation //import Money extension MSDashboard { public static func from(dict: Dictionary<String, Any>) -> MSDashboard? { guard let money = MSDashboardMoney.from(dict: dict.msValue("money")), let sales = MSDashboardSales.from(dict: dict.msValue("sales")), let orders = MSDashboardOrders.from(dict: dict.msValue("orders")) else { return nil } return MSDashboard(sales: sales, orders: orders, money: money) } } extension MSDashboardMoney { public static func from(dict: Dictionary<String, Any>) -> MSDashboardMoney? { guard let income: Double = dict.value("income"), let outcome: Double = dict.value("outcome"), let balance: Double = dict.value("balance"), let todayMovement: Double = dict.value("todayMovement"), let movement: Double = dict.value("movement") else { return nil } return MSDashboardMoney(income: income.toMoney(), outcome: outcome.toMoney(), balance: balance.toMoney(), todayMovement: todayMovement.toMoney(), movement: movement.toMoney()) } } extension MSDashboardOrders { public static func from(dict: Dictionary<String, Any>) -> MSDashboardOrders? { guard let count: Int = dict.value("count"), let amount: Double = dict.value("amount"), let movementAmount: Double = dict.value("movementAmount") else { return nil } return MSDashboardOrders(count: count, amount: amount.toMoney(), movementAmount: movementAmount.toMoney()) } } extension MSDashboardSales { public static func from(dict: Dictionary<String, Any>) -> MSDashboardSales? { guard let count: Int = dict.value("count"), let amount: Double = dict.value("amount"), let movementAmount: Double = dict.value("movementAmount") else { return nil } return MSDashboardSales(count: count, amount: amount.toMoney(), movementAmount: movementAmount.toMoney()) } }
mit
852ae05008523f65b75a1f4efb7b17b8
37.360656
115
0.607692
4.804928
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/Command.swift
2
1125
// // Command.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import Foundation /// An `Command` associates a command with the actor that can perform that command. public struct Command { unowned let performer: Performer let action: Action init(performer: Performer, action: Action) { self.performer = performer self.action = action } // MARK: func applyStateChange(inReverse reversed: Bool = false) { let directionalCommand = reversed ? action.reversed : action performer.applyStateChange(for: directionalCommand) } /// Convenience to run the `action` against the `performer`. func perform() { performer.perform(action) } func cancel() { performer.cancel(action) } } extension Command: CustomDebugStringConvertible { public var debugDescription: String { return "\(performer.dynamicType): \(action)" } } extension Command: Equatable {} public func ==(lhs: Command, rhs: Command) -> Bool { return lhs.action == rhs.action && lhs.performer === rhs.performer }
mit
392e8db2a96269bfbc9d9c8e0cb0569a
24
83
0.650667
4.518072
false
false
false
false
etiennemartin/jugglez
Jugglez/IntroScene.swift
1
6547
// // GameScene.swift // JuggleGame // // Created by Etienne Martin on 2015-01-17. // Copyright (c) 2015 Etienne Martin. All rights reserved. // import SpriteKit public enum GameMode: CustomStringConvertible { case None case Easy case Medium case Hard case Expert case HighScore public var description: String { switch self { case .None: return "None" case .Easy: return "Easy" case .Medium: return "Medium" case .Hard: return "Hard" case .Expert: return "Expert" case .HighScore: return "High scores" } } // Static set of all modes. Useful for enumerating public static let allModes = [Easy, Medium, Hard, Expert] } struct GameModeButton { var mode: GameMode var node: Button } class IntroScene: SKScene { private var _buttonTapSoundAction = SKAction.playSoundFileNamed("BallTap.wav", waitForCompletion: false) private var _gitHubRepoUrl: String = "https://github.com/etiennemartin/jugglez" private var _gitHubNode: SKSpriteNode? private var _buttons: [GameModeButton] = [] override init(size: CGSize) { super.init(size: size) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { backgroundColor = SKColor.themeDarkBackgroundColor() // Title Bg let bgHeight = self.size.height * 0.25 let titleBg = SKShapeNode(rect: CGRect(x: 0, y: self.size.height - bgHeight, width: self.size.width, height: bgHeight)) titleBg.fillColor = SKColor.themeLightBackgroundColor() addChild(titleBg) // Title Label let endPosition = CGPoint(x: self.size.width / 2, y: self.size.height * 0.75 + 20) let startPosition = CGPoint(x: self.size.width / 2, y: self.size.height + 75) let label = SKLabelNode(text: "Jugglez") label.fontName = SKLabelNode.defaultFontName() label.fontSize = 80 label.fontColor = SKColor.themeDarkFontColor() label.position = startPosition addChild(label) // Animate title in let moveAction = SKAction.moveTo(endPosition, duration: 0.75) moveAction.timingMode = SKActionTimingMode.EaseOut label.runAction(moveAction) // Buttons let position = self.size.height * 0.75 let gap = min( ((self.size.height * 0.75) / 5) - 10, 75) let xOffset = self.size.width / 6 addButtonWithLabel(GameMode.Easy, position: CGPoint(x: xOffset, y: position - gap)) addButtonWithLabel(GameMode.Medium, position: CGPoint(x: xOffset, y: position - (gap * 2))) addButtonWithLabel(GameMode.Hard, position: CGPoint(x: xOffset, y: position - (gap * 3))) addButtonWithLabel(GameMode.Expert, position: CGPoint(x: xOffset, y: position - (gap * 4))) addButtonWithLabel(GameMode.HighScore, position: CGPoint(x: xOffset, y: position - (gap * 5))) // Version let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] let versionLabel = SKLabelNode(fontNamed: SKLabelNode.defaultFontName()) versionLabel.text = "\(version!) (\(build!))" versionLabel.fontColor = SKColor.themeDarkFontColor().colorWithAlphaComponent(0.8) versionLabel.fontSize = 16 versionLabel.position = CGPoint(x: versionLabel.frame.size.width / 2 + 5, y: 5) addChild(versionLabel) // Add Git hub icon self.addGitHubLink() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! let location = touch.locationInNode(self) // Detect touch with buttons for button in _buttons { let buttonRect: CGRect = button.node.calculateAccumulatedFrame() if (CGRectContainsPoint(buttonRect, location)) { let reveal = SKTransition.fadeWithColor(backgroundColor, duration: 0.75) button.node.foregroundColor = SKColor.colorForGameMode(button.mode).colorWithAlphaComponent(0.25) self.runAction(_buttonTapSoundAction) if button.mode == GameMode.HighScore { // Present high score scene let scene = HighScoreScene(size: self.size) scene.scaleMode = .ResizeFill self.view?.presentScene(scene, transition:reveal) } else { // Present game scene let scene = GamePlayScene(size: self.size) scene.scaleMode = .ResizeFill scene.mode = button.mode self.view?.presentScene(scene, transition:reveal) } break } } // Detect touch with gitHub icon let gitHubRect: CGRect = _gitHubNode!.calculateAccumulatedFrame() if (CGRectContainsPoint(gitHubRect, location)) { let url = NSURL(string: _gitHubRepoUrl) UIApplication.sharedApplication().openURL(url!) } } override func update(currentTime: CFTimeInterval) { super.update(currentTime) } func addButtonWithLabel(mode: GameMode, position: CGPoint) { let nodeButton: Button = Button(frame: CGRect(x: 0, y: 0, width: self.size.width * 0.67, height: 50), text: mode.description) nodeButton.position = position nodeButton.position.y = -75 nodeButton.foregroundColor = SKColor.colorForGameMode(mode) nodeButton.textColor = SKColor.themeButtonTextColor() addChild(nodeButton) // Animate button in let moveAction = SKAction.moveTo(position, duration: 0.75) moveAction.timingMode = SKActionTimingMode.EaseOut nodeButton.runAction(moveAction) let modeButton = GameModeButton(mode: mode, node: nodeButton) _buttons.append(modeButton) } func addGitHubLink() { let dim: CGFloat = 24.0 _gitHubNode = SKSpriteNode(imageNamed: "GitHub-Mark-120px-plus") _gitHubNode?.size = CGSize(width: dim, height: dim) let startPos = CGPoint(x: self.size.width + dim, y: dim) let endPos = CGPoint(x: self.size.width - dim, y: dim) _gitHubNode?.position = startPos _gitHubNode?.runAction(SKAction.moveTo(endPos, duration: 0.75)) addChild(_gitHubNode!) } }
mit
ccd08598a20ff15efa6362aeeb58dd5b
36.198864
133
0.634031
4.524534
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/NSSet.swift
1
18255
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation open class NSSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFSetGetTypeID()) internal var _storage: Set<NSObject> open var count: Int { guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } return _storage.count } open func member(_ object: Any) -> Any? { guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } let value = __SwiftValue.store(object) guard let idx = _storage.firstIndex(of: value) else { return nil } return _storage[idx] } open func objectEnumerator() -> NSEnumerator { guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } return NSGeneratorEnumerator(_storage.map { __SwiftValue.fetch(nonOptional: $0) }.makeIterator()) } public convenience override init() { self.init(objects: [], count: 0) } public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) { _storage = Set(minimumCapacity: cnt) super.init() let buffer = UnsafeBufferPointer(start: objects, count: cnt) for obj in buffer { _storage.insert(__SwiftValue.store(obj)) } } public convenience init(array: [Any]) { let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: array.count) for (idx, element) in array.enumerated() { buffer.advanced(by: idx).initialize(to: __SwiftValue.store(element)) } self.init(objects: buffer, count: array.count) buffer.deinitialize(count: array.count) buffer.deallocate() } public convenience init(set: Set<AnyHashable>) { self.init(set: set, copyItems: false) } public convenience init(set anSet: NSSet) { self.init(array: anSet.allObjects) } public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) { if flag { self.init(array: set.map { if let item = $0 as? NSObject { return item.copy() } else { return $0 } }) } else { self.init(array: Array(set)) } } public convenience init(object: Any) { self.init(array: [object]) } internal class func _objects(from aDecoder: NSCoder, allowDecodingNonindexedArrayKey: Bool = true) -> [NSObject] { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if (allowDecodingNonindexedArrayKey && type(of: aDecoder) == NSKeyedUnarchiver.self) || aDecoder.containsValue(forKey: "NS.objects") { let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects") return objects as! [NSObject] } else { var objects: [NSObject] = [] var count = 0 var key: String { return "NS.object.\(count)" } while aDecoder.containsValue(forKey: key) { let object = aDecoder.decodeObject(forKey: key) objects.append(object as! NSObject) count += 1 } return objects } } public required convenience init?(coder aDecoder: NSCoder) { self.init(array: NSSet._objects(from: aDecoder)) } open func encode(with aCoder: NSCoder) { // The encoding of a NSSet is identical to the encoding of an NSArray of its contents self.allObjects._nsObject.encode(with: aCoder) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSSet.self { // return self for immutable type return self } else if type(of: self) === NSMutableSet.self { let set = NSSet() set._storage = self._storage return set } return NSSet(array: self.allObjects) } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self { // always create and return an NSMutableSet let mutableSet = NSMutableSet() mutableSet._storage = self._storage return mutableSet } return NSMutableSet(array: self.allObjects) } public static var supportsSecureCoding: Bool { return true } override open var description: String { return description(withLocale: nil) } open func description(withLocale locale: Locale?) -> String { return description(withLocale: locale, indent: 0) } private func description(withLocale locale: Locale?, indent level: Int) -> String { var descriptions = [String]() for obj in self._storage { if let string = obj as? String { descriptions.append(string) } else if let array = obj as? [Any] { descriptions.append(NSArray(array: array).description(withLocale: locale, indent: level + 1)) } else if let dict = obj as? [AnyHashable : Any] { descriptions.append(dict._bridgeToObjectiveC().description(withLocale: locale, indent: level + 1)) } else if let set = obj as? Set<AnyHashable> { descriptions.append(set._bridgeToObjectiveC().description(withLocale: locale, indent: level + 1)) } else { descriptions.append("\(obj)") } } var indent = "" for _ in 0..<level { indent += " " } var result = indent + "{(\n" for idx in 0..<self.count { result += indent + " " + descriptions[idx] if idx + 1 < self.count { result += ",\n" } else { result += "\n" } } result += indent + ")}" return result } override open var _cfTypeID: CFTypeID { return CFSetGetTypeID() } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Set<AnyHashable>: return isEqual(to: other) case let other as NSSet: return isEqual(to: Set._unconditionallyBridgeFromObjectiveC(other)) default: return false } } open override var hash: Int { return self.count } open var allObjects: [Any] { if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self { return _storage.map { __SwiftValue.fetch(nonOptional: $0) } } else { let enumerator = objectEnumerator() var items = [Any]() while let val = enumerator.nextObject() { items.append(val) } return items } } open func anyObject() -> Any? { return objectEnumerator().nextObject() } open func contains(_ anObject: Any) -> Bool { return member(anObject) != nil } open func intersects(_ otherSet: Set<AnyHashable>) -> Bool { if count < otherSet.count { for item in self { if otherSet.contains(item as! AnyHashable) { return true } } return false } else { return otherSet.contains { obj in contains(obj) } } } open func isEqual(to otherSet: Set<AnyHashable>) -> Bool { return count == otherSet.count && isSubset(of: otherSet) } open func isSubset(of otherSet: Set<AnyHashable>) -> Bool { // If self is larger then self cannot be a subset of otherSet if count > otherSet.count { return false } // `true` if we don't contain any object that `otherSet` doesn't contain. for item in self { if !otherSet.contains(item as! AnyHashable) { return false } } return true } open func adding(_ anObject: Any) -> Set<AnyHashable> { return self.addingObjects(from: [anObject]) } open func addingObjects(from other: Set<AnyHashable>) -> Set<AnyHashable> { var result = Set<AnyHashable>(minimumCapacity: Swift.max(count, other.count)) if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self { result.formUnion(_storage.map { __SwiftValue.fetch(nonOptional: $0) as! AnyHashable }) } else { for case let obj as NSObject in self { _ = result.insert(obj) } } return result.union(other) } open func addingObjects(from other: [Any]) -> Set<AnyHashable> { var result = Set<AnyHashable>(minimumCapacity: count) if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self { result.formUnion(_storage.map { __SwiftValue.fetch(nonOptional: $0) as! AnyHashable }) } else { for case let obj as AnyHashable in self { result.insert(obj) } } for case let obj as AnyHashable in other { result.insert(obj) } return result } open func enumerateObjects(_ block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { enumerateObjects(options: [], using: block) } open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { var stop : ObjCBool = false for obj in self { withUnsafeMutablePointer(to: &stop) { stop in block(obj, stop) } if stop.boolValue { break } } } open func objects(passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { return objects(options: [], passingTest: predicate) } open func objects(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { var result = Set<AnyHashable>() enumerateObjects(options: opts) { obj, stopp in if predicate(obj, stopp) { result.insert(obj as! AnyHashable) } } return result } open func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any] { return allObjects._nsObject.sortedArray(using: sortDescriptors) } } extension NSSet : _CFBridgeable, _SwiftBridgeable { internal var _cfObject: CFSet { return unsafeBitCast(self, to: CFSet.self) } internal var _swiftObject: Set<NSObject> { return Set._unconditionallyBridgeFromObjectiveC(self) } } extension CFSet : _NSBridgeable, _SwiftBridgeable { internal var _nsObject: NSSet { return unsafeBitCast(self, to: NSSet.self) } internal var _swiftObject: Set<NSObject> { return _nsObject._swiftObject } } extension NSMutableSet { internal var _cfMutableObject: CFMutableSet { return unsafeBitCast(self, to: CFMutableSet.self) } } extension Set : _NSBridgeable, _CFBridgeable { internal var _nsObject: NSSet { return _bridgeToObjectiveC() } internal var _cfObject: CFSet { return _nsObject._cfObject } } extension NSSet : Sequence { public typealias Iterator = NSEnumerator.Iterator public func makeIterator() -> Iterator { return self.objectEnumerator().makeIterator() } } extension NSSet: CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self._storage) } } open class NSMutableSet : NSSet { open func add(_ object: Any) { guard type(of: self) === NSMutableSet.self else { NSRequiresConcreteImplementation() } _storage.insert(__SwiftValue.store(object)) } open func remove(_ object: Any) { guard type(of: self) === NSMutableSet.self else { NSRequiresConcreteImplementation() } _storage.remove(__SwiftValue.store(object)) } override public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) { super.init(objects: objects, count: cnt) } public convenience init() { self.init(capacity: 0) } public required init(capacity numItems: Int) { super.init(objects: [], count: 0) } public required convenience init?(coder aDecoder: NSCoder) { self.init(array: NSSet._objects(from: aDecoder)) } open func addObjects(from array: [Any]) { if type(of: self) === NSMutableSet.self { for case let obj in array { _storage.insert(__SwiftValue.store(obj)) } } else { array.forEach(add) } } open func intersect(_ otherSet: Set<AnyHashable>) { if type(of: self) === NSMutableSet.self { _storage.formIntersection(otherSet.map { __SwiftValue.store($0) }) } else { for obj in self { if !otherSet.contains(obj as! AnyHashable) { remove(obj) } } } } open func minus(_ otherSet: Set<AnyHashable>) { if type(of: self) === NSMutableSet.self { _storage.subtract(otherSet.map { __SwiftValue.store($0) }) } else { otherSet.forEach(remove) } } open func removeAllObjects() { if type(of: self) === NSMutableSet.self { _storage.removeAll() } else { forEach(remove) } } open func union(_ otherSet: Set<AnyHashable>) { if type(of: self) === NSMutableSet.self { _storage.formUnion(otherSet.map { __SwiftValue.store($0) }) } else { otherSet.forEach(add) } } open func setSet(_ otherSet: Set<AnyHashable>) { if type(of: self) === NSMutableSet.self { _storage = Set(otherSet.map { __SwiftValue.store($0) }) } else { removeAllObjects() union(otherSet) } } } /**************** Counted Set ****************/ open class NSCountedSet : NSMutableSet { internal var _table: Dictionary<NSObject, Int> public required init(capacity numItems: Int) { _table = Dictionary<NSObject, Int>() super.init(capacity: numItems) } public convenience init() { self.init(capacity: 0) } public convenience init(array: [Any]) { self.init(capacity: array.count) for object in array { let value = __SwiftValue.store(object) if let count = _table[value] { _table[value] = count + 1 } else { _table[value] = 1 _storage.insert(value) } } } public convenience init(set: Set<AnyHashable>) { self.init(array: Array(set)) } public required convenience init?(coder: NSCoder) { NSUnimplemented() } open override func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSCountedSet.self { let countedSet = NSCountedSet() countedSet._storage = self._storage countedSet._table = self._table return countedSet } return NSCountedSet(array: self.allObjects) } open override func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSCountedSet.self { let countedSet = NSCountedSet() countedSet._storage = self._storage countedSet._table = self._table return countedSet } return NSCountedSet(array: self.allObjects) } open func count(for object: Any) -> Int { guard type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } let value = __SwiftValue.store(object) guard let count = _table[value] else { return 0 } return count } open override func add(_ object: Any) { guard type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } let value = __SwiftValue.store(object) if let count = _table[value] { _table[value] = count + 1 } else { _table[value] = 1 _storage.insert(value) } } open override func remove(_ object: Any) { guard type(of: self) === NSCountedSet.self else { NSRequiresConcreteImplementation() } let value = __SwiftValue.store(object) guard let count = _table[value] else { return } if count > 1 { _table[value] = count - 1 } else { _table[value] = nil _storage.remove(value) } } open override func removeAllObjects() { if type(of: self) === NSCountedSet.self { _storage.removeAll() _table.removeAll() } else { forEach(remove) } } } extension NSSet : _StructTypeBridgeable { public typealias _StructType = Set<AnyHashable> public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
apache-2.0
eca42c4910882a82faf2a105ffb78ad8
31.482206
154
0.567625
4.687982
false
false
false
false
slabgorb/Tiler
Tiler/MapViewController.swift
1
5695
// // MapViewController.swift // Tiler // // Created by Keith Avery on 3/3/16. // Copyright © 2016 Keith Avery. All rights reserved. // import UIKit import PKHUD class MapViewController: UIViewController { // MARK: Properties @IBOutlet var mapView: MapView! var textInputViewController: TextInputViewController? var map:Map? = Map(title: "Untitled") var mapIndex: Int = 0 var mapList:MapList? override func viewDidLoad() { super.viewDidLoad() let mapList = loadMaps() map = mapList?.get(mapIndex) navigationItem.title = map?.title } // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // mapView.reloadData() // // // } // func addTile(tile: Tile, _ row: Int, _ column: Int) { // let added:Either<String,Bool> = self.mapView.addTileView(TileView(tile: tile)) // switch added { // case .Left(let errorText): // HUD.flash(HUDContentType.LabeledError(title: "Error Adding Tile", subtitle: errorText), delay: 1.0) // case .Right(_): // print("added tile") // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func unwindToList(segue: UIStoryboardSegue) { } @IBAction func renameMap(sender: AnyObject?) { removeTextInputViewController() self.textInputViewController = TextInputViewController() if let textInputViewController = self.textInputViewController { textInputViewController.delegate = self self.addChildViewController(textInputViewController) self.view.addSubview(textInputViewController.view) } } func saveMap() { mapList = loadMaps() if let map = map, mapList = mapList { mapList[mapIndex] = map saveMaps() } mapView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "expandTileSegueId": if let navigationController = segue.destinationViewController as? UINavigationController { if let viewController = navigationController.topViewController as? TileCustomizationViewController { if let currentSelection = mapView.indexPathsForSelectedItems()?.first { if let tile = map?.tiles[currentSelection.row] { viewController.mapDelegate = self viewController.tile = tile } } } } case "newTileSegueId": if let navigationController = segue.destinationViewController as? UINavigationController { if let viewController = navigationController.topViewController as? TileCustomizationViewController { viewController.mapDelegate = self viewController.tile = nil } } default: break } } } } // MARK:- UICollectionViewDelegate extension MapViewController: UICollectionViewDelegate { } extension MapViewController: MapDelegate { func add(tile: Tile) { do { try map!.add(tile) } catch let error as NSError { print(error.description) } } } // MARK:- UICollectionViewDataSource extension MapViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { var count:Int = 0 if let maxRow = map?.maxRow() { count = maxRow + 1 } return count } func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var count:Int = 0 if let map = self.map { count = map.maxColumnInRow(section) + 1 } return count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("TileCellId", forIndexPath: indexPath) as! TileViewCell if let map = self.map { let tileRow = map.tilesInRow(indexPath.section) if tileRow.count > 0 { let tile = tileRow[indexPath.row] let tileView = TileView(tile:tile) cell.tileView = tileView } cell.label = UILabel() cell.label?.text = "\(indexPath.section):\(indexPath.row)" } return cell } } // MARK:- MapPersistence extension MapViewController: MapPersistence { } // MARK:- TextInputViewControllerDelegate extension MapViewController: TextInputViewControllerDelegate { func textInputViewControllerCancelButtonTapped(viewController: TextInputViewController) { removeTextInputViewController() } func textInputViewController(viewController: TextInputViewController, saveButtonTappedWithText text:String) { if let map = map { map.title = text saveMap() navigationItem.title = map.title } removeTextInputViewController() } }
mit
491e0ca2c06d976c172fb755c82c3070
28.502591
130
0.60836
5.438395
false
false
false
false
chengxianghe/MissGe
MissGe/Pods/KeychainAccess/Lib/KeychainAccess/Keychain.swift
2
115990
// // Keychain.swift // KeychainAccess // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security #if os(iOS) || os(OSX) import LocalAuthentication #endif public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" public enum ItemClass { case genericPassword case internetPassword } public enum ProtocolType { case ftp case ftpAccount case http case irc case nntp case pop3 case smtp case socks case imap case ldap case appleTalk case afp case telnet case ssh case ftps case https case httpProxy case httpsProxy case ftpProxy case smb case rtsp case rtspProxy case daap case eppc case ipp case nntps case ldaps case telnetS case imaps case ircs case pop3S } public enum AuthenticationType { case ntlm case msn case dpa case rpa case httpBasic case httpDigest case htmlForm case `default` } public enum Accessibility { /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will migrate to a new device when using encrypted backups. */ case whenUnlocked /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accesible by background applications. Items with this attribute will migrate to a new device when using encrypted backups. */ case afterFirstUnlock /** Item data can always be accessed regardless of the lock state of the device. This is not recommended for anything except system use. Items with this attribute will migrate to a new device when using encrypted backups. */ case always /** Item data can only be accessed while the device is unlocked. This class is only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode will cause all items in this class to be deleted. */ @available(iOS 8.0, OSX 10.10, *) case whenPasscodeSetThisDeviceOnly /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case whenUnlockedThisDeviceOnly /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accessible by background applications. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device these items will be missing. */ case afterFirstUnlockThisDeviceOnly /** Item data can always be accessed regardless of the lock state of the device. This option is not recommended for anything except system use. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case alwaysThisDeviceOnly } public struct AuthenticationPolicy: OptionSet { /** User presence policy using Touch ID or Passcode. Touch ID does not have to be available or enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0) /** Constraint: Touch ID (any finger). Touch ID must be available and at least one finger must be enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1) /** Constraint: Touch ID from the set of currently enrolled fingers. Touch ID must be available and at least one finger must be enrolled. When fingers are added or removed, the item is invalidated. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3) /** Constraint: Device passcode */ @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4) /** Constraint logic operation: when using more than one constraint, at least one of them must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let or = AuthenticationPolicy(rawValue: 1 << 14) /** Constraint logic operation: when using more than one constraint, all must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let and = AuthenticationPolicy(rawValue: 1 << 15) /** Create access control for private key operations (i.e. sign operation) */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30) /** Security: Application provided password for data encryption key generation. This is not a constraint but additional item encryption mechanism. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31) #if swift(>=2.3) public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } #else public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } #endif } public struct Attributes { public var `class`: String? { return attributes[Class] as? String } public var data: Data? { return attributes[ValueData] as? Data } public var ref: Data? { return attributes[ValueRef] as? Data } public var persistentRef: Data? { return attributes[ValuePersistentRef] as? Data } public var accessible: String? { return attributes[AttributeAccessible] as? String } public var accessControl: SecAccessControl? { if #available(OSX 10.10, *) { if let accessControl = attributes[AttributeAccessControl] { return (accessControl as! SecAccessControl) } return nil } else { return nil } } public var accessGroup: String? { return attributes[AttributeAccessGroup] as? String } public var synchronizable: Bool? { return attributes[AttributeSynchronizable] as? Bool } public var creationDate: Date? { return attributes[AttributeCreationDate] as? Date } public var modificationDate: Date? { return attributes[AttributeModificationDate] as? Date } public var attributeDescription: String? { return attributes[AttributeDescription] as? String } public var comment: String? { return attributes[AttributeComment] as? String } public var creator: String? { return attributes[AttributeCreator] as? String } public var type: String? { return attributes[AttributeType] as? String } public var label: String? { return attributes[AttributeLabel] as? String } public var isInvisible: Bool? { return attributes[AttributeIsInvisible] as? Bool } public var isNegative: Bool? { return attributes[AttributeIsNegative] as? Bool } public var account: String? { return attributes[AttributeAccount] as? String } public var service: String? { return attributes[AttributeService] as? String } public var generic: Data? { return attributes[AttributeGeneric] as? Data } public var securityDomain: String? { return attributes[AttributeSecurityDomain] as? String } public var server: String? { return attributes[AttributeServer] as? String } public var `protocol`: String? { return attributes[AttributeProtocol] as? String } public var authenticationType: String? { return attributes[AttributeAuthenticationType] as? String } public var port: Int? { return attributes[AttributePort] as? Int } public var path: String? { return attributes[AttributePath] as? String } fileprivate let attributes: [String: Any] init(attributes: [String: Any]) { self.attributes = attributes } public subscript(key: String) -> Any? { get { return attributes[key] } } } public final class Keychain { public var itemClass: ItemClass { return options.itemClass } public var service: String { return options.service } public var accessGroup: String? { return options.accessGroup } public var server: URL { return options.server } public var protocolType: ProtocolType { return options.protocolType } public var authenticationType: AuthenticationType { return options.authenticationType } public var accessibility: Accessibility { return options.accessibility } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public var authenticationPolicy: AuthenticationPolicy? { return options.authenticationPolicy } public var synchronizable: Bool { return options.synchronizable } public var label: String? { return options.label } public var comment: String? { return options.comment } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public var authenticationPrompt: String? { return options.authenticationPrompt } #if os(iOS) || os(OSX) @available(iOS 9.0, OSX 10.11, *) public var authenticationContext: LAContext? { return options.authenticationContext as? LAContext } #endif fileprivate let options: Options // MARK: public convenience init() { var options = Options() if let bundleIdentifier = Bundle.main.bundleIdentifier { options.service = bundleIdentifier } self.init(options) } public convenience init(service: String) { var options = Options() options.service = service self.init(options) } public convenience init(accessGroup: String) { var options = Options() if let bundleIdentifier = Bundle.main.bundleIdentifier { options.service = bundleIdentifier } options.accessGroup = accessGroup self.init(options) } public convenience init(service: String, accessGroup: String) { var options = Options() options.service = service options.accessGroup = accessGroup self.init(options) } public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) { self.init(server: URL(string: server)!, protocolType: protocolType, authenticationType: authenticationType) } public convenience init(server: URL, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) { var options = Options() options.itemClass = .internetPassword options.server = server options.protocolType = protocolType options.authenticationType = authenticationType self.init(options) } fileprivate init(_ opts: Options) { options = opts } // MARK: public func accessibility(_ accessibility: Accessibility) -> Keychain { var options = self.options options.accessibility = accessibility return Keychain(options) } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public func accessibility(_ accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain { var options = self.options options.accessibility = accessibility options.authenticationPolicy = authenticationPolicy return Keychain(options) } public func synchronizable(_ synchronizable: Bool) -> Keychain { var options = self.options options.synchronizable = synchronizable return Keychain(options) } public func label(_ label: String) -> Keychain { var options = self.options options.label = label return Keychain(options) } public func comment(_ comment: String) -> Keychain { var options = self.options options.comment = comment return Keychain(options) } public func attributes(_ attributes: [String: Any]) -> Keychain { var options = self.options attributes.forEach { options.attributes.updateValue($1, forKey: $0) } return Keychain(options) } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public func authenticationPrompt(_ authenticationPrompt: String) -> Keychain { var options = self.options options.authenticationPrompt = authenticationPrompt return Keychain(options) } #if os(iOS) || os(OSX) @available(iOS 9.0, OSX 10.11, *) public func authenticationContext(_ authenticationContext: LAContext) -> Keychain { var options = self.options options.authenticationContext = authenticationContext return Keychain(options) } #endif // MARK: public func get(_ key: String) throws -> String? { return try getString(key) } public func getString(_ key: String) throws -> String? { guard let data = try getData(key) else { return nil } guard let string = String(data: data, encoding: .utf8) else { print("failed to convert data to string") throw Status.conversionError } return string } public func getData(_ key: String) throws -> Data? { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = kCFBooleanTrue query[AttributeAccount] = key var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: guard let data = result as? Data else { throw Status.unexpectedError } return data case errSecItemNotFound: return nil default: throw securityError(status: status) } } public func get<T>(_ key: String, handler: (Attributes?) -> T) throws -> T { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = kCFBooleanTrue query[ReturnAttributes] = kCFBooleanTrue query[ReturnRef] = kCFBooleanTrue query[ReturnPersistentRef] = kCFBooleanTrue query[AttributeAccount] = key var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: guard let attributes = result as? [String: Any] else { throw Status.unexpectedError } return handler(Attributes(attributes: attributes)) case errSecItemNotFound: return handler(nil) default: throw securityError(status: status) } } // MARK: public func set(_ value: String, key: String) throws { guard let data = value.data(using: .utf8, allowLossyConversion: false) else { print("failed to convert string to data") throw Status.conversionError } try set(data, key: key) } public func set(_ value: Data, key: String) throws { var query = options.query() query[AttributeAccount] = key #if os(iOS) if #available(iOS 9.0, *) { query[UseAuthenticationUI] = UseAuthenticationUIFail } else { query[UseNoAuthenticationUI] = kCFBooleanTrue } #elseif os(OSX) query[ReturnData] = kCFBooleanTrue if #available(OSX 10.11, *) { query[UseAuthenticationUI] = UseAuthenticationUIFail } #endif var status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecSuccess, errSecInteractionNotAllowed: var query = options.query() query[AttributeAccount] = key var (attributes, error) = options.attributes(key: nil, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } #if os(iOS) if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { try remove(key) try set(value, key: key) } else { status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) if status != errSecSuccess { throw securityError(status: status) } } #else status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) if status != errSecSuccess { throw securityError(status: status) } #endif case errSecItemNotFound: var (attributes, error) = options.attributes(key: key, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } status = SecItemAdd(attributes as CFDictionary, nil) if status != errSecSuccess { throw securityError(status: status) } default: throw securityError(status: status) } } public subscript(key: String) -> String? { get { return (try? get(key)).flatMap { $0 } } set { if let value = newValue { do { try set(value, key: key) } catch {} } else { do { try remove(key) } catch {} } } } public subscript(string key: String) -> String? { get { return self[key] } set { self[key] = newValue } } public subscript(data key: String) -> Data? { get { return (try? getData(key)).flatMap { $0 } } set { if let value = newValue { do { try set(value, key: key) } catch {} } else { do { try remove(key) } catch {} } } } public subscript(attributes key: String) -> Attributes? { get { return (try? get(key) { $0 }).flatMap { $0 } } } // MARK: public func remove(_ key: String) throws { var query = options.query() query[AttributeAccount] = key let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess && status != errSecItemNotFound { throw securityError(status: status) } } public func removeAll() throws { var query = options.query() #if !os(iOS) && !os(watchOS) && !os(tvOS) query[MatchLimit] = MatchLimitAll #endif let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess && status != errSecItemNotFound { throw securityError(status: status) } } // MARK: public func contains(_ key: String) throws -> Bool { var query = options.query() query[AttributeAccount] = key let status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecSuccess: return true case errSecItemNotFound: return false default: throw securityError(status: status) } } // MARK: public class func allKeys(_ itemClass: ItemClass) -> [(String, String)] { var query = [String: Any]() query[Class] = itemClass.rawValue query[AttributeSynchronizable] = SynchronizableAny query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = kCFBooleanTrue var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: if let items = result as? [[String: Any]] { return prettify(itemClass: itemClass, items: items).map { switch itemClass { case .genericPassword: return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String) case .internetPassword: return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String) } } } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allKeys() -> [String] { let allItems = type(of: self).prettify(itemClass: itemClass, items: items()) let filter: ([String: Any]) -> String? = { $0["key"] as? String } #if swift(>=4.1) return allItems.compactMap(filter) #else return allItems.flatMap(filter) #endif } public class func allItems(_ itemClass: ItemClass) -> [[String: Any]] { var query = [String: Any]() query[Class] = itemClass.rawValue query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = kCFBooleanTrue #if os(iOS) || os(watchOS) || os(tvOS) query[ReturnData] = kCFBooleanTrue #endif var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: if let items = result as? [[String: Any]] { return prettify(itemClass: itemClass, items: items) } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allItems() -> [[String: Any]] { return type(of: self).prettify(itemClass: itemClass, items: items()) } #if os(iOS) @available(iOS 8.0, *) public func getSharedPassword(_ completion: @escaping (_ account: String?, _ password: String?, _ error: Error?) -> () = { account, password, error -> () in }) { if let domain = server.host { type(of: self).requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in if let credential = credentials.first { let account = credential["account"] let password = credential["password"] completion(account, password, error) } else { completion(nil, nil, error) } } } else { let error = securityError(status: Status.param.rawValue) completion(nil, nil, error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func getSharedPassword(_ account: String, completion: @escaping (_ password: String?, _ error: Error?) -> () = { password, error -> () in }) { if let domain = server.host { type(of: self).requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in if let credential = credentials.first { if let password = credential["password"] { completion(password, error) } else { completion(nil, error) } } else { completion(nil, error) } } } else { let error = securityError(status: Status.param.rawValue) completion(nil, error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func setSharedPassword(_ password: String, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { setSharedPassword(password as String?, account: account, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) fileprivate func setSharedPassword(_ password: String?, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { if let domain = server.host { SecAddSharedWebCredential(domain as CFString, account as CFString, password as CFString?) { error -> () in if let error = error { completion(error.error) } else { completion(nil) } } } else { let error = securityError(status: Status.param.rawValue) completion(error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func removeSharedPassword(_ account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) { setSharedPassword(nil, account: account, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(_ completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: nil, account: nil, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(domain: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain, account: nil, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(domain: String, account: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: Optional(domain), account: Optional(account)!, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) fileprivate class func requestSharedWebCredential(domain: String?, account: String?, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> ()) { SecRequestSharedWebCredential(domain as CFString?, account as CFString?) { (credentials, error) -> () in var remoteError: NSError? if let error = error { remoteError = error.error if remoteError?.code != Int(errSecItemNotFound) { print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)") } } if let credentials = credentials { let credentials = (credentials as NSArray).map { credentials -> [String: String] in var credential = [String: String]() if let credentials = credentials as? [String: String] { if let server = credentials[AttributeServer] { credential["server"] = server } if let account = credentials[AttributeAccount] { credential["account"] = account } if let password = credentials[SharedPassword] { credential["password"] = password } } return credential } completion(credentials, remoteError) } else { completion([], remoteError) } } } #endif #if os(iOS) /** @abstract Returns a randomly generated password. @return String password in the form xxx-xxx-xxx-xxx where x is taken from the sets "abcdefghkmnopqrstuvwxy", "ABCDEFGHJKLMNPQRSTUVWXYZ", "3456789" with at least one character from each set being present. */ @available(iOS 8.0, *) public class func generatePassword() -> String { return SecCreateSharedWebCredentialPassword()! as String } #endif // MARK: fileprivate func items() -> [[String: Any]] { var query = options.query() query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = kCFBooleanTrue #if os(iOS) || os(watchOS) || os(tvOS) query[ReturnData] = kCFBooleanTrue #endif var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: if let items = result as? [[String: Any]] { return items } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } fileprivate class func prettify(itemClass: ItemClass, items: [[String: Any]]) -> [[String: Any]] { let items = items.map { attributes -> [String: Any] in var item = [String: Any]() item["class"] = itemClass.description switch itemClass { case .genericPassword: if let service = attributes[AttributeService] as? String { item["service"] = service } if let accessGroup = attributes[AttributeAccessGroup] as? String { item["accessGroup"] = accessGroup } case .internetPassword: if let server = attributes[AttributeServer] as? String { item["server"] = server } if let proto = attributes[AttributeProtocol] as? String { if let protocolType = ProtocolType(rawValue: proto) { item["protocol"] = protocolType.description } } if let auth = attributes[AttributeAuthenticationType] as? String { if let authenticationType = AuthenticationType(rawValue: auth) { item["authenticationType"] = authenticationType.description } } } if let key = attributes[AttributeAccount] as? String { item["key"] = key } if let data = attributes[ValueData] as? Data { if let text = String(data: data, encoding: .utf8) { item["value"] = text } else { item["value"] = data } } if let accessible = attributes[AttributeAccessible] as? String { if let accessibility = Accessibility(rawValue: accessible) { item["accessibility"] = accessibility.description } } if let synchronizable = attributes[AttributeSynchronizable] as? Bool { item["synchronizable"] = synchronizable ? "true" : "false" } return item } return items } // MARK: @discardableResult fileprivate class func securityError(status: OSStatus) -> Error { let error = Status(status: status) print("OSStatus error:[\(error.errorCode)] \(error.description)") return error } @discardableResult fileprivate func securityError(status: OSStatus) -> Error { return type(of: self).securityError(status: status) } } struct Options { var itemClass: ItemClass = .genericPassword var service: String = "" var accessGroup: String? = nil var server: URL! var protocolType: ProtocolType! var authenticationType: AuthenticationType = .default var accessibility: Accessibility = .afterFirstUnlock var authenticationPolicy: AuthenticationPolicy? var synchronizable: Bool = false var label: String? var comment: String? var authenticationPrompt: String? var authenticationContext: AnyObject? var attributes = [String: Any]() } /** Class Key Constant */ private let Class = String(kSecClass) /** Attribute Key Constants */ private let AttributeAccessible = String(kSecAttrAccessible) @available(iOS 8.0, OSX 10.10, *) private let AttributeAccessControl = String(kSecAttrAccessControl) private let AttributeAccessGroup = String(kSecAttrAccessGroup) private let AttributeSynchronizable = String(kSecAttrSynchronizable) private let AttributeCreationDate = String(kSecAttrCreationDate) private let AttributeModificationDate = String(kSecAttrModificationDate) private let AttributeDescription = String(kSecAttrDescription) private let AttributeComment = String(kSecAttrComment) private let AttributeCreator = String(kSecAttrCreator) private let AttributeType = String(kSecAttrType) private let AttributeLabel = String(kSecAttrLabel) private let AttributeIsInvisible = String(kSecAttrIsInvisible) private let AttributeIsNegative = String(kSecAttrIsNegative) private let AttributeAccount = String(kSecAttrAccount) private let AttributeService = String(kSecAttrService) private let AttributeGeneric = String(kSecAttrGeneric) private let AttributeSecurityDomain = String(kSecAttrSecurityDomain) private let AttributeServer = String(kSecAttrServer) private let AttributeProtocol = String(kSecAttrProtocol) private let AttributeAuthenticationType = String(kSecAttrAuthenticationType) private let AttributePort = String(kSecAttrPort) private let AttributePath = String(kSecAttrPath) private let SynchronizableAny = kSecAttrSynchronizableAny /** Search Constants */ private let MatchLimit = String(kSecMatchLimit) private let MatchLimitOne = kSecMatchLimitOne private let MatchLimitAll = kSecMatchLimitAll /** Return Type Key Constants */ private let ReturnData = String(kSecReturnData) private let ReturnAttributes = String(kSecReturnAttributes) private let ReturnRef = String(kSecReturnRef) private let ReturnPersistentRef = String(kSecReturnPersistentRef) /** Value Type Key Constants */ private let ValueData = String(kSecValueData) private let ValueRef = String(kSecValueRef) private let ValuePersistentRef = String(kSecValuePersistentRef) /** Other Constants */ @available(iOS 8.0, OSX 10.10, *) private let UseOperationPrompt = String(kSecUseOperationPrompt) #if os(iOS) @available(iOS, introduced: 8.0, deprecated: 9.0, message: "Use a UseAuthenticationUI instead.") private let UseNoAuthenticationUI = String(kSecUseNoAuthenticationUI) #endif @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUI = String(kSecUseAuthenticationUI) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationContext = String(kSecUseAuthenticationContext) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIAllow = String(kSecUseAuthenticationUIAllow) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIFail = String(kSecUseAuthenticationUIFail) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUISkip = String(kSecUseAuthenticationUISkip) #if os(iOS) /** Credential Key Constants */ private let SharedPassword = String(kSecSharedPassword) #endif extension Keychain: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { let items = allItems() if items.isEmpty { return "[]" } var description = "[\n" for item in items { description += " " description += "\(item)\n" } description += "]" return description } public var debugDescription: String { return "\(items())" } } extension Options { func query() -> [String: Any] { var query = [String: Any]() query[Class] = itemClass.rawValue query[AttributeSynchronizable] = SynchronizableAny switch itemClass { case .genericPassword: query[AttributeService] = service // Access group is not supported on any simulators. #if (!arch(i386) && !arch(x86_64)) || (!os(iOS) && !os(watchOS) && !os(tvOS)) if let accessGroup = self.accessGroup { query[AttributeAccessGroup] = accessGroup } #endif case .internetPassword: query[AttributeServer] = server.host query[AttributePort] = server.port query[AttributeProtocol] = protocolType.rawValue query[AttributeAuthenticationType] = authenticationType.rawValue } if #available(OSX 10.10, *) { if authenticationPrompt != nil { query[UseOperationPrompt] = authenticationPrompt } } #if !os(watchOS) if #available(iOS 9.0, OSX 10.11, *) { if authenticationContext != nil { query[UseAuthenticationContext] = authenticationContext } } #endif return query } func attributes(key: String?, value: Data) -> ([String: Any], Error?) { var attributes: [String: Any] if key != nil { attributes = query() attributes[AttributeAccount] = key } else { attributes = [String: Any]() } attributes[ValueData] = value if label != nil { attributes[AttributeLabel] = label } if comment != nil { attributes[AttributeComment] = comment } if let policy = authenticationPolicy { if #available(OSX 10.10, *) { var error: Unmanaged<CFError>? guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue as CFTypeRef, SecAccessControlCreateFlags(rawValue: CFOptionFlags(policy.rawValue)), &error) else { if let error = error?.takeUnretainedValue() { return (attributes, error.error) } return (attributes, Status.unexpectedError) } attributes[AttributeAccessControl] = accessControl } else { print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") } } else { attributes[AttributeAccessible] = accessibility.rawValue } attributes[AttributeSynchronizable] = synchronizable ? kCFBooleanTrue : kCFBooleanFalse return (attributes, nil) } } // MARK: extension Attributes: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(attributes)" } public var debugDescription: String { return description } } extension ItemClass: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecClassGenericPassword): self = .genericPassword case String(kSecClassInternetPassword): self = .internetPassword default: return nil } } public var rawValue: String { switch self { case .genericPassword: return String(kSecClassGenericPassword) case .internetPassword: return String(kSecClassInternetPassword) } } public var description: String { switch self { case .genericPassword: return "GenericPassword" case .internetPassword: return "InternetPassword" } } } extension ProtocolType: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecAttrProtocolFTP): self = .ftp case String(kSecAttrProtocolFTPAccount): self = .ftpAccount case String(kSecAttrProtocolHTTP): self = .http case String(kSecAttrProtocolIRC): self = .irc case String(kSecAttrProtocolNNTP): self = .nntp case String(kSecAttrProtocolPOP3): self = .pop3 case String(kSecAttrProtocolSMTP): self = .smtp case String(kSecAttrProtocolSOCKS): self = .socks case String(kSecAttrProtocolIMAP): self = .imap case String(kSecAttrProtocolLDAP): self = .ldap case String(kSecAttrProtocolAppleTalk): self = .appleTalk case String(kSecAttrProtocolAFP): self = .afp case String(kSecAttrProtocolTelnet): self = .telnet case String(kSecAttrProtocolSSH): self = .ssh case String(kSecAttrProtocolFTPS): self = .ftps case String(kSecAttrProtocolHTTPS): self = .https case String(kSecAttrProtocolHTTPProxy): self = .httpProxy case String(kSecAttrProtocolHTTPSProxy): self = .httpsProxy case String(kSecAttrProtocolFTPProxy): self = .ftpProxy case String(kSecAttrProtocolSMB): self = .smb case String(kSecAttrProtocolRTSP): self = .rtsp case String(kSecAttrProtocolRTSPProxy): self = .rtspProxy case String(kSecAttrProtocolDAAP): self = .daap case String(kSecAttrProtocolEPPC): self = .eppc case String(kSecAttrProtocolIPP): self = .ipp case String(kSecAttrProtocolNNTPS): self = .nntps case String(kSecAttrProtocolLDAPS): self = .ldaps case String(kSecAttrProtocolTelnetS): self = .telnetS case String(kSecAttrProtocolIMAPS): self = .imaps case String(kSecAttrProtocolIRCS): self = .ircs case String(kSecAttrProtocolPOP3S): self = .pop3S default: return nil } } public var rawValue: String { switch self { case .ftp: return String(kSecAttrProtocolFTP) case .ftpAccount: return String(kSecAttrProtocolFTPAccount) case .http: return String(kSecAttrProtocolHTTP) case .irc: return String(kSecAttrProtocolIRC) case .nntp: return String(kSecAttrProtocolNNTP) case .pop3: return String(kSecAttrProtocolPOP3) case .smtp: return String(kSecAttrProtocolSMTP) case .socks: return String(kSecAttrProtocolSOCKS) case .imap: return String(kSecAttrProtocolIMAP) case .ldap: return String(kSecAttrProtocolLDAP) case .appleTalk: return String(kSecAttrProtocolAppleTalk) case .afp: return String(kSecAttrProtocolAFP) case .telnet: return String(kSecAttrProtocolTelnet) case .ssh: return String(kSecAttrProtocolSSH) case .ftps: return String(kSecAttrProtocolFTPS) case .https: return String(kSecAttrProtocolHTTPS) case .httpProxy: return String(kSecAttrProtocolHTTPProxy) case .httpsProxy: return String(kSecAttrProtocolHTTPSProxy) case .ftpProxy: return String(kSecAttrProtocolFTPProxy) case .smb: return String(kSecAttrProtocolSMB) case .rtsp: return String(kSecAttrProtocolRTSP) case .rtspProxy: return String(kSecAttrProtocolRTSPProxy) case .daap: return String(kSecAttrProtocolDAAP) case .eppc: return String(kSecAttrProtocolEPPC) case .ipp: return String(kSecAttrProtocolIPP) case .nntps: return String(kSecAttrProtocolNNTPS) case .ldaps: return String(kSecAttrProtocolLDAPS) case .telnetS: return String(kSecAttrProtocolTelnetS) case .imaps: return String(kSecAttrProtocolIMAPS) case .ircs: return String(kSecAttrProtocolIRCS) case .pop3S: return String(kSecAttrProtocolPOP3S) } } public var description: String { switch self { case .ftp: return "FTP" case .ftpAccount: return "FTPAccount" case .http: return "HTTP" case .irc: return "IRC" case .nntp: return "NNTP" case .pop3: return "POP3" case .smtp: return "SMTP" case .socks: return "SOCKS" case .imap: return "IMAP" case .ldap: return "LDAP" case .appleTalk: return "AppleTalk" case .afp: return "AFP" case .telnet: return "Telnet" case .ssh: return "SSH" case .ftps: return "FTPS" case .https: return "HTTPS" case .httpProxy: return "HTTPProxy" case .httpsProxy: return "HTTPSProxy" case .ftpProxy: return "FTPProxy" case .smb: return "SMB" case .rtsp: return "RTSP" case .rtspProxy: return "RTSPProxy" case .daap: return "DAAP" case .eppc: return "EPPC" case .ipp: return "IPP" case .nntps: return "NNTPS" case .ldaps: return "LDAPS" case .telnetS: return "TelnetS" case .imaps: return "IMAPS" case .ircs: return "IRCS" case .pop3S: return "POP3S" } } } extension AuthenticationType: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecAttrAuthenticationTypeNTLM): self = .ntlm case String(kSecAttrAuthenticationTypeMSN): self = .msn case String(kSecAttrAuthenticationTypeDPA): self = .dpa case String(kSecAttrAuthenticationTypeRPA): self = .rpa case String(kSecAttrAuthenticationTypeHTTPBasic): self = .httpBasic case String(kSecAttrAuthenticationTypeHTTPDigest): self = .httpDigest case String(kSecAttrAuthenticationTypeHTMLForm): self = .htmlForm case String(kSecAttrAuthenticationTypeDefault): self = .`default` default: return nil } } public var rawValue: String { switch self { case .ntlm: return String(kSecAttrAuthenticationTypeNTLM) case .msn: return String(kSecAttrAuthenticationTypeMSN) case .dpa: return String(kSecAttrAuthenticationTypeDPA) case .rpa: return String(kSecAttrAuthenticationTypeRPA) case .httpBasic: return String(kSecAttrAuthenticationTypeHTTPBasic) case .httpDigest: return String(kSecAttrAuthenticationTypeHTTPDigest) case .htmlForm: return String(kSecAttrAuthenticationTypeHTMLForm) case .`default`: return String(kSecAttrAuthenticationTypeDefault) } } public var description: String { switch self { case .ntlm: return "NTLM" case .msn: return "MSN" case .dpa: return "DPA" case .rpa: return "RPA" case .httpBasic: return "HTTPBasic" case .httpDigest: return "HTTPDigest" case .htmlForm: return "HTMLForm" case .`default`: return "Default" } } } extension Accessibility: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { if #available(OSX 10.10, *) { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = .whenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = .afterFirstUnlock case String(kSecAttrAccessibleAlways): self = .always case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly): self = .whenPasscodeSetThisDeviceOnly case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = .whenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = .afterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = .alwaysThisDeviceOnly default: return nil } } else { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = .whenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = .afterFirstUnlock case String(kSecAttrAccessibleAlways): self = .always case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = .whenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = .afterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = .alwaysThisDeviceOnly default: return nil } } } public var rawValue: String { switch self { case .whenUnlocked: return String(kSecAttrAccessibleWhenUnlocked) case .afterFirstUnlock: return String(kSecAttrAccessibleAfterFirstUnlock) case .always: return String(kSecAttrAccessibleAlways) case .whenPasscodeSetThisDeviceOnly: if #available(OSX 10.10, *) { return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) } else { fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.") } case .whenUnlockedThisDeviceOnly: return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) case .afterFirstUnlockThisDeviceOnly: return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) case .alwaysThisDeviceOnly: return String(kSecAttrAccessibleAlwaysThisDeviceOnly) } } public var description: String { switch self { case .whenUnlocked: return "WhenUnlocked" case .afterFirstUnlock: return "AfterFirstUnlock" case .always: return "Always" case .whenPasscodeSetThisDeviceOnly: return "WhenPasscodeSetThisDeviceOnly" case .whenUnlockedThisDeviceOnly: return "WhenUnlockedThisDeviceOnly" case .afterFirstUnlockThisDeviceOnly: return "AfterFirstUnlockThisDeviceOnly" case .alwaysThisDeviceOnly: return "AlwaysThisDeviceOnly" } } } extension CFError { var error: NSError { let domain = CFErrorGetDomain(self) as String let code = CFErrorGetCode(self) let userInfo = CFErrorCopyUserInfo(self) as! [String: Any] return NSError(domain: domain, code: code, userInfo: userInfo) } } public enum Status: OSStatus, Error { case success = 0 case unimplemented = -4 case diskFull = -34 case io = -36 case opWr = -49 case param = -50 case wrPerm = -61 case allocate = -108 case userCanceled = -128 case badReq = -909 case internalComponent = -2070 case notAvailable = -25291 case readOnly = -25292 case authFailed = -25293 case noSuchKeychain = -25294 case invalidKeychain = -25295 case duplicateKeychain = -25296 case duplicateCallback = -25297 case invalidCallback = -25298 case duplicateItem = -25299 case itemNotFound = -25300 case bufferTooSmall = -25301 case dataTooLarge = -25302 case noSuchAttr = -25303 case invalidItemRef = -25304 case invalidSearchRef = -25305 case noSuchClass = -25306 case noDefaultKeychain = -25307 case interactionNotAllowed = -25308 case readOnlyAttr = -25309 case wrongSecVersion = -25310 case keySizeNotAllowed = -25311 case noStorageModule = -25312 case noCertificateModule = -25313 case noPolicyModule = -25314 case interactionRequired = -25315 case dataNotAvailable = -25316 case dataNotModifiable = -25317 case createChainFailed = -25318 case invalidPrefsDomain = -25319 case inDarkWake = -25320 case aclNotSimple = -25240 case policyNotFound = -25241 case invalidTrustSetting = -25242 case noAccessForItem = -25243 case invalidOwnerEdit = -25244 case trustNotAvailable = -25245 case unsupportedFormat = -25256 case unknownFormat = -25257 case keyIsSensitive = -25258 case multiplePrivKeys = -25259 case passphraseRequired = -25260 case invalidPasswordRef = -25261 case invalidTrustSettings = -25262 case noTrustSettings = -25263 case pkcs12VerifyFailure = -25264 case invalidCertificate = -26265 case notSigner = -26267 case policyDenied = -26270 case invalidKey = -26274 case decode = -26275 case `internal` = -26276 case unsupportedAlgorithm = -26268 case unsupportedOperation = -26271 case unsupportedPadding = -26273 case itemInvalidKey = -34000 case itemInvalidKeyType = -34001 case itemInvalidValue = -34002 case itemClassMissing = -34003 case itemMatchUnsupported = -34004 case useItemListUnsupported = -34005 case useKeychainUnsupported = -34006 case useKeychainListUnsupported = -34007 case returnDataUnsupported = -34008 case returnAttributesUnsupported = -34009 case returnRefUnsupported = -34010 case returnPersitentRefUnsupported = -34011 case valueRefUnsupported = -34012 case valuePersistentRefUnsupported = -34013 case returnMissingPointer = -34014 case matchLimitUnsupported = -34015 case itemIllegalQuery = -34016 case waitForCallback = -34017 case missingEntitlement = -34018 case upgradePending = -34019 case mpSignatureInvalid = -25327 case otrTooOld = -25328 case otrIDTooNew = -25329 case serviceNotAvailable = -67585 case insufficientClientID = -67586 case deviceReset = -67587 case deviceFailed = -67588 case appleAddAppACLSubject = -67589 case applePublicKeyIncomplete = -67590 case appleSignatureMismatch = -67591 case appleInvalidKeyStartDate = -67592 case appleInvalidKeyEndDate = -67593 case conversionError = -67594 case appleSSLv2Rollback = -67595 case quotaExceeded = -67596 case fileTooBig = -67597 case invalidDatabaseBlob = -67598 case invalidKeyBlob = -67599 case incompatibleDatabaseBlob = -67600 case incompatibleKeyBlob = -67601 case hostNameMismatch = -67602 case unknownCriticalExtensionFlag = -67603 case noBasicConstraints = -67604 case noBasicConstraintsCA = -67605 case invalidAuthorityKeyID = -67606 case invalidSubjectKeyID = -67607 case invalidKeyUsageForPolicy = -67608 case invalidExtendedKeyUsage = -67609 case invalidIDLinkage = -67610 case pathLengthConstraintExceeded = -67611 case invalidRoot = -67612 case crlExpired = -67613 case crlNotValidYet = -67614 case crlNotFound = -67615 case crlServerDown = -67616 case crlBadURI = -67617 case unknownCertExtension = -67618 case unknownCRLExtension = -67619 case crlNotTrusted = -67620 case crlPolicyFailed = -67621 case idpFailure = -67622 case smimeEmailAddressesNotFound = -67623 case smimeBadExtendedKeyUsage = -67624 case smimeBadKeyUsage = -67625 case smimeKeyUsageNotCritical = -67626 case smimeNoEmailAddress = -67627 case smimeSubjAltNameNotCritical = -67628 case sslBadExtendedKeyUsage = -67629 case ocspBadResponse = -67630 case ocspBadRequest = -67631 case ocspUnavailable = -67632 case ocspStatusUnrecognized = -67633 case endOfData = -67634 case incompleteCertRevocationCheck = -67635 case networkFailure = -67636 case ocspNotTrustedToAnchor = -67637 case recordModified = -67638 case ocspSignatureError = -67639 case ocspNoSigner = -67640 case ocspResponderMalformedReq = -67641 case ocspResponderInternalError = -67642 case ocspResponderTryLater = -67643 case ocspResponderSignatureRequired = -67644 case ocspResponderUnauthorized = -67645 case ocspResponseNonceMismatch = -67646 case codeSigningBadCertChainLength = -67647 case codeSigningNoBasicConstraints = -67648 case codeSigningBadPathLengthConstraint = -67649 case codeSigningNoExtendedKeyUsage = -67650 case codeSigningDevelopment = -67651 case resourceSignBadCertChainLength = -67652 case resourceSignBadExtKeyUsage = -67653 case trustSettingDeny = -67654 case invalidSubjectName = -67655 case unknownQualifiedCertStatement = -67656 case mobileMeRequestQueued = -67657 case mobileMeRequestRedirected = -67658 case mobileMeServerError = -67659 case mobileMeServerNotAvailable = -67660 case mobileMeServerAlreadyExists = -67661 case mobileMeServerServiceErr = -67662 case mobileMeRequestAlreadyPending = -67663 case mobileMeNoRequestPending = -67664 case mobileMeCSRVerifyFailure = -67665 case mobileMeFailedConsistencyCheck = -67666 case notInitialized = -67667 case invalidHandleUsage = -67668 case pvcReferentNotFound = -67669 case functionIntegrityFail = -67670 case internalError = -67671 case memoryError = -67672 case invalidData = -67673 case mdsError = -67674 case invalidPointer = -67675 case selfCheckFailed = -67676 case functionFailed = -67677 case moduleManifestVerifyFailed = -67678 case invalidGUID = -67679 case invalidHandle = -67680 case invalidDBList = -67681 case invalidPassthroughID = -67682 case invalidNetworkAddress = -67683 case crlAlreadySigned = -67684 case invalidNumberOfFields = -67685 case verificationFailure = -67686 case unknownTag = -67687 case invalidSignature = -67688 case invalidName = -67689 case invalidCertificateRef = -67690 case invalidCertificateGroup = -67691 case tagNotFound = -67692 case invalidQuery = -67693 case invalidValue = -67694 case callbackFailed = -67695 case aclDeleteFailed = -67696 case aclReplaceFailed = -67697 case aclAddFailed = -67698 case aclChangeFailed = -67699 case invalidAccessCredentials = -67700 case invalidRecord = -67701 case invalidACL = -67702 case invalidSampleValue = -67703 case incompatibleVersion = -67704 case privilegeNotGranted = -67705 case invalidScope = -67706 case pvcAlreadyConfigured = -67707 case invalidPVC = -67708 case emmLoadFailed = -67709 case emmUnloadFailed = -67710 case addinLoadFailed = -67711 case invalidKeyRef = -67712 case invalidKeyHierarchy = -67713 case addinUnloadFailed = -67714 case libraryReferenceNotFound = -67715 case invalidAddinFunctionTable = -67716 case invalidServiceMask = -67717 case moduleNotLoaded = -67718 case invalidSubServiceID = -67719 case attributeNotInContext = -67720 case moduleManagerInitializeFailed = -67721 case moduleManagerNotFound = -67722 case eventNotificationCallbackNotFound = -67723 case inputLengthError = -67724 case outputLengthError = -67725 case privilegeNotSupported = -67726 case deviceError = -67727 case attachHandleBusy = -67728 case notLoggedIn = -67729 case algorithmMismatch = -67730 case keyUsageIncorrect = -67731 case keyBlobTypeIncorrect = -67732 case keyHeaderInconsistent = -67733 case unsupportedKeyFormat = -67734 case unsupportedKeySize = -67735 case invalidKeyUsageMask = -67736 case unsupportedKeyUsageMask = -67737 case invalidKeyAttributeMask = -67738 case unsupportedKeyAttributeMask = -67739 case invalidKeyLabel = -67740 case unsupportedKeyLabel = -67741 case invalidKeyFormat = -67742 case unsupportedVectorOfBuffers = -67743 case invalidInputVector = -67744 case invalidOutputVector = -67745 case invalidContext = -67746 case invalidAlgorithm = -67747 case invalidAttributeKey = -67748 case missingAttributeKey = -67749 case invalidAttributeInitVector = -67750 case missingAttributeInitVector = -67751 case invalidAttributeSalt = -67752 case missingAttributeSalt = -67753 case invalidAttributePadding = -67754 case missingAttributePadding = -67755 case invalidAttributeRandom = -67756 case missingAttributeRandom = -67757 case invalidAttributeSeed = -67758 case missingAttributeSeed = -67759 case invalidAttributePassphrase = -67760 case missingAttributePassphrase = -67761 case invalidAttributeKeyLength = -67762 case missingAttributeKeyLength = -67763 case invalidAttributeBlockSize = -67764 case missingAttributeBlockSize = -67765 case invalidAttributeOutputSize = -67766 case missingAttributeOutputSize = -67767 case invalidAttributeRounds = -67768 case missingAttributeRounds = -67769 case invalidAlgorithmParms = -67770 case missingAlgorithmParms = -67771 case invalidAttributeLabel = -67772 case missingAttributeLabel = -67773 case invalidAttributeKeyType = -67774 case missingAttributeKeyType = -67775 case invalidAttributeMode = -67776 case missingAttributeMode = -67777 case invalidAttributeEffectiveBits = -67778 case missingAttributeEffectiveBits = -67779 case invalidAttributeStartDate = -67780 case missingAttributeStartDate = -67781 case invalidAttributeEndDate = -67782 case missingAttributeEndDate = -67783 case invalidAttributeVersion = -67784 case missingAttributeVersion = -67785 case invalidAttributePrime = -67786 case missingAttributePrime = -67787 case invalidAttributeBase = -67788 case missingAttributeBase = -67789 case invalidAttributeSubprime = -67790 case missingAttributeSubprime = -67791 case invalidAttributeIterationCount = -67792 case missingAttributeIterationCount = -67793 case invalidAttributeDLDBHandle = -67794 case missingAttributeDLDBHandle = -67795 case invalidAttributeAccessCredentials = -67796 case missingAttributeAccessCredentials = -67797 case invalidAttributePublicKeyFormat = -67798 case missingAttributePublicKeyFormat = -67799 case invalidAttributePrivateKeyFormat = -67800 case missingAttributePrivateKeyFormat = -67801 case invalidAttributeSymmetricKeyFormat = -67802 case missingAttributeSymmetricKeyFormat = -67803 case invalidAttributeWrappedKeyFormat = -67804 case missingAttributeWrappedKeyFormat = -67805 case stagedOperationInProgress = -67806 case stagedOperationNotStarted = -67807 case verifyFailed = -67808 case querySizeUnknown = -67809 case blockSizeMismatch = -67810 case publicKeyInconsistent = -67811 case deviceVerifyFailed = -67812 case invalidLoginName = -67813 case alreadyLoggedIn = -67814 case invalidDigestAlgorithm = -67815 case invalidCRLGroup = -67816 case certificateCannotOperate = -67817 case certificateExpired = -67818 case certificateNotValidYet = -67819 case certificateRevoked = -67820 case certificateSuspended = -67821 case insufficientCredentials = -67822 case invalidAction = -67823 case invalidAuthority = -67824 case verifyActionFailed = -67825 case invalidCertAuthority = -67826 case invaldCRLAuthority = -67827 case invalidCRLEncoding = -67828 case invalidCRLType = -67829 case invalidCRL = -67830 case invalidFormType = -67831 case invalidID = -67832 case invalidIdentifier = -67833 case invalidIndex = -67834 case invalidPolicyIdentifiers = -67835 case invalidTimeString = -67836 case invalidReason = -67837 case invalidRequestInputs = -67838 case invalidResponseVector = -67839 case invalidStopOnPolicy = -67840 case invalidTuple = -67841 case multipleValuesUnsupported = -67842 case notTrusted = -67843 case noDefaultAuthority = -67844 case rejectedForm = -67845 case requestLost = -67846 case requestRejected = -67847 case unsupportedAddressType = -67848 case unsupportedService = -67849 case invalidTupleGroup = -67850 case invalidBaseACLs = -67851 case invalidTupleCredendtials = -67852 case invalidEncoding = -67853 case invalidValidityPeriod = -67854 case invalidRequestor = -67855 case requestDescriptor = -67856 case invalidBundleInfo = -67857 case invalidCRLIndex = -67858 case noFieldValues = -67859 case unsupportedFieldFormat = -67860 case unsupportedIndexInfo = -67861 case unsupportedLocality = -67862 case unsupportedNumAttributes = -67863 case unsupportedNumIndexes = -67864 case unsupportedNumRecordTypes = -67865 case fieldSpecifiedMultiple = -67866 case incompatibleFieldFormat = -67867 case invalidParsingModule = -67868 case databaseLocked = -67869 case datastoreIsOpen = -67870 case missingValue = -67871 case unsupportedQueryLimits = -67872 case unsupportedNumSelectionPreds = -67873 case unsupportedOperator = -67874 case invalidDBLocation = -67875 case invalidAccessRequest = -67876 case invalidIndexInfo = -67877 case invalidNewOwner = -67878 case invalidModifyMode = -67879 case missingRequiredExtension = -67880 case extendedKeyUsageNotCritical = -67881 case timestampMissing = -67882 case timestampInvalid = -67883 case timestampNotTrusted = -67884 case timestampServiceNotAvailable = -67885 case timestampBadAlg = -67886 case timestampBadRequest = -67887 case timestampBadDataFormat = -67888 case timestampTimeNotAvailable = -67889 case timestampUnacceptedPolicy = -67890 case timestampUnacceptedExtension = -67891 case timestampAddInfoNotAvailable = -67892 case timestampSystemFailure = -67893 case signingTimeMissing = -67894 case timestampRejection = -67895 case timestampWaiting = -67896 case timestampRevocationWarning = -67897 case timestampRevocationNotification = -67898 case unexpectedError = -99999 } extension Status: RawRepresentable, CustomStringConvertible { public init(status: OSStatus) { if let mappedStatus = Status(rawValue: status) { self = mappedStatus } else { self = .unexpectedError } } public var description: String { switch self { case .success: return "No error." case .unimplemented: return "Function or operation not implemented." case .diskFull: return "The disk is full." case .io: return "I/O error (bummers)" case .opWr: return "file already open with with write permission" case .param: return "One or more parameters passed to a function were not valid." case .wrPerm: return "write permissions error" case .allocate: return "Failed to allocate memory." case .userCanceled: return "User canceled the operation." case .badReq: return "Bad parameter or invalid state for operation." case .internalComponent: return "" case .notAvailable: return "No keychain is available. You may need to restart your computer." case .readOnly: return "This keychain cannot be modified." case .authFailed: return "The user name or passphrase you entered is not correct." case .noSuchKeychain: return "The specified keychain could not be found." case .invalidKeychain: return "The specified keychain is not a valid keychain file." case .duplicateKeychain: return "A keychain with the same name already exists." case .duplicateCallback: return "The specified callback function is already installed." case .invalidCallback: return "The specified callback function is not valid." case .duplicateItem: return "The specified item already exists in the keychain." case .itemNotFound: return "The specified item could not be found in the keychain." case .bufferTooSmall: return "There is not enough memory available to use the specified item." case .dataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case .noSuchAttr: return "The specified attribute does not exist." case .invalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case .invalidSearchRef: return "Unable to search the current keychain." case .noSuchClass: return "The specified item does not appear to be a valid keychain item." case .noDefaultKeychain: return "A default keychain could not be found." case .interactionNotAllowed: return "User interaction is not allowed." case .readOnlyAttr: return "The specified attribute could not be modified." case .wrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case .keySizeNotAllowed: return "This item specifies a key size which is too large." case .noStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case .noCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case .noPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case .interactionRequired: return "User interaction is required, but is currently not allowed." case .dataNotAvailable: return "The contents of this item cannot be retrieved." case .dataNotModifiable: return "The contents of this item cannot be modified." case .createChainFailed: return "One or more certificates required to validate this certificate cannot be found." case .invalidPrefsDomain: return "The specified preferences domain is not valid." case .inDarkWake: return "In dark wake, no UI possible" case .aclNotSimple: return "The specified access control list is not in standard (simple) form." case .policyNotFound: return "The specified policy cannot be found." case .invalidTrustSetting: return "The specified trust setting is invalid." case .noAccessForItem: return "The specified item has no access control." case .invalidOwnerEdit: return "Invalid attempt to change the owner of this item." case .trustNotAvailable: return "No trust results are available." case .unsupportedFormat: return "Import/Export format unsupported." case .unknownFormat: return "Unknown format in import." case .keyIsSensitive: return "Key material must be wrapped for export." case .multiplePrivKeys: return "An attempt was made to import multiple private keys." case .passphraseRequired: return "Passphrase is required for import/export." case .invalidPasswordRef: return "The password reference was invalid." case .invalidTrustSettings: return "The Trust Settings Record was corrupted." case .noTrustSettings: return "No Trust Settings were found." case .pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case .invalidCertificate: return "This certificate could not be decoded." case .notSigner: return "A certificate was not signed by its proposed parent." case .policyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case .invalidKey: return "The provided key material was not valid." case .decode: return "Unable to decode the provided data." case .`internal`: return "An internal error occurred in the Security framework." case .unsupportedAlgorithm: return "An unsupported algorithm was encountered." case .unsupportedOperation: return "The operation you requested is not supported by this key." case .unsupportedPadding: return "The padding you requested is not supported." case .itemInvalidKey: return "A string key in dictionary is not one of the supported keys." case .itemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case .itemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case .itemClassMissing: return "No kSecItemClass key was specified in a dictionary." case .itemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case .useItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case .useKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case .useKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case .returnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case .returnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case .returnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case .returnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case .valueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case .valuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case .returnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case .matchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case .itemIllegalQuery: return "The caller passed in a query which contained too many keys." case .waitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case .missingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case .upgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case .mpSignatureInvalid: return "Signature invalid on MP message" case .otrTooOld: return "Message is too old to use" case .otrIDTooNew: return "Key ID is too new to use! Message from the future?" case .serviceNotAvailable: return "The required service is not available." case .insufficientClientID: return "The client ID is not correct." case .deviceReset: return "A device reset has occurred." case .deviceFailed: return "A device failure has occurred." case .appleAddAppACLSubject: return "Adding an application ACL subject failed." case .applePublicKeyIncomplete: return "The public key is incomplete." case .appleSignatureMismatch: return "A signature mismatch has occurred." case .appleInvalidKeyStartDate: return "The specified key has an invalid start date." case .appleInvalidKeyEndDate: return "The specified key has an invalid end date." case .conversionError: return "A conversion error has occurred." case .appleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case .quotaExceeded: return "The quota was exceeded." case .fileTooBig: return "The file is too big." case .invalidDatabaseBlob: return "The specified database has an invalid blob." case .invalidKeyBlob: return "The specified database has an invalid key blob." case .incompatibleDatabaseBlob: return "The specified database has an incompatible blob." case .incompatibleKeyBlob: return "The specified database has an incompatible key blob." case .hostNameMismatch: return "A host name mismatch has occurred." case .unknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case .noBasicConstraints: return "No basic constraints were found." case .noBasicConstraintsCA: return "No basic CA constraints were found." case .invalidAuthorityKeyID: return "The authority key ID is not valid." case .invalidSubjectKeyID: return "The subject key ID is not valid." case .invalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case .invalidExtendedKeyUsage: return "The extended key usage is not valid." case .invalidIDLinkage: return "The ID linkage is not valid." case .pathLengthConstraintExceeded: return "The path length constraint was exceeded." case .invalidRoot: return "The root or anchor certificate is not valid." case .crlExpired: return "The CRL has expired." case .crlNotValidYet: return "The CRL is not yet valid." case .crlNotFound: return "The CRL was not found." case .crlServerDown: return "The CRL server is down." case .crlBadURI: return "The CRL has a bad Uniform Resource Identifier." case .unknownCertExtension: return "An unknown certificate extension was encountered." case .unknownCRLExtension: return "An unknown CRL extension was encountered." case .crlNotTrusted: return "The CRL is not trusted." case .crlPolicyFailed: return "The CRL policy failed." case .idpFailure: return "The issuing distribution point was not valid." case .smimeEmailAddressesNotFound: return "An email address mismatch was encountered." case .smimeBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case .smimeBadKeyUsage: return "The key usage is not compatible with SMIME." case .smimeKeyUsageNotCritical: return "The key usage extension is not marked as critical." case .smimeNoEmailAddress: return "No email address was found in the certificate." case .smimeSubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case .sslBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case .ocspBadResponse: return "The OCSP response was incorrect or could not be parsed." case .ocspBadRequest: return "The OCSP request was incorrect or could not be parsed." case .ocspUnavailable: return "OCSP service is unavailable." case .ocspStatusUnrecognized: return "The OCSP server did not recognize this certificate." case .endOfData: return "An end-of-data was detected." case .incompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case .networkFailure: return "A network failure occurred." case .ocspNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case .recordModified: return "The record was modified." case .ocspSignatureError: return "The OCSP response had an invalid signature." case .ocspNoSigner: return "The OCSP response had no signer." case .ocspResponderMalformedReq: return "The OCSP responder was given a malformed request." case .ocspResponderInternalError: return "The OCSP responder encountered an internal error." case .ocspResponderTryLater: return "The OCSP responder is busy, try again later." case .ocspResponderSignatureRequired: return "The OCSP responder requires a signature." case .ocspResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case .ocspResponseNonceMismatch: return "The OCSP response nonce did not match the request." case .codeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case .codeSigningNoBasicConstraints: return "Code signing found no basic constraints." case .codeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case .codeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case .codeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case .resourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case .resourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case .trustSettingDeny: return "The trust setting for this policy was set to Deny." case .invalidSubjectName: return "An invalid certificate subject name was encountered." case .unknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case .mobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case .mobileMeRequestRedirected: return "The MobileMe request was redirected." case .mobileMeServerError: return "A MobileMe server error occurred." case .mobileMeServerNotAvailable: return "The MobileMe server is not available." case .mobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case .mobileMeServerServiceErr: return "A MobileMe service error has occurred." case .mobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case .mobileMeNoRequestPending: return "MobileMe has no request pending." case .mobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case .mobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case .notInitialized: return "A function was called without initializing CSSM." case .invalidHandleUsage: return "The CSSM handle does not match with the service type." case .pvcReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case .functionIntegrityFail: return "A function address was not within the verified module." case .internalError: return "An internal error has occurred." case .memoryError: return "A memory error has occurred." case .invalidData: return "Invalid data was encountered." case .mdsError: return "A Module Directory Service error has occurred." case .invalidPointer: return "An invalid pointer was encountered." case .selfCheckFailed: return "Self-check has failed." case .functionFailed: return "A function has failed." case .moduleManifestVerifyFailed: return "A module manifest verification failure has occurred." case .invalidGUID: return "An invalid GUID was encountered." case .invalidHandle: return "An invalid handle was encountered." case .invalidDBList: return "An invalid DB list was encountered." case .invalidPassthroughID: return "An invalid passthrough ID was encountered." case .invalidNetworkAddress: return "An invalid network address was encountered." case .crlAlreadySigned: return "The certificate revocation list is already signed." case .invalidNumberOfFields: return "An invalid number of fields were encountered." case .verificationFailure: return "A verification failure occurred." case .unknownTag: return "An unknown tag was encountered." case .invalidSignature: return "An invalid signature was encountered." case .invalidName: return "An invalid name was encountered." case .invalidCertificateRef: return "An invalid certificate reference was encountered." case .invalidCertificateGroup: return "An invalid certificate group was encountered." case .tagNotFound: return "The specified tag was not found." case .invalidQuery: return "The specified query was not valid." case .invalidValue: return "An invalid value was detected." case .callbackFailed: return "A callback has failed." case .aclDeleteFailed: return "An ACL delete operation has failed." case .aclReplaceFailed: return "An ACL replace operation has failed." case .aclAddFailed: return "An ACL add operation has failed." case .aclChangeFailed: return "An ACL change operation has failed." case .invalidAccessCredentials: return "Invalid access credentials were encountered." case .invalidRecord: return "An invalid record was encountered." case .invalidACL: return "An invalid ACL was encountered." case .invalidSampleValue: return "An invalid sample value was encountered." case .incompatibleVersion: return "An incompatible version was encountered." case .privilegeNotGranted: return "The privilege was not granted." case .invalidScope: return "An invalid scope was encountered." case .pvcAlreadyConfigured: return "The PVC is already configured." case .invalidPVC: return "An invalid PVC was encountered." case .emmLoadFailed: return "The EMM load has failed." case .emmUnloadFailed: return "The EMM unload has failed." case .addinLoadFailed: return "The add-in load operation has failed." case .invalidKeyRef: return "An invalid key was encountered." case .invalidKeyHierarchy: return "An invalid key hierarchy was encountered." case .addinUnloadFailed: return "The add-in unload operation has failed." case .libraryReferenceNotFound: return "A library reference was not found." case .invalidAddinFunctionTable: return "An invalid add-in function table was encountered." case .invalidServiceMask: return "An invalid service mask was encountered." case .moduleNotLoaded: return "A module was not loaded." case .invalidSubServiceID: return "An invalid subservice ID was encountered." case .attributeNotInContext: return "An attribute was not in the context." case .moduleManagerInitializeFailed: return "A module failed to initialize." case .moduleManagerNotFound: return "A module was not found." case .eventNotificationCallbackNotFound: return "An event notification callback was not found." case .inputLengthError: return "An input length error was encountered." case .outputLengthError: return "An output length error was encountered." case .privilegeNotSupported: return "The privilege is not supported." case .deviceError: return "A device error was encountered." case .attachHandleBusy: return "The CSP handle was busy." case .notLoggedIn: return "You are not logged in." case .algorithmMismatch: return "An algorithm mismatch was encountered." case .keyUsageIncorrect: return "The key usage is incorrect." case .keyBlobTypeIncorrect: return "The key blob type is incorrect." case .keyHeaderInconsistent: return "The key header is inconsistent." case .unsupportedKeyFormat: return "The key header format is not supported." case .unsupportedKeySize: return "The key size is not supported." case .invalidKeyUsageMask: return "The key usage mask is not valid." case .unsupportedKeyUsageMask: return "The key usage mask is not supported." case .invalidKeyAttributeMask: return "The key attribute mask is not valid." case .unsupportedKeyAttributeMask: return "The key attribute mask is not supported." case .invalidKeyLabel: return "The key label is not valid." case .unsupportedKeyLabel: return "The key label is not supported." case .invalidKeyFormat: return "The key format is not valid." case .unsupportedVectorOfBuffers: return "The vector of buffers is not supported." case .invalidInputVector: return "The input vector is not valid." case .invalidOutputVector: return "The output vector is not valid." case .invalidContext: return "An invalid context was encountered." case .invalidAlgorithm: return "An invalid algorithm was encountered." case .invalidAttributeKey: return "A key attribute was not valid." case .missingAttributeKey: return "A key attribute was missing." case .invalidAttributeInitVector: return "An init vector attribute was not valid." case .missingAttributeInitVector: return "An init vector attribute was missing." case .invalidAttributeSalt: return "A salt attribute was not valid." case .missingAttributeSalt: return "A salt attribute was missing." case .invalidAttributePadding: return "A padding attribute was not valid." case .missingAttributePadding: return "A padding attribute was missing." case .invalidAttributeRandom: return "A random number attribute was not valid." case .missingAttributeRandom: return "A random number attribute was missing." case .invalidAttributeSeed: return "A seed attribute was not valid." case .missingAttributeSeed: return "A seed attribute was missing." case .invalidAttributePassphrase: return "A passphrase attribute was not valid." case .missingAttributePassphrase: return "A passphrase attribute was missing." case .invalidAttributeKeyLength: return "A key length attribute was not valid." case .missingAttributeKeyLength: return "A key length attribute was missing." case .invalidAttributeBlockSize: return "A block size attribute was not valid." case .missingAttributeBlockSize: return "A block size attribute was missing." case .invalidAttributeOutputSize: return "An output size attribute was not valid." case .missingAttributeOutputSize: return "An output size attribute was missing." case .invalidAttributeRounds: return "The number of rounds attribute was not valid." case .missingAttributeRounds: return "The number of rounds attribute was missing." case .invalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case .missingAlgorithmParms: return "An algorithm parameters attribute was missing." case .invalidAttributeLabel: return "A label attribute was not valid." case .missingAttributeLabel: return "A label attribute was missing." case .invalidAttributeKeyType: return "A key type attribute was not valid." case .missingAttributeKeyType: return "A key type attribute was missing." case .invalidAttributeMode: return "A mode attribute was not valid." case .missingAttributeMode: return "A mode attribute was missing." case .invalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case .missingAttributeEffectiveBits: return "An effective bits attribute was missing." case .invalidAttributeStartDate: return "A start date attribute was not valid." case .missingAttributeStartDate: return "A start date attribute was missing." case .invalidAttributeEndDate: return "An end date attribute was not valid." case .missingAttributeEndDate: return "An end date attribute was missing." case .invalidAttributeVersion: return "A version attribute was not valid." case .missingAttributeVersion: return "A version attribute was missing." case .invalidAttributePrime: return "A prime attribute was not valid." case .missingAttributePrime: return "A prime attribute was missing." case .invalidAttributeBase: return "A base attribute was not valid." case .missingAttributeBase: return "A base attribute was missing." case .invalidAttributeSubprime: return "A subprime attribute was not valid." case .missingAttributeSubprime: return "A subprime attribute was missing." case .invalidAttributeIterationCount: return "An iteration count attribute was not valid." case .missingAttributeIterationCount: return "An iteration count attribute was missing." case .invalidAttributeDLDBHandle: return "A database handle attribute was not valid." case .missingAttributeDLDBHandle: return "A database handle attribute was missing." case .invalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case .missingAttributeAccessCredentials: return "An access credentials attribute was missing." case .invalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case .missingAttributePublicKeyFormat: return "A public key format attribute was missing." case .invalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case .missingAttributePrivateKeyFormat: return "A private key format attribute was missing." case .invalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case .missingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case .invalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case .missingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case .stagedOperationInProgress: return "A staged operation is in progress." case .stagedOperationNotStarted: return "A staged operation was not started." case .verifyFailed: return "A cryptographic verification failure has occurred." case .querySizeUnknown: return "The query size is unknown." case .blockSizeMismatch: return "A block size mismatch occurred." case .publicKeyInconsistent: return "The public key was inconsistent." case .deviceVerifyFailed: return "A device verification failure has occurred." case .invalidLoginName: return "An invalid login name was detected." case .alreadyLoggedIn: return "The user is already logged in." case .invalidDigestAlgorithm: return "An invalid digest algorithm was detected." case .invalidCRLGroup: return "An invalid CRL group was detected." case .certificateCannotOperate: return "The certificate cannot operate." case .certificateExpired: return "An expired certificate was detected." case .certificateNotValidYet: return "The certificate is not yet valid." case .certificateRevoked: return "The certificate was revoked." case .certificateSuspended: return "The certificate was suspended." case .insufficientCredentials: return "Insufficient credentials were detected." case .invalidAction: return "The action was not valid." case .invalidAuthority: return "The authority was not valid." case .verifyActionFailed: return "A verify action has failed." case .invalidCertAuthority: return "The certificate authority was not valid." case .invaldCRLAuthority: return "The CRL authority was not valid." case .invalidCRLEncoding: return "The CRL encoding was not valid." case .invalidCRLType: return "The CRL type was not valid." case .invalidCRL: return "The CRL was not valid." case .invalidFormType: return "The form type was not valid." case .invalidID: return "The ID was not valid." case .invalidIdentifier: return "The identifier was not valid." case .invalidIndex: return "The index was not valid." case .invalidPolicyIdentifiers: return "The policy identifiers are not valid." case .invalidTimeString: return "The time specified was not valid." case .invalidReason: return "The trust policy reason was not valid." case .invalidRequestInputs: return "The request inputs are not valid." case .invalidResponseVector: return "The response vector was not valid." case .invalidStopOnPolicy: return "The stop-on policy was not valid." case .invalidTuple: return "The tuple was not valid." case .multipleValuesUnsupported: return "Multiple values are not supported." case .notTrusted: return "The trust policy was not trusted." case .noDefaultAuthority: return "No default authority was detected." case .rejectedForm: return "The trust policy had a rejected form." case .requestLost: return "The request was lost." case .requestRejected: return "The request was rejected." case .unsupportedAddressType: return "The address type is not supported." case .unsupportedService: return "The service is not supported." case .invalidTupleGroup: return "The tuple group was not valid." case .invalidBaseACLs: return "The base ACLs are not valid." case .invalidTupleCredendtials: return "The tuple credentials are not valid." case .invalidEncoding: return "The encoding was not valid." case .invalidValidityPeriod: return "The validity period was not valid." case .invalidRequestor: return "The requestor was not valid." case .requestDescriptor: return "The request descriptor was not valid." case .invalidBundleInfo: return "The bundle information was not valid." case .invalidCRLIndex: return "The CRL index was not valid." case .noFieldValues: return "No field values were detected." case .unsupportedFieldFormat: return "The field format is not supported." case .unsupportedIndexInfo: return "The index information is not supported." case .unsupportedLocality: return "The locality is not supported." case .unsupportedNumAttributes: return "The number of attributes is not supported." case .unsupportedNumIndexes: return "The number of indexes is not supported." case .unsupportedNumRecordTypes: return "The number of record types is not supported." case .fieldSpecifiedMultiple: return "Too many fields were specified." case .incompatibleFieldFormat: return "The field format was incompatible." case .invalidParsingModule: return "The parsing module was not valid." case .databaseLocked: return "The database is locked." case .datastoreIsOpen: return "The data store is open." case .missingValue: return "A missing value was detected." case .unsupportedQueryLimits: return "The query limits are not supported." case .unsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case .unsupportedOperator: return "The operator is not supported." case .invalidDBLocation: return "The database location is not valid." case .invalidAccessRequest: return "The access request is not valid." case .invalidIndexInfo: return "The index information is not valid." case .invalidNewOwner: return "The new owner is not valid." case .invalidModifyMode: return "The modify mode is not valid." case .missingRequiredExtension: return "A required certificate extension is missing." case .extendedKeyUsageNotCritical: return "The extended key usage extension was not marked critical." case .timestampMissing: return "A timestamp was expected but was not found." case .timestampInvalid: return "The timestamp was not valid." case .timestampNotTrusted: return "The timestamp was not trusted." case .timestampServiceNotAvailable: return "The timestamp service is not available." case .timestampBadAlg: return "An unrecognized or unsupported Algorithm Identifier in timestamp." case .timestampBadRequest: return "The timestamp transaction is not permitted or supported." case .timestampBadDataFormat: return "The timestamp data submitted has the wrong format." case .timestampTimeNotAvailable: return "The time source for the Timestamp Authority is not available." case .timestampUnacceptedPolicy: return "The requested policy is not supported by the Timestamp Authority." case .timestampUnacceptedExtension: return "The requested extension is not supported by the Timestamp Authority." case .timestampAddInfoNotAvailable: return "The additional information requested is not available." case .timestampSystemFailure: return "The timestamp request cannot be handled due to system failure." case .signingTimeMissing: return "A signing time was expected but was not found." case .timestampRejection: return "A timestamp transaction was rejected." case .timestampWaiting: return "A timestamp transaction is waiting." case .timestampRevocationWarning: return "A timestamp authority revocation warning was issued." case .timestampRevocationNotification: return "A timestamp authority revocation notification was issued." case .unexpectedError: return "Unexpected error has occurred." } } } extension Status: CustomNSError { public static let errorDomain = KeychainAccessErrorDomain public var errorCode: Int { return Int(rawValue) } public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: description] } }
mit
29676eaa698b39d3f111d96565477489
38.709004
217
0.604233
5.525701
false
false
false
false
sugar2010/SwiftOptimizer
swix/oneD/oneD-simple-math.swift
2
3664
// // oneD_math.swift // swix // // Created by Scott Sievert on 6/11/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate // SLOW PARTS: almost everything // to speed up first: abs, sign, norm, rand, randn /// applies the function to every element of an array and takes only that argument. This is just a simple for-loop. If you want to use some custom fancy function, define it yourself. func apply_function(function: Double->Double, x: matrix) -> matrix{ var y = zeros(x.count) for i in 0..<x.count{ y[i] = function(x[i]) } return y } func sin(x: matrix) -> matrix{ return apply_function(sin, x) } func cos(x: matrix) -> matrix{ return apply_function(cos, x) } func tan(x: matrix) -> matrix{ return apply_function(tan, x) } /// log_e(.) func log(x: matrix) -> matrix{ var y = apply_function(log, x) return y } func abs(x: matrix) -> matrix{ return apply_function(abs, x) } func sqrt(x: matrix) -> matrix{ var y = apply_function(sqrt, x) return y } func round(x: matrix) -> matrix{ return apply_function(round, x) } func floor(x: matrix) -> matrix{ var y = apply_function(floor, x) return y } func ceil(x: matrix) -> matrix{ var y = apply_function(ceil, x) return y } func sign(x: Double) -> Double{ if x < 0{ return -1 } else{ return 1 } } func sign(x: matrix)->matrix{ return apply_function(sign, x) } func pow(x: matrix, power: Double) -> matrix{ var y = zeros(x.count) for i in 0..<x.count{ y[i] = pow(x[i], power) } return y } func sum(x: matrix) -> Double{ var y = zeros(x.count) var s: Double = 0 for i in 0..<x.count{ s = x[i] + s } return s } func avg(x: matrix) -> Double{ var y: Double = sum(x) return y / x.count.double } func std(x: matrix) -> Double{ var y: Double = avg(x) var z = x - y return sqrt(sum(pow(z, 2) / x.count.double)) } /// variance used since var is a keyword func variance(x: matrix) -> Double{ var y: Double = avg(x) var z = x - y return sum(pow(z, 2) / x.count.double) } func norm(x: matrix, type:String="l2") -> Double{ if type=="l2"{ return sqrt(sum(pow(x, 2)))} if type=="l1"{ return sum(abs(x))} if type=="l0"{ var count = 0.0 for i in 0..<x.n{ if x[i] != 0{ count += 1 } } return count } assert(false, "type of norm unrecongnized") return -1.0 } func cumsum(x: matrix) -> matrix{ let N = x.count var y = zeros(N) for i in 0..<N{ if i==0 { y[i] = x[0] } else if i==1 { y[i] = x[0] + x[1] } else { y[i] = x[i] + y[i-1] } } return y } func rand() -> Double{ return Double(arc4random()) / pow(2, 32) } func rand(N: Int) -> matrix{ var x = zeros(N) for i in 0..<N{ x[i] = rand() } return x } func randn() -> Double{ var u:Double = rand() var v:Double = rand() var x = sqrt(-2*log(u))*cos(2*pi*v); return x } func randn(N: Int, mean: Double=0, sigma: Double=1) -> matrix{ var x = zeros(N) for i in 0..<N{ x[i] = randn() } var y = (x * sigma) + mean; return y } func min(x: matrix, absValue:Bool=false) -> Double{ // absValue not implemeted yet var min = inf var xP = matrixToPointer(x) var minC = min_objc(xP, x.n.cint) return minC } func max(x: matrix, absValue:Bool=false) -> Double{ // absValue not implemeted yet var xP = matrixToPointer(x) var maxC = max_objc(xP, x.n.cint); return maxC }
mit
6141454ceecbc4f9607dc4b065e0ed61
20.680473
182
0.558133
2.9312
false
false
false
false
adrfer/swift
test/SILGen/tuples.swift
2
5362
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s class C {} enum Foo { case X(C, Int) } // <rdar://problem/16020428> // CHECK-LABEL: sil hidden @_TF6tuples8matchFooFT1xOS_3Foo_T_ func matchFoo(x x: Foo) { switch x { case .X(let x): () } } protocol P { func foo() } struct A : P { func foo() {} } func make_int() -> Int { return 0 } func make_p() -> P { return A() } func make_xy() -> (x: Int, y: P) { return (make_int(), make_p()) } // CHECK-LABEL: sil hidden @_TF6tuples17testShuffleOpaqueFT_T_ func testShuffleOpaque() { // CHECK: [[X:%.*]] = alloc_box $P // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK: [[Y:%.*]] = alloc_box $Int // CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 1 // CHECK-NEXT: store [[T1]] to [[PBY]] // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[PBX]] // CHECK-NEXT: dealloc_stack [[TEMP]] var (x,y) : (y:P, x:Int) = make_xy() // CHECK-NEXT: [[PAIR:%.*]] = alloc_box $(y: P, x: Int) // CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]] // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 1 // CHECK-NEXT: store [[T1]] to [[PAIR_1]] // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[PAIR_0]] // CHECK-NEXT: dealloc_stack [[TEMP]] var pair : (y:P, x:Int) = make_xy() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]] : $*(x: Int, y: P), 1 // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $(y: P, x: Int) // CHECK-NEXT: [[TEMP2_0:%.*]] = tuple_element_addr [[TEMP2]] : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[TEMP2_0]] // CHECK-NEXT: [[TEMP2_1:%.*]] = tuple_element_addr [[TEMP2]] : $*(y: P, x: Int), 1 // CHECK-NEXT: store [[T1]] to [[TEMP2_1]] // CHECK-NEXT: copy_addr [take] [[TEMP2]] to [[PBPAIR]] // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: dealloc_stack [[TEMP]] pair = make_xy() } func testShuffleTuple() { // CHECK: [[X:%.*]] = alloc_box $P // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK: [[Y:%.*]] = alloc_box $Int // CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [[PBY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: apply [[T0]]([[PBX]]) var (x,y) : (y:P, x:Int) = (x: make_int(), y: make_p()) // CHECK-NEXT: [[PAIR:%.*]] = alloc_box $(y: P, x: Int) // CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]] // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [[PAIR_1]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: apply [[T0]]([[PAIR_0]]) var pair : (y:P, x:Int) = (x: make_int(), y: make_p()) // This isn't really optimal; we should be evaluating make_p directly // into the temporary. // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[INT:%.*]] = apply [[T0]]() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $P // CHECK-NEXT: apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $(y: P, x: Int) // CHECK-NEXT: [[TEMP2_0:%.*]] = tuple_element_addr [[TEMP2]] : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[TEMP]] to [initialization] [[TEMP2_0]] // CHECK-NEXT: [[TEMP2_1:%.*]] = tuple_element_addr [[TEMP2]] : $*(y: P, x: Int), 1 // CHECK-NEXT: store [[INT]] to [[TEMP2_1]] // CHECK-NEXT: copy_addr [take] [[TEMP2]] to [[PBPAIR]] // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: dealloc_stack [[TEMP]] pair = (x: make_int(), y: make_p()) }
apache-2.0
dee440c9c93177c6616e2f1d21cd18bc
43.31405
85
0.53357
2.76677
false
false
false
false
knehez/edx-app-ios
Source/ListCursor.swift
4
3870
// // ListCursor.swift // edX // // Created by Akiva Leffert on 6/26/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class ListCursor<A> { private var index : Int private let list : [A] public init(before : [A], current : A, after : [A]) { self.index = before.count var list = before list.append(current) list.extend(after) self.list = list } // Will fail if current is not in the list public init?(list: [A], currentFinder : A -> Bool) { if let index = list.firstIndexMatching(currentFinder) { self.index = index self.list = list } else { self.index = 0 self.list = [] return nil } } public init(cursor : ListCursor<A>) { self.index = cursor.index self.list = cursor.list } public init?(startOfList list : [A]) { if list.count == 0 { self.index = 0 self.list = [] return nil } else { self.index = 0 self.list = list } } public init?(endOfList list : [A]) { if list.count == 0 { self.index = 0 self.list = [] return nil } else { self.index = list.count - 1 self.list = list } } public func updateCurrentToItemMatching(matcher : A -> Bool) { if let index = list.firstIndexMatching(matcher) { self.index = index } else { assert(false, "Could not find item in cursor") } } /// Return the previous value if available and decrement the index public func prev() -> A? { if hasPrev { index = index - 1 return list[index] } else { return nil } } /// Return the next value if available and increment the index public func next() -> A? { if hasNext { index = index + 1 return list[index] } else { return nil } } public var hasPrev : Bool { return index > 0 } public var hasNext : Bool { return index + 1 < list.count } public var current : A { assert(index >= 0 && index < list.count, "Invariant violated") return list[index] } /// Return the previous value if possible without changing the current index public func peekPrev() -> A? { if hasPrev { return list[index - 1] } else { return nil } } /// Return the next value if possible without changing the current index public func peekNext() -> A? { if hasNext { return list[index + 1] } else { return nil } } public func loopToStartExcludingCurrent(@noescape f : (ListCursor<A>, Int) -> Void) { while let value = prev() { f(self, self.index) } } public func loopToEndExcludingCurrent(@noescape f : (ListCursor<A>, Int) -> Void) { while let value = next() { f(self, self.index) } } /// Loops through all values backward to the beginning, including the current block public func loopToStart(@noescape f : (ListCursor<A>, Int) -> Void) { for i in reverse(0 ... self.index) { self.index = i f(self, i) } } /// Loops through all values forward to the end, including the current block public func loopToEnd(@noescape f : (ListCursor<A>, Int) -> Void) { for i in self.index ..< self.list.count { self.index = i f(self, i) } } }
apache-2.0
b9e1e128f208374c86d75e3a7a4f9549
23.5
89
0.496641
4.363021
false
false
false
false
KrishMunot/swift
test/SILOptimizer/diagnostic_constant_propagation.swift
3
22253
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify // REQUIRES: PTRSIZE=64 // FIXME: <rdar://problem/19508336> Extend test/SILOptimizer/diagnostic_constant_propagation.swift to 32-bit platforms // These are tests for diagnostics produced by constant propagation pass. func testArithmeticOverflow() { let xu8 : UInt8 = 250 let yu8 : UInt8 = 250 var _ /*zu8*/ = xu8 + yu8 // expected-error {{arithmetic operation '250 + 250' (on type 'UInt8') results in an overflow}} var _ /*xpyu8*/ : UInt8 = 250 + 250 // expected-error {{arithmetic operation '250 + 250' (on type 'UInt8') results in an overflow}} var _ /*xpyi8*/ : Int8 = 126 + 126 // expected-error {{arithmetic operation '126 + 126' (on type 'Int8') results in an overflow}} var _ /*xmyu16*/ : UInt16 = 65000 * 2 // expected-error {{arithmetic operation '65000 * 2' (on type 'UInt16') results in an overflow}} var _ /*xmyi16*/ : Int16 = 32000 * 2 // expected-error {{arithmetic operation '32000 * 2' (on type 'Int16') results in an overflow}} var _ /*xmyu32*/ : UInt32 = 4294967295 * 30 // expected-error {{arithmetic operation '4294967295 * 30' (on type 'UInt32') results in an overflow}} var _ /*xpyi32*/ : Int32 = 2147483647 + 30 // expected-error {{arithmetic operation '2147483647 + 30' (on type 'Int32') results in an overflow}} var _ /*xpyu64*/ : UInt64 = 9223372036854775807 * 30 // expected-error {{results in an overflow}} var _ /*xpyi64*/ : Int64 = 9223372036854775807 + 1 // expected-error {{results in an overflow}} var xu8_2 : UInt8 = 240 xu8_2 += 40 // expected-error {{arithmetic operation '240 + 40' (on type 'UInt8') results in an overflow}} var _ : UInt8 = 230 - 240 // expected-error {{arithmetic operation '230 - 240' (on type 'UInt8') results in an overflow}} var xu8_3 : UInt8 = 240 // Global (cross block) analysis. for _ in 0..<10 {} xu8_3 += 40 // expected-error {{arithmetic operation '240 + 40' (on type 'UInt8') results in an overflow}} var _ : UInt8 = 240 + 5 + 15 // expected-error {{arithmetic operation '245 + 15' (on type 'UInt8') results in an overflow}} // TODO: We should remove the second init for Int8 - see rdar://problem/19224768 _ = Int8(126) + Int8(1+1) // expected-error {{arithmetic operation '126 + 2' (on type 'Int8') results in an overflow}} // DISABLED FOR NOW // asserts in the shift operators confuse constant propagation // var csh1: Int8 = (1 << 7) - 1 // expected - error {{arithmetic operation '-128 - 1' (on type 'Int8') results in an overflow}} // var csh2: Int8 = (-1 & ~(1<<7))+1 // expected - error {{arithmetic operation '127 + 1' (on type 'Int8') results in an overflow}} } @_transparent func myaddSigned(_ x: Int8, _ y: Int8, _ z: Int8) -> Int8 { return x + y } @_transparent func myaddUnsigned(_ x: UInt8, _ y: UInt8, _ z: UInt8) -> UInt8 { return x + y } func testGenericArithmeticOverflowMessage() { myaddSigned(125, 125, 125) // expected-error{{arithmetic operation '125 + 125' (on signed 8-bit integer type) results in an overflow}} myaddUnsigned(250, 250, 250) // expected-error{{arithmetic operation '250 + 250' (on unsigned 8-bit integer type) results in an overflow}} } typealias MyInt = UInt8 func testConvertOverflow() { var _ /*int8_minus_two*/ : Int8 = (-2) var _ /*int8_plus_two*/ : Int8 = (2) var _ /*int16_minus_two*/ : Int16 = (-2) var _ /*int16_plus_two*/ : Int16 = (2) var _ /*int32_minus_two*/ : Int32 = (-2) var _ /*int32_plus_two*/ : Int32 = (2) var _ /*int64_minus_two*/ : Int64 = (-2) var _ /*int64_plus_two*/ : Int64 = (2) let int_minus_two : Int = (-2) let int_plus_two : Int = (2) var _ /*convert_minus_two*/ = Int8(int_minus_two) var _ /*convert_plus_two*/ = Int8(int_plus_two) var _ /*uint8_minus_two*/ : UInt8 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt8'}} var _ /*uint8_plus_two*/ : UInt8 = (2) var _ /*uint16_minus_two*/ : UInt16 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt16'}} var _ /*uint16_plus_two*/ : UInt16 = (2) var _ /*uint32_minus_two*/ : UInt32 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt32'}} let uint32_plus_two : UInt32 = (2) var _ /*uint64_minus_two*/ : UInt64 = (-2) // expected-error {{negative integer '-2' overflows when stored into unsigned type 'UInt64'}} var _ /*uint64_plus_two*/ : UInt64 = (2) var _ /*convert_s_to_u_minus_two*/ = UInt8(int_minus_two) // expected-error {{integer overflows when converted from 'Int' to 'UInt8'}} var _ /*convert_s_to_u_plus_two*/ = UInt8(int_plus_two) var _ /*convert_u_to_s_plus_two*/ = Int8(uint32_plus_two) var _ /*int8_min*/ : Int8 = (-128) var _ /*int8_min_m1*/ : Int8 = (-129) // expected-error {{integer literal '-129' overflows when stored into 'Int8'}} var _ /*int16_min*/ : Int16 = (-32768) var _ /*int16_min_m1*/ : Int16 = (-32769) // expected-error {{integer literal '-32769' overflows when stored into 'Int16'}} var _ /*int32_min*/ : Int32 = (-2147483648) var _ /*int32_min_m1*/ : Int32 = (-2147483649) // expected-error {{integer literal '-2147483649' overflows when stored into 'Int32'}} var _ /*int64_min*/ : Int64 = (-9223372036854775808) var _ /*int64_min_m1*/ : Int64 = (-9223372036854775809) // expected-error {{integer literal '-9223372036854775809' overflows when stored into 'Int64'}} let int_minus_128 = -128 var _ /*int8_min_conv*/ = Int8(int_minus_128) let int_minus_129 = -129 var _ /*int8_min_m1_conv*/ = Int8(int_minus_129) // expected-error {{integer overflows when converted from 'Int' to 'Int8'}} var _ /*int8_max*/ : Int8 = (127) var _ /*int8_max_p1*/ : Int8 = (128) // expected-error {{integer literal '128' overflows when stored into 'Int8'}} let int16_max : Int16 = (32767) var _ /*int16_max_p1*/ : Int16 = (32768) // expected-error {{integer literal '32768' overflows when stored into 'Int16'}} var _ /*int32_max*/ : Int32 = (2147483647) var _ /*int32_max_p1*/ : Int32 = (2147483648) // expected-error {{integer literal '2147483648' overflows when stored into 'Int32'}} var _ /*int64_max*/ : Int64 = (9223372036854775807) var _ /*int64_max_p1*/ : Int64 = (9223372036854775808) // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int64'}} var _ /*int16_max_conv*/ = Int16(UInt64(int16_max)) let uint64_plus_32768 : UInt64 = 32768 var _ /*int16_max_p1_conv*/ = Int16(uint64_plus_32768) // expected-error {{integer overflows when converted from 'UInt64' to 'Int16'}} var _ /*int8_max_pa*/ : Int8 = -13333; //expected-error{{integer literal '-13333' overflows when stored into 'Int8}} var _ /*int32_max_p_hex*/ : Int32 = 0xFFFF_FFFF; //expected-error{{integer literal '4294967295' overflows when stored into 'Int32'}} var _ /*uint32_max_hex*/ : UInt32 = 0xFFFF_FFFF var _ /*uint32_max_p_hex*/ : UInt32 = 0xFFFF_FFFF_F; //expected-error{{integer literal '68719476735' overflows when stored into 'UInt32'}} var _ /*uint0_typealias*/ : MyInt = 256; //expected-error{{integer literal '256' overflows when stored into 'MyInt'}} var _ /*uint8_min*/ : UInt8 = (0) let uint16_min : UInt16 = (0) var _ /*uint32_min*/ : UInt32 = (0) let uint64_min : UInt64 = (0) var _ /*uint8_min_conv_to_u*/ = UInt8(uint64_min) let int8_zero : Int8 = (0) var _ /*int16_zero*/ : Int16 = (0) var _ /*int32_zero*/ : Int32 = (0) var _ /*int64_zero*/ : Int64 = (0) var _ /*int8_min_conv_to_s*/ = Int8(uint16_min) var _ /*uint8_max*/ : UInt8 = (255) var _ /*uint8_max_p1*/ : UInt8 = (256) // expected-error {{integer literal '256' overflows when stored into 'UInt8'}} var _ /*uint16_max*/ : UInt16 = (65535) var _ /*uint16_max_p1*/ : UInt16 = (65536) // expected-error {{integer literal '65536' overflows when stored into 'UInt16'}} var _ /*uint32_max*/ : UInt32 = (4294967295) var _ /*uint32_max_p1*/ : UInt32 = (4294967296) // expected-error {{integer literal '4294967296' overflows when stored into 'UInt32'}} var _ /*uint64_max*/ : UInt64 = (18446744073709551615) var _ /*uint64_max_p1*/ : UInt64 = (18446744073709551616) // expected-error {{integer literal '18446744073709551616' overflows when stored into 'UInt64'}} let uint16_255 : UInt16 = 255 var _ /*uint8_max_conv*/ = UInt8(uint16_255) let uint16_256 : UInt16 = 256 var _ /*uint8_max_p1_conv*/ = UInt8(uint16_256) // expected-error {{integer overflows when converted from 'UInt16' to 'UInt8'}} // Check same size int conversions. let int8_minus_1 : Int8 = -1 let _ /*ssint8_neg*/ = UInt8(int8_minus_1) // expected-error {{negative integer cannot be converted to unsigned type 'UInt8'}} let uint8_128 : UInt8 = 128 let _ /*ssint8_toobig*/ = Int8(uint8_128) // expected-error {{integer overflows when converted from 'UInt8' to 'Int8'}} let uint8_127 : UInt8 = 127 let _ /*ssint8_good*/ = Int8(uint8_127) let int8_127 : Int8 = 127 let _ /*ssint8_good2*/ = UInt8(int8_127) let _ /*ssint8_zero*/ = UInt8(int8_zero) let uint8_zero : UInt8 = 0 let _ /*ssint8_zero2*/ = Int8(uint8_zero) // Check signed to unsigned extending size conversions. UInt16(Int8(-1)) // expected-error{{negative integer cannot be converted to unsigned type 'UInt16'}} // expected-warning{{unused}} UInt64(Int16(-200)) // expected-error{{negative integer cannot be converted to unsigned type 'UInt64'}} // expected-warning{{unused}} UInt64(Int32(-200)) // expected-error{{negative integer cannot be converted to unsigned type 'UInt64'}} // expected-warning{{unused}} Int16(Int8(-1)) // expected-warning{{unused}} Int64(Int16(-200)) // expected-warning{{unused}} Int64(Int32(-200)) // expected-warning{{unused}} Int64(UInt32(200)) // expected-warning{{unused}} UInt64(UInt32(200)) // expected-warning{{unused}} // IEEE binary32 max value = 2^128 * (2^23-1)/2^23 var _ /*float32_max*/ : Float32 = (340282326356119256160033759537265639424) var _ /*float32_max_p1*/ : Float32 = (340282326356119256160033759537265639425) // 2^128 * (2^25-1)/2^25 - 1 var _ /*float32_max_not_yet_overflow*/ : Float32 = (340282356779733661637539395458142568447) // 2^128 * (2^25-1)/2^25 var _ /*float32_max_first_overflow*/ : Float32 = (340282356779733661637539395458142568448) // expected-error {{integer literal '340282356779733661637539395458142568448' overflows when stored into 'Float32'}} // 2^128 var _ /*float32_max_definitely_overflow*/ : Float32 = (340282366920938463463374607431768211456) // expected-error {{integer literal '340282366920938463463374607431768211456' overflows when stored into 'Float32'}} // IEEE binary32 min value = -1 * 2^128 * (2^23-1)/2^23 var _ /*float32_min*/ : Float32 = (-340282326356119256160033759537265639424) var _ /*float32_min_p1*/ : Float32 = (-340282326356119256160033759537265639425) // -1 * 2^128 * (2^25-1)/2^25 - 1 var _ /*float32_min_not_yet_overflow*/ : Float32 = (-340282356779733661637539395458142568447) // -1 * 2^128 * (2^25-1)/2^25 var _ /*float32_min_first_overflow*/ : Float32 = (-340282356779733661637539395458142568448) // expected-error {{integer literal '-340282356779733661637539395458142568448' overflows when stored into 'Float32'}} // -1 * 2^128 var _ /*float32_min_definitely_overflow*/ : Float32 = (-340282366920938463463374607431768211456) // expected-error {{integer literal '-340282366920938463463374607431768211456' overflows when stored into 'Float32'}} // IEEE binary64 max value = 2^1024 * (2^52-1)/2^52 var _ /*float64_max*/ : Float64 = (179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) var _ /*float64_max_p1*/ : Float64 = (179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) // 2^1024 * (2^54-1)/2^54 - 1 var _/*float64_max_not_yet_overflow*/ : Float64 = (179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791) // 2^1024 * (2^54-1)/2^54 var _ /*float64_max_first_overflow*/ : Float64 = (179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792) // expected-error {{integer literal '179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792' overflows when stored into 'Double'}} // 2^1024 var _/*float64_max_definitely_overflow*/ : Float64 = (179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216) // expected-error {{integer literal '179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216' overflows when stored into 'Double'}} // IEEE binary64 min value = -1 * 2^1024 * (2^52-1)/2^52 var _/*float64_min*/ : Float64 = (-179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) var _/*float64_min_p1*/ : Float64 = (-179769313486231550856124328384506240234343437157459335924404872448581845754556114388470639943126220321960804027157371570809852884964511743044087662767600909594331927728237078876188760579532563768698654064825262115771015791463983014857704008123419459386245141723703148097529108423358883457665451722744025579520) // -1 * 2^1024 * (2^54-1)/2^54 - 1 var _/*float64_min_not_yet_overflow*/ : Float64 = (-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791) // -1 * 2^1024 * (2^54-1)/2^54 var _/*float64_min_first_overflow*/ : Float64 = (-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792) // expected-error {{integer literal '-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792' overflows when stored into 'Double'}} // -1 * 2^1024 var _/*float64_min_definitely_overflow*/ : Float64 = (-179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216) // expected-error {{integer literal '-179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216' overflows when stored into 'Double'}} } @_transparent func intConversionWrapperForUSCheckedConversion(_ x: UInt8, _ unused: UInt8) -> Int8 { return Int8(x) } @_transparent func intConversionWrapperForLiteral() -> Int8 { return 255 // expected-error {{integer literal '255' overflows when stored into 'Int8'}} } func testFallBackDiagnosticMessages() { intConversionWrapperForUSCheckedConversion(255, 30) // expected-error {{integer overflows when converted from unsigned 'Builtin.Int8' to signed 'Builtin.Int8'}} intConversionWrapperForLiteral() // expected-error {{integer literal '255' overflows when stored into signed 'Builtin.Int8'}} } // XXX FIXME -- blocked by: 15735295 Need [su]{div,rem}_with_overflow IR /* func testDivision() { var i : Int = 3 / 3 var id : Int = 3 / 0 // expected -error{{division by zero}} var ir : Int = 3 % 0 // expected -error{{division by zero}} var uzero : UInt8 = 0 var uone : UInt8 = 1 var u : UInt8 = uzero / uone var ud : UInt8 = uone / uzero // expected -error{{division by zero}} var ur : UInt8 = uone % uzero // expected -error{{division by zero}} var f : Float = 3.0 / 0.0 var minusOne : Int32 = -1 var overflow : Int32 = -2147483648 / minusOne // expected -error{{division '-2147483648 / -1' results in an overflow}} } */ func testPostIncOverflow() { var s_max = Int.max s_max += 1 // expected-error {{arithmetic operation '9223372036854775807 + 1' (on type 'Int') results in an overflow}} var u_max = UInt.max u_max += 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt') results in an overflow}} var s8_max = Int8.max s8_max += 1 // expected-error {{arithmetic operation '127 + 1' (on type 'Int8') results in an overflow}} var u8_max = UInt8.max u8_max += 1 // expected-error {{arithmetic operation '255 + 1' (on type 'UInt8') results in an overflow}} var s16_max = Int16.max s16_max += 1 // expected-error {{arithmetic operation '32767 + 1' (on type 'Int16') results in an overflow}} var u16_max = UInt16.max u16_max += 1 // expected-error {{arithmetic operation '65535 + 1' (on type 'UInt16') results in an overflow}} var s32_max = Int32.max s32_max += 1 // expected-error {{arithmetic operation '2147483647 + 1' (on type 'Int32') results in an overflow}} var u32_max = UInt32.max u32_max += 1 // expected-error {{arithmetic operation '4294967295 + 1' (on type 'UInt32') results in an overflow}} var s64_max = Int64.max s64_max += 1 // expected-error {{arithmetic operation '9223372036854775807 + 1' (on type 'Int64') results in an overflow}} var u64_max = UInt64.max u64_max += 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt64') results in an overflow}} } func testPostDecOverflow() { var s_min = Int.min s_min -= 1 // expected-error {{arithmetic operation '-9223372036854775808 - 1' (on type 'Int') results in an overflow}} var u_min = UInt.min u_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt') results in an overflow}} var s8_min = Int8.min s8_min -= 1 // expected-error {{arithmetic operation '-128 - 1' (on type 'Int8') results in an overflow}} var u8_min = UInt8.min u8_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt8') results in an overflow}} var s16_min = Int16.min s16_min -= 1 // expected-error {{arithmetic operation '-32768 - 1' (on type 'Int16') results in an overflow}} var u16_min = UInt16.min u16_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt16') results in an overflow}} var s32_min = Int32.min s32_min -= 1 // expected-error {{arithmetic operation '-2147483648 - 1' (on type 'Int32') results in an overflow}} var u32_min = UInt32.min u32_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt32') results in an overflow}} var s64_min = Int64.min s64_min -= 1 // expected-error {{arithmetic operation '-9223372036854775808 - 1' (on type 'Int64') results in an overflow}} var u64_min = UInt64.min u64_min -= 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt64') results in an overflow}} } func testAssumeNonNegative() { let input = -3 _ = _assumeNonNegative(input) // expected-error {{assumed non-negative value '-3' is negative}} } protocol Num { func Double() -> Self } extension Int8 : Num { @_transparent func Double() -> Int8 { return self * 2 } } @_transparent func Double<T : Num>(_ x: T) -> T { return x.Double() } func tryDouble() -> Int8 { return Double(Int8.max) // expected-error {{arithmetic operation '127 * 2' (on signed 8-bit integer type) results in an overflow}} } @_transparent func add<T : SignedInteger>(_ left: T, _ right: T) -> T { return left + right } @_transparent func applyBinary<T : SignedInteger>(_ fn: (T, T) -> (T), _ left: T, _ right: T) -> T { return fn(left, right) } func testTransparentApply() -> Int8 { return applyBinary(add, Int8.max, Int8.max) // expected-error {{arithmetic operation '127 + 127' (on signed 8-bit integer type) results in an overflow}} }
apache-2.0
7ea8bef83f207c44306424276bde04a2
64.837278
754
0.720532
3.507724
false
false
false
false
nanthi1990/SwiftCharts
Examples/Examples/CubicLinesExample.swift
2
2503
// // CubicLinesExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class CubicLinesExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints = [(0, 0), (4, 4), (8, 11), (9, 2), (11, 10), (12, 3), (15, 18), (18, 10), (20, 15)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))} let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.purpleColor(), lineWidth: 2, animDuration: 1, animDelay: 0) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel], pathGenerator: CubicLinePathGenerator()) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLineLayer ] ) self.view.addSubview(chart.view) self.chart = chart } }
apache-2.0
1d1b34f80b4b28c39b90726edb91f963
48.078431
259
0.687175
5.269474
false
false
false
false