CombinedText
stringlengths
8
3.42M
// // RegistrationPageViewController.swift // Latr // // Created by Apprentice on 7/8/17. // Copyright © 2017 JackHowa. All rights reserved. // import UIKit import Firebase // need db for specifying the db call import FirebaseDatabase import FirebaseAuth class RegistrationPageViewController: UIViewController { let databaseRef = Database.database().reference(fromURL: "https://snapchat-f15b6.firebaseio.com") @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var userEmailTextField: UITextField! @IBOutlet weak var userPhoneTextField: UITextField! @IBOutlet weak var userPasswordTextField: UITextField! @IBOutlet weak var userConfirmPasswordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func displayAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title:"OK", style: UIAlertActionStyle.default, handler:nil); myAlert.addAction(okAction); self.present(myAlert, animated:true, completion:nil); } @IBAction func registerButtonTapped(_ sender: Any) { let user = "" // let name = userNameTextField.text; let email = userEmailTextField.text; let phone = userPhoneTextField.text; let password = userPasswordTextField.text; let confirmPassword = userConfirmPasswordTextField.text; // Check for empty fields if(email!.isEmpty || password!.isEmpty || confirmPassword!.isEmpty) { // Display alert message displayAlertMessage(userMessage: "Email, Password, & Confirmed Password fields are required.") return; } // Check if passwords match if(password != confirmPassword) { // Display alert message displayAlertMessage(userMessage: "Passwords do not match.") return; } // // Here is where we need some guidance re saving textfield user inputs // // Store data, refer to Login for post request to Firebase Auth.auth().createUser(withEmail: email!, password: password!, completion: { (user, error) in if error != nil{ print(error!) return } guard let uid = user?.uid else{ return } let userReference = self.databaseRef.child("users").child(uid) let values = ["email": email, "phone": phone] userReference.updateChildValues(values , withCompletionBlock: { (error, ref) in if error != nil{ print(error!) return } self.performSegue(withIdentifier: "registrationSegue", sender: nil) }) }) // Display alert message with confirmation // var myAlert = UIAlertController(title:"Alert", message:"Registration is successful.", preferredStyle:UIAlertControllerStyle.alert); // // let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ // action in // self.dismiss(animated: true, completion:nil); // } // myAlert.addAction(okAction); // self.present(myAlert, animated:true, completion:nil); } } add error handling for same email registration // // RegistrationPageViewController.swift // Latr // // Created by Apprentice on 7/8/17. // Copyright © 2017 JackHowa. All rights reserved. // import UIKit import Firebase // need db for specifying the db call import FirebaseDatabase import FirebaseAuth class RegistrationPageViewController: UIViewController { let databaseRef = Database.database().reference(fromURL: "https://snapchat-f15b6.firebaseio.com") @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var userEmailTextField: UITextField! @IBOutlet weak var userPhoneTextField: UITextField! @IBOutlet weak var userPasswordTextField: UITextField! @IBOutlet weak var userConfirmPasswordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func displayAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title:"OK", style: UIAlertActionStyle.default, handler:nil); myAlert.addAction(okAction); self.present(myAlert, animated:true, completion:nil); } @IBAction func registerButtonTapped(_ sender: Any) { let user = "" // let name = userNameTextField.text; let email = userEmailTextField.text; let phone = userPhoneTextField.text; let password = userPasswordTextField.text; let confirmPassword = userConfirmPasswordTextField.text; // Check for empty fields if(email!.isEmpty || password!.isEmpty || confirmPassword!.isEmpty) { // Display alert message displayAlertMessage(userMessage: "Email, Password, & Confirmed Password fields are required.") return; } // Check if passwords match if(password != confirmPassword) { // Display alert message displayAlertMessage(userMessage: "Account already exists. Try your best to login.") return; } // // Here is where we need some guidance re saving textfield user inputs // // Store data, refer to Login for post request to Firebase Auth.auth().createUser(withEmail: email!, password: password!, completion: { (user, error) in if error != nil{ self.displayAlertMessage(userMessage: "Account was not created properly.") print(error!) return } guard let uid = user?.uid else{ return } let userReference = self.databaseRef.child("users").child(uid) let values = ["email": email, "phone": phone] userReference.updateChildValues(values , withCompletionBlock: { (error, ref) in if error != nil{ print(error!) return } self.performSegue(withIdentifier: "registrationSegue", sender: nil) }) }) } }
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Starscream import Freddy import RestKit internal class SpeechToTextSocket { private(set) internal var results = SpeechRecognitionResults() private(set) internal var state: SpeechToTextState = .Disconnected internal var onConnect: (Void -> Void)? = nil internal var onListening: (Void -> Void)? = nil internal var onResults: (SpeechRecognitionResults -> Void)? = nil internal var onError: (NSError -> Void)? = nil internal var onDisconnect: (Void -> Void)? = nil private let socket: WebSocket private let queue = NSOperationQueue() private let restToken: RestToken private var tokenRefreshes = 0 private let maxTokenRefreshes = 1 private let userAgent = buildUserAgent("watson-apis-ios-sdk/0.7.0 SpeechToTextV1") private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1" internal init( username: String, password: String, model: String?, learningOptOut: Bool?, serviceURL: String, tokenURL: String, websocketsURL: String) { // initialize authentication token let tokenURL = tokenURL + "?url=" + serviceURL restToken = RestToken(tokenURL: tokenURL, username: username, password: password) // build url with options let url = SpeechToTextSocket.buildURL(websocketsURL, model: model, learningOptOut: learningOptOut)! // initialize socket socket = WebSocket(url: url) socket.delegate = self // configure operation queue queue.maxConcurrentOperationCount = 1 queue.suspended = true } internal func connect() { // ensure the socket is not already connected guard state == .Disconnected || state == .Connecting else { return } // flush operation queue if state == .Disconnected { queue.cancelAllOperations() } // update state state = .Connecting // restrict the number of retries guard tokenRefreshes <= maxTokenRefreshes else { let failureReason = "Invalid HTTP upgrade. Check credentials?" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "WebSocket", code: 400, userInfo: userInfo) onError?(error) return } // refresh token, if necessary guard let token = restToken.token else { restToken.refreshToken(onError) { self.tokenRefreshes += 1 self.connect() } return } // connect with token socket.headers["X-Watson-Authorization-Token"] = token socket.headers["User-Agent"] = userAgent socket.connect() } internal func writeStart(settings: RecognitionSettings) { guard state != .Disconnected else { return } guard let start = try? settings.toJSON().serializeString() else { return } queue.addOperationWithBlock { self.socket.writeString(start) self.results = SpeechRecognitionResults() if self.state != .Disconnected { self.state = .Listening self.onListening?() } } } internal func writeAudio(audio: NSData) { guard state != .Disconnected else { return } queue.addOperationWithBlock { self.socket.writeData(audio) if self.state == .Listening { self.state = .SentAudio } } } internal func writeStop() { guard state != .Disconnected else { return } guard let stop = try? RecognitionStop().toJSON().serializeString() else { return } queue.addOperationWithBlock { self.socket.writeString(stop) } } internal func writeNop() { guard state != .Disconnected else { return } let nop = "{\"action\": \"no-op\"}" queue.addOperationWithBlock { self.socket.writeString(nop) } } internal func waitForResults() { queue.addOperationWithBlock { switch self.state { case .Connecting, .Connected, .Listening, .Disconnected: return // no results to wait for case .SentAudio, .Transcribing: self.queue.suspended = true let onListeningCache = self.onListening self.onListening = { self.onListening = onListeningCache self.queue.suspended = false } } } } internal func disconnect(forceTimeout: NSTimeInterval? = nil) { queue.addOperationWithBlock { self.queue.suspended = true self.queue.cancelAllOperations() self.socket.disconnect(forceTimeout: forceTimeout) } } private static func buildURL(url: String, model: String?, learningOptOut: Bool?) -> NSURL? { var queryParameters = [NSURLQueryItem]() if let model = model { queryParameters.append(NSURLQueryItem(name: "model", value: model)) } if let learningOptOut = learningOptOut { let value = "\(learningOptOut)" queryParameters.append(NSURLQueryItem(name: "x-watson-learning-opt-out", value: value)) } let urlComponents = NSURLComponents(string: url) urlComponents?.queryItems = queryParameters return urlComponents?.URL } private func onStateMessage(state: RecognitionState) { if state.state == "listening" && self.state == .Transcribing { self.state = .Listening onListening?() } } private func onResultsMessage(wrapper: SpeechRecognitionEvent) { state = .Transcribing results.addResults(wrapper) onResults?(results) } private func onErrorMessage(error: String) { let failureReason = error let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) onError?(error) } private func isAuthenticationFailure(error: NSError) -> Bool { guard let description = error.userInfo[NSLocalizedDescriptionKey] as? String else { return false } let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 400) let matchesDescription = (description == "Invalid HTTP upgrade") if matchesDomain && matchesCode && matchesDescription { return true } return false } private func isNormalDisconnect(error: NSError) -> Bool { guard let description = error.userInfo[NSLocalizedDescriptionKey] as? String else { return false } let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 1000) let matchesDescription = (description == "connection closed by server") if matchesDomain && matchesCode && matchesDescription { return true } return false } } // MARK: - WebSocket Delegate extension SpeechToTextSocket: WebSocketDelegate { internal func websocketDidConnect(socket: WebSocket) { state = .Connected tokenRefreshes = 0 queue.suspended = false results = SpeechRecognitionResults() onConnect?() } internal func websocketDidReceiveData(socket: WebSocket, data: NSData) { return // should not receive any binary data from the service } internal func websocketDidReceiveMessage(socket: WebSocket, text: String) { guard let json = try? JSON(jsonString: text) else { return } if let state = try? json.decode(type: RecognitionState.self) { onStateMessage(state) } if let results = try? json.decode(type: SpeechRecognitionEvent.self) { onResultsMessage(results) } if let error = try? json.string("error") { onErrorMessage(error) } } internal func websocketDidDisconnect(socket: WebSocket, error: NSError?) { state = .Disconnected guard let error = error else { onDisconnect?() return } if isNormalDisconnect(error) { onDisconnect?() return } if isAuthenticationFailure(error) { restToken.refreshToken(onError) { self.tokenRefreshes += 1 self.connect() } return } onError?(error) onDisconnect?() } } Suspend operation queue when disconnected by Speech to Text service /** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Starscream import Freddy import RestKit internal class SpeechToTextSocket { private(set) internal var results = SpeechRecognitionResults() private(set) internal var state: SpeechToTextState = .Disconnected internal var onConnect: (Void -> Void)? = nil internal var onListening: (Void -> Void)? = nil internal var onResults: (SpeechRecognitionResults -> Void)? = nil internal var onError: (NSError -> Void)? = nil internal var onDisconnect: (Void -> Void)? = nil private let socket: WebSocket private let queue = NSOperationQueue() private let restToken: RestToken private var tokenRefreshes = 0 private let maxTokenRefreshes = 1 private let userAgent = buildUserAgent("watson-apis-ios-sdk/0.7.0 SpeechToTextV1") private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1" internal init( username: String, password: String, model: String?, learningOptOut: Bool?, serviceURL: String, tokenURL: String, websocketsURL: String) { // initialize authentication token let tokenURL = tokenURL + "?url=" + serviceURL restToken = RestToken(tokenURL: tokenURL, username: username, password: password) // build url with options let url = SpeechToTextSocket.buildURL(websocketsURL, model: model, learningOptOut: learningOptOut)! // initialize socket socket = WebSocket(url: url) socket.delegate = self // configure operation queue queue.maxConcurrentOperationCount = 1 queue.suspended = true } internal func connect() { // ensure the socket is not already connected guard state == .Disconnected || state == .Connecting else { return } // flush operation queue if state == .Disconnected { queue.cancelAllOperations() } // update state state = .Connecting // restrict the number of retries guard tokenRefreshes <= maxTokenRefreshes else { let failureReason = "Invalid HTTP upgrade. Check credentials?" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "WebSocket", code: 400, userInfo: userInfo) onError?(error) return } // refresh token, if necessary guard let token = restToken.token else { restToken.refreshToken(onError) { self.tokenRefreshes += 1 self.connect() } return } // connect with token socket.headers["X-Watson-Authorization-Token"] = token socket.headers["User-Agent"] = userAgent socket.connect() } internal func writeStart(settings: RecognitionSettings) { guard state != .Disconnected else { return } guard let start = try? settings.toJSON().serializeString() else { return } queue.addOperationWithBlock { self.socket.writeString(start) self.results = SpeechRecognitionResults() if self.state != .Disconnected { self.state = .Listening self.onListening?() } } } internal func writeAudio(audio: NSData) { guard state != .Disconnected else { return } queue.addOperationWithBlock { self.socket.writeData(audio) if self.state == .Listening { self.state = .SentAudio } } } internal func writeStop() { guard state != .Disconnected else { return } guard let stop = try? RecognitionStop().toJSON().serializeString() else { return } queue.addOperationWithBlock { self.socket.writeString(stop) } } internal func writeNop() { guard state != .Disconnected else { return } let nop = "{\"action\": \"no-op\"}" queue.addOperationWithBlock { self.socket.writeString(nop) } } internal func waitForResults() { queue.addOperationWithBlock { switch self.state { case .Connecting, .Connected, .Listening, .Disconnected: return // no results to wait for case .SentAudio, .Transcribing: self.queue.suspended = true let onListeningCache = self.onListening self.onListening = { self.onListening = onListeningCache self.queue.suspended = false } } } } internal func disconnect(forceTimeout: NSTimeInterval? = nil) { queue.addOperationWithBlock { self.queue.suspended = true self.queue.cancelAllOperations() self.socket.disconnect(forceTimeout: forceTimeout) } } private static func buildURL(url: String, model: String?, learningOptOut: Bool?) -> NSURL? { var queryParameters = [NSURLQueryItem]() if let model = model { queryParameters.append(NSURLQueryItem(name: "model", value: model)) } if let learningOptOut = learningOptOut { let value = "\(learningOptOut)" queryParameters.append(NSURLQueryItem(name: "x-watson-learning-opt-out", value: value)) } let urlComponents = NSURLComponents(string: url) urlComponents?.queryItems = queryParameters return urlComponents?.URL } private func onStateMessage(state: RecognitionState) { if state.state == "listening" && self.state == .Transcribing { self.state = .Listening onListening?() } } private func onResultsMessage(wrapper: SpeechRecognitionEvent) { state = .Transcribing results.addResults(wrapper) onResults?(results) } private func onErrorMessage(error: String) { let failureReason = error let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) onError?(error) } private func isAuthenticationFailure(error: NSError) -> Bool { guard let description = error.userInfo[NSLocalizedDescriptionKey] as? String else { return false } let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 400) let matchesDescription = (description == "Invalid HTTP upgrade") if matchesDomain && matchesCode && matchesDescription { return true } return false } private func isNormalDisconnect(error: NSError) -> Bool { guard let description = error.userInfo[NSLocalizedDescriptionKey] as? String else { return false } let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 1000) let matchesDescription = (description == "connection closed by server") if matchesDomain && matchesCode && matchesDescription { return true } return false } } // MARK: - WebSocket Delegate extension SpeechToTextSocket: WebSocketDelegate { internal func websocketDidConnect(socket: WebSocket) { state = .Connected tokenRefreshes = 0 queue.suspended = false results = SpeechRecognitionResults() onConnect?() } internal func websocketDidReceiveData(socket: WebSocket, data: NSData) { return // should not receive any binary data from the service } internal func websocketDidReceiveMessage(socket: WebSocket, text: String) { guard let json = try? JSON(jsonString: text) else { return } if let state = try? json.decode(type: RecognitionState.self) { onStateMessage(state) } if let results = try? json.decode(type: SpeechRecognitionEvent.self) { onResultsMessage(results) } if let error = try? json.string("error") { onErrorMessage(error) } } internal func websocketDidDisconnect(socket: WebSocket, error: NSError?) { state = .Disconnected queue.suspended = true guard let error = error else { onDisconnect?() return } if isNormalDisconnect(error) { onDisconnect?() return } if isAuthenticationFailure(error) { restToken.refreshToken(onError) { self.tokenRefreshes += 1 self.connect() } return } onError?(error) onDisconnect?() } }
// // Rule.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public protocol OptInRule {} public protocol Rule { init() // Rules need to be able to be initialized with default values static var description: RuleDescription { get } func validateFile(file: File) -> [StyleViolation] } extension Rule { func isEqualTo(rule: Rule) -> Bool { switch (self, rule) { case (let rule1 as ConfigurableRule, let rule2 as ConfigurableRule): return rule1.isEqualTo(rule2) default: return self.dynamicType.description == rule.dynamicType.description } } } public protocol ConfigurableRule: Rule { init?(config: AnyObject) func isEqualTo(rule: ConfigurableRule) -> Bool } public protocol ViolationLevelRule: ConfigurableRule { var warning: RuleParameter<Int> { get set } var error: RuleParameter<Int> { get set } } public protocol CorrectableRule: Rule { func correctFile(file: File) -> [Correction] } // MARK: - ViolationLevelRule conformance to ConfigurableRule public extension ViolationLevelRule { public init?(config: AnyObject) { self.init() if let config = [Int].arrayOf(config) where config.count > 0 { warning = RuleParameter(severity: .Warning, value: config[0]) if config.count > 1 { error = RuleParameter(severity: .Error, value: config[1]) } } else if let config = config as? [String: AnyObject] { if let warningNumber = config["warning"] as? Int { warning = RuleParameter(severity: .Warning, value: warningNumber) } if let errorNumber = config["error"] as? Int { error = RuleParameter(severity: .Error, value: errorNumber) } } else { return nil } } public func isEqualTo(rule: ConfigurableRule) -> Bool { if let rule = rule as? Self { return warning == rule.warning && error == rule.error } return false } } // MARK: - == Implementations public func == (lhs: [Rule], rhs: [Rule]) -> Bool { if lhs.count == rhs.count { return zip(lhs, rhs).map { $0.isEqualTo($1) }.reduce(true) { $0 && $1 } } return false } Switched out count > 0 with !isEmpty. // // Rule.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public protocol OptInRule {} public protocol Rule { init() // Rules need to be able to be initialized with default values static var description: RuleDescription { get } func validateFile(file: File) -> [StyleViolation] } extension Rule { func isEqualTo(rule: Rule) -> Bool { switch (self, rule) { case (let rule1 as ConfigurableRule, let rule2 as ConfigurableRule): return rule1.isEqualTo(rule2) default: return self.dynamicType.description == rule.dynamicType.description } } } public protocol ConfigurableRule: Rule { init?(config: AnyObject) func isEqualTo(rule: ConfigurableRule) -> Bool } public protocol ViolationLevelRule: ConfigurableRule { var warning: RuleParameter<Int> { get set } var error: RuleParameter<Int> { get set } } public protocol CorrectableRule: Rule { func correctFile(file: File) -> [Correction] } // MARK: - ViolationLevelRule conformance to ConfigurableRule public extension ViolationLevelRule { public init?(config: AnyObject) { self.init() if let config = [Int].arrayOf(config) where !config.isEmpty { warning = RuleParameter(severity: .Warning, value: config[0]) if config.count > 1 { error = RuleParameter(severity: .Error, value: config[1]) } } else if let config = config as? [String: AnyObject] { if let warningNumber = config["warning"] as? Int { warning = RuleParameter(severity: .Warning, value: warningNumber) } if let errorNumber = config["error"] as? Int { error = RuleParameter(severity: .Error, value: errorNumber) } } else { return nil } } public func isEqualTo(rule: ConfigurableRule) -> Bool { if let rule = rule as? Self { return warning == rule.warning && error == rule.error } return false } } // MARK: - == Implementations public func == (lhs: [Rule], rhs: [Rule]) -> Bool { if lhs.count == rhs.count { return zip(lhs, rhs).map { $0.isEqualTo($1) }.reduce(true) { $0 && $1 } } return false }
// // UserInteractionFunctions.swift // Pods // // Created by Jay Thomas on 2016-05-12. // // extension JTAppleCalendarView { /// Returns the cellStatus of a date that is visible on the screen. If the row and column for the date cannot be found, then nil is returned /// - Paramater row: Int row of the date to find /// - Paramater column: Int column of the date to find /// - returns: /// - CellState: The state of the found cell public func cellStatusForDateAtRow(row: Int, column: Int) -> CellState? { if // the row or column falls within an invalid range row < 0 || row >= cachedConfiguration.numberOfRows || column < 0 || column >= MAX_NUMBER_OF_DAYS_IN_WEEK { return nil } let Offset: Int let convertedRow: Int let convertedSection: Int if direction == .Horizontal { Offset = Int(round(calendarView.contentOffset.x / (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).itemSize.width)) convertedRow = (row * MAX_NUMBER_OF_DAYS_IN_WEEK) + ((column + Offset) % MAX_NUMBER_OF_DAYS_IN_WEEK) convertedSection = (Offset + column) / MAX_NUMBER_OF_DAYS_IN_WEEK } else { Offset = Int(round(calendarView.contentOffset.y / (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).itemSize.height)) convertedRow = ((row * MAX_NUMBER_OF_DAYS_IN_WEEK) + column + (Offset * MAX_NUMBER_OF_DAYS_IN_WEEK)) % (MAX_NUMBER_OF_DAYS_IN_WEEK * cachedConfiguration.numberOfRows) convertedSection = (Offset + row) / cachedConfiguration.numberOfRows } let indexPathToFind = NSIndexPath(forItem: convertedRow, inSection: convertedSection) if let date = dateFromPath(indexPathToFind) { let stateOfCell = cellStateFromIndexPath(indexPathToFind, withDate: date) return stateOfCell } return nil } /// Returns the cell status for a given date /// - Parameter: date Date of the cell you which to find /// - returns: /// - CellState: The state of the found cell public func cellStatusForDate(date: NSDate)-> CellState? { // validate the path let paths = pathsFromDates([date]) if paths.count < 1 { return nil } let cell = calendarView.cellForItemAtIndexPath(paths[0]) as? JTAppleDayCell let stateOfCell = cellStateFromIndexPath(paths[0], withDate: date, cell: cell) return stateOfCell } /// Returns the calendar view's current section boundary dates. /// - returns: /// - startDate: The start date of the current section /// - endDate: The end date of the current section public func currentCalendarDateSegment() -> (startDate: NSDate, endDate: NSDate) { guard let dateSegment = dateFromSection(currentSectionPage) else { assert(false, "Error in currentCalendarDateSegment method. Report this issue to Jay on github.") return (NSDate(), NSDate()) } return dateSegment } /// Let's the calendar know which cell xib to use for the displaying of it's date-cells. /// - Parameter name: The name of the xib of your cell design public func registerCellViewXib(fileName name: String) { cellViewSource = JTAppleCalendarViewSource.fromXib(name) } /// Let's the calendar know which cell class to use for the displaying of it's date-cells. /// - Parameter name: The class name of your cell design public func registerCellViewClass(fileName name: String) { cellViewSource = JTAppleCalendarViewSource.fromClassName(name) } /// Let's the calendar know which cell class to use for the displaying of it's date-cells. /// - Parameter name: The type of your cell design public func registerCellViewClass(cellClass cellClass: AnyClass) { cellViewSource = JTAppleCalendarViewSource.fromType(cellClass) } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewXibs(fileNames headerViewXibNames: [String]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for headerViewXibName in headerViewXibNames { registeredHeaderViews.append(JTAppleCalendarViewSource.fromXib(headerViewXibName)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewXibName) } } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewClass(fileNames headerViewClassNames: [String]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for headerViewClassName in headerViewClassNames { registeredHeaderViews.append(JTAppleCalendarViewSource.fromClassName(headerViewClassName)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewClassName) } } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewClass(headerClass headerViewClasses: [AnyClass]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for aClass in headerViewClasses { registeredHeaderViews.append(JTAppleCalendarViewSource.fromType(aClass)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: aClass.description()) } } /// Reloads the data on the calendar view. Scroll delegates are not triggered with this function. public func reloadData(withAnchorDate date:NSDate? = nil, withAnimation animation: Bool = false, completionHandler: (()->Void)? = nil) { reloadData(checkDelegateDataSource: true, withAnchorDate: date, withAnimation: animation, completionHandler: completionHandler) } /// Reload the date of specified date-cells on the calendar-view /// - Parameter dates: Date-cells with these specified dates will be reloaded public func reloadDates(dates: [NSDate]) { batchReloadIndexPaths(pathsFromDates(dates)) } /// Select a date-cell range /// - Parameter startDate: Date to start the selection from /// - Parameter endDate: Date to end the selection from /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(from startDate:NSDate, to endDate:NSDate, triggerSelectionDelegate: Bool = true) { selectDates(generateDateRange(from: startDate, to: endDate), triggerSelectionDelegate: triggerSelectionDelegate) } /// Select a date-cells /// - Parameter date: The date-cell with this date will be selected /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(dates: [NSDate], triggerSelectionDelegate: Bool = true) { var allIndexPathsToReload: [NSIndexPath] = [] var validDatesToSelect = dates // If user is trying to select multiple dates with multiselection disabled, then only select the last object if !calendarView.allowsMultipleSelection && dates.count > 0 { validDatesToSelect = [dates.last!] } for date in validDatesToSelect { let components = self.calendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = self.calendar.dateFromComponents(components)! // If the date is not within valid boundaries, then exit if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { continue } let pathFromDates = self.pathsFromDates([date]) // If the date path youre searching for, doesnt exist, then return if pathFromDates.count < 0 { continue } let sectionIndexPath = pathFromDates[0] let selectTheDate = { self.calendarView.selectItemAtIndexPath(sectionIndexPath, animated: false, scrollPosition: .None) // If triggereing is enabled, then let their delegate handle the reloading of view, else we will reload the data if triggerSelectionDelegate { self.collectionView(self.calendarView, didSelectItemAtIndexPath: sectionIndexPath) } else { // Although we do not want the delegate triggered, we still want counterpart cells to be selected // Because there is no triggering of the delegate, the cell will not be added to selection and it will not be reloaded. We need to do this here self.addCellToSelectedSetIfUnselected(sectionIndexPath, date: date) allIndexPathsToReload.append(sectionIndexPath) let cellState = self.cellStateFromIndexPath(sectionIndexPath, withDate: date) if let aSelectedCounterPartIndexPath = self.selectCounterPartCellIndexPathIfExists(sectionIndexPath, date: date, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then it will also need to be reloaded allIndexPathsToReload.append(aSelectedCounterPartIndexPath) } } } let deSelectTheDate = { (oldIndexPath: NSIndexPath) -> Void in if !allIndexPathsToReload.contains(oldIndexPath) { allIndexPathsToReload.append(oldIndexPath) } // To avoid adding the same indexPath twice. if let index = self.theSelectedIndexPaths.indexOf(oldIndexPath) { let oldDate = self.theSelectedDates[index] self.calendarView.deselectItemAtIndexPath(oldIndexPath, animated: false) self.theSelectedIndexPaths.removeAtIndex(index) self.theSelectedDates.removeAtIndex(index) // If delegate triggering is enabled, let the delegate function handle the cell if triggerSelectionDelegate { self.collectionView(self.calendarView, didDeselectItemAtIndexPath: oldIndexPath) } else { // Although we do not want the delegate triggered, we still want counterpart cells to be deselected let cellState = self.cellStateFromIndexPath(oldIndexPath, withDate: oldDate) if let anUnselectedCounterPartIndexPath = self.deselectCounterPartCellIndexPath(oldIndexPath, date: oldDate, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then it will also need to be reloaded allIndexPathsToReload.append(anUnselectedCounterPartIndexPath) } } } } // Remove old selections if self.calendarView.allowsMultipleSelection == false { // If single selection is ON let selectedIndexPaths = self.theSelectedIndexPaths // made a copy because the array is about to be mutated for indexPath in selectedIndexPaths { if indexPath != sectionIndexPath { deSelectTheDate(indexPath) } } // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } else { // If multiple selection is on. Multiple selection behaves differently to singleselection. It behaves like a toggle. if self.theSelectedIndexPaths.contains(sectionIndexPath) { // If this cell is already selected, then deselect it deSelectTheDate(sectionIndexPath) } else { // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } } } // If triggering was false, although the selectDelegates weren't called, we do want the cell refreshed. Reload to call itemAtIndexPath if triggerSelectionDelegate == false && allIndexPathsToReload.count > 0 { delayRunOnMainThread(0.0) { self.batchReloadIndexPaths(allIndexPathsToReload) } } } /// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToNextSegment(triggerScrollToDateDelegate: Bool = false, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage + 1 if page < monthInfo.count { scrollToSection(page, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, completionHandler: completionHandler) } } /// Scrolls the calendar view to the previous section view. It will execute a completion handler at the end of scroll animation if provided. /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToPreviousSegment(triggerScrollToDateDelegate: Bool = false, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage - 1 if page > -1 { scrollToSection(page, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, completionHandler: completionHandler) } } /// Scrolls the calendar view to the start of a section view containing a specified date. /// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Paramater preferredScrollPositionIndex: Integer indicating the end scroll position on the screen. This value indicates column number for Horizontal scrolling and row number for a vertical scrolling calendar /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToDate(date: NSDate, triggerScrollToDateDelegate: Bool = true, animateScroll: Bool = true, preferredScrollPosition: UICollectionViewScrollPosition? = nil, completionHandler:(()->Void)? = nil) { self.triggerScrollToDateDelegate = triggerScrollToDateDelegate let components = calendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = calendar.dateFromComponents(components)! scrollInProgress = true delayRunOnMainThread(0.0, closure: { // This part should be inside the mainRunLoop if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { self.scrollInProgress = false return } let retrievedPathsFromDates = self.pathsFromDates([date]) if retrievedPathsFromDates.count > 0 { let sectionIndexPath = self.pathsFromDates([date])[0] var position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top if !self.pagingEnabled { if let validPosition:UICollectionViewScrollPosition = preferredScrollPosition { if self.direction == .Horizontal { if validPosition == .Left || validPosition == .Right || validPosition == .CenteredHorizontally { position = validPosition } else { position = .Left } } else { if validPosition == .Top || validPosition == .Bottom || validPosition == .CenteredVertically { position = validPosition } else { position = .Top } } } } let scrollToIndexPath = {(iPath: NSIndexPath, withAnimation: Bool)-> Void in if let validCompletionHandler = completionHandler { self.delayedExecutionClosure.append(validCompletionHandler) } // regular movement self.calendarView.scrollToItemAtIndexPath(iPath, atScrollPosition: position, animated: animateScroll) if animateScroll { if let check = self.calendarOffsetIsAlreadyAtScrollPosition(forIndexPath: iPath) where check == true { self.scrollViewDidEndScrollingAnimation(self.calendarView) self.scrollInProgress = false return } } } if self.pagingEnabled { if self.registeredHeaderViews.count > 0 { // If both paging and header is on, then scroll to the actual date // If direction is vertical and user has a custom size that is at least the size of the collectionview. // If this check is not done, it will scroll to header, and have white space at bottom because view is smaller due to small custom user itemSize if self.direction == .Vertical && (self.calendarView.collectionViewLayout as! JTAppleCalendarLayout).sizeOfSection(sectionIndexPath.section) >= self.calendarView.frame.height { self.scrollToHeaderInSection(sectionIndexPath.section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: animateScroll, completionHandler: completionHandler) return } else { scrollToIndexPath(NSIndexPath(forItem: 0, inSection: sectionIndexPath.section), animateScroll) } } else { // If paging is on and header is off, then scroll to the start date in section scrollToIndexPath(NSIndexPath(forItem: 0, inSection: sectionIndexPath.section), animateScroll) } } else { // If paging is off, then scroll to the actual date in the section scrollToIndexPath(sectionIndexPath, animateScroll) } // Jt101 put this into a function to reduce code between this and the scroll to header function delayRunOnMainThread(0.0, closure: { if !animateScroll { self.scrollViewDidEndScrollingAnimation(self.calendarView) self.scrollInProgress = false } }) } }) } /// Scrolls the calendar view to the start of a section view header. If the calendar has no headers registered, then this function does nothing /// - Paramater date: The calendar view will scroll to the header of a this provided date public func scrollToHeaderForDate(date: NSDate, triggerScrollToDateDelegate: Bool = false, withAnimation animation: Bool = false, completionHandler: (()->Void)? = nil) { let path = pathsFromDates([date]) // Return if date was incalid and no path was returned if path.count < 1 { return } scrollToHeaderInSection(path[0].section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: animation, completionHandler: completionHandler) } /// Generates a range of dates from from a startDate to an endDate you provide /// Parameter startDate: Start date to generate dates from /// Parameter endDate: End date to generate dates to /// returns: /// - An array of the successfully generated dates public func generateDateRange(from startDate: NSDate, to endDate:NSDate)-> [NSDate] { if startDate > endDate { return [] } var returnDates: [NSDate] = [] var currentDate = startDate repeat { returnDates.append(currentDate) currentDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: currentDate, options: NSCalendarOptions.MatchNextTime)! } while currentDate <= endDate return returnDates } } Fixed: reset scrollInProgress bool in no dates paths are found. // // UserInteractionFunctions.swift // Pods // // Created by Jay Thomas on 2016-05-12. // // extension JTAppleCalendarView { /// Returns the cellStatus of a date that is visible on the screen. If the row and column for the date cannot be found, then nil is returned /// - Paramater row: Int row of the date to find /// - Paramater column: Int column of the date to find /// - returns: /// - CellState: The state of the found cell public func cellStatusForDateAtRow(row: Int, column: Int) -> CellState? { if // the row or column falls within an invalid range row < 0 || row >= cachedConfiguration.numberOfRows || column < 0 || column >= MAX_NUMBER_OF_DAYS_IN_WEEK { return nil } let Offset: Int let convertedRow: Int let convertedSection: Int if direction == .Horizontal { Offset = Int(round(calendarView.contentOffset.x / (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).itemSize.width)) convertedRow = (row * MAX_NUMBER_OF_DAYS_IN_WEEK) + ((column + Offset) % MAX_NUMBER_OF_DAYS_IN_WEEK) convertedSection = (Offset + column) / MAX_NUMBER_OF_DAYS_IN_WEEK } else { Offset = Int(round(calendarView.contentOffset.y / (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).itemSize.height)) convertedRow = ((row * MAX_NUMBER_OF_DAYS_IN_WEEK) + column + (Offset * MAX_NUMBER_OF_DAYS_IN_WEEK)) % (MAX_NUMBER_OF_DAYS_IN_WEEK * cachedConfiguration.numberOfRows) convertedSection = (Offset + row) / cachedConfiguration.numberOfRows } let indexPathToFind = NSIndexPath(forItem: convertedRow, inSection: convertedSection) if let date = dateFromPath(indexPathToFind) { let stateOfCell = cellStateFromIndexPath(indexPathToFind, withDate: date) return stateOfCell } return nil } /// Returns the cell status for a given date /// - Parameter: date Date of the cell you which to find /// - returns: /// - CellState: The state of the found cell public func cellStatusForDate(date: NSDate)-> CellState? { // validate the path let paths = pathsFromDates([date]) if paths.count < 1 { return nil } let cell = calendarView.cellForItemAtIndexPath(paths[0]) as? JTAppleDayCell let stateOfCell = cellStateFromIndexPath(paths[0], withDate: date, cell: cell) return stateOfCell } /// Returns the calendar view's current section boundary dates. /// - returns: /// - startDate: The start date of the current section /// - endDate: The end date of the current section public func currentCalendarDateSegment() -> (startDate: NSDate, endDate: NSDate) { guard let dateSegment = dateFromSection(currentSectionPage) else { assert(false, "Error in currentCalendarDateSegment method. Report this issue to Jay on github.") return (NSDate(), NSDate()) } return dateSegment } /// Let's the calendar know which cell xib to use for the displaying of it's date-cells. /// - Parameter name: The name of the xib of your cell design public func registerCellViewXib(fileName name: String) { cellViewSource = JTAppleCalendarViewSource.fromXib(name) } /// Let's the calendar know which cell class to use for the displaying of it's date-cells. /// - Parameter name: The class name of your cell design public func registerCellViewClass(fileName name: String) { cellViewSource = JTAppleCalendarViewSource.fromClassName(name) } /// Let's the calendar know which cell class to use for the displaying of it's date-cells. /// - Parameter name: The type of your cell design public func registerCellViewClass(cellClass cellClass: AnyClass) { cellViewSource = JTAppleCalendarViewSource.fromType(cellClass) } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewXibs(fileNames headerViewXibNames: [String]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for headerViewXibName in headerViewXibNames { registeredHeaderViews.append(JTAppleCalendarViewSource.fromXib(headerViewXibName)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewXibName) } } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewClass(fileNames headerViewClassNames: [String]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for headerViewClassName in headerViewClassNames { registeredHeaderViews.append(JTAppleCalendarViewSource.fromClassName(headerViewClassName)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewClassName) } } /// Register header views with the calender. This needs to be done before the view can be displayed /// - Parameter fileNames: A dictionary containing [headerViewNames:HeaderviewSizes] public func registerHeaderViewClass(headerClass headerViewClasses: [AnyClass]) { registeredHeaderViews.removeAll() // remove the already registered xib files if the user re-registers again. for aClass in headerViewClasses { registeredHeaderViews.append(JTAppleCalendarViewSource.fromType(aClass)) self.calendarView.registerClass(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: aClass.description()) } } /// Reloads the data on the calendar view. Scroll delegates are not triggered with this function. public func reloadData(withAnchorDate date:NSDate? = nil, withAnimation animation: Bool = false, completionHandler: (()->Void)? = nil) { reloadData(checkDelegateDataSource: true, withAnchorDate: date, withAnimation: animation, completionHandler: completionHandler) } /// Reload the date of specified date-cells on the calendar-view /// - Parameter dates: Date-cells with these specified dates will be reloaded public func reloadDates(dates: [NSDate]) { batchReloadIndexPaths(pathsFromDates(dates)) } /// Select a date-cell range /// - Parameter startDate: Date to start the selection from /// - Parameter endDate: Date to end the selection from /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(from startDate:NSDate, to endDate:NSDate, triggerSelectionDelegate: Bool = true) { selectDates(generateDateRange(from: startDate, to: endDate), triggerSelectionDelegate: triggerSelectionDelegate) } /// Select a date-cells /// - Parameter date: The date-cell with this date will be selected /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(dates: [NSDate], triggerSelectionDelegate: Bool = true) { var allIndexPathsToReload: [NSIndexPath] = [] var validDatesToSelect = dates // If user is trying to select multiple dates with multiselection disabled, then only select the last object if !calendarView.allowsMultipleSelection && dates.count > 0 { validDatesToSelect = [dates.last!] } for date in validDatesToSelect { let components = self.calendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = self.calendar.dateFromComponents(components)! // If the date is not within valid boundaries, then exit if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { continue } let pathFromDates = self.pathsFromDates([date]) // If the date path youre searching for, doesnt exist, then return if pathFromDates.count < 0 { continue } let sectionIndexPath = pathFromDates[0] let selectTheDate = { self.calendarView.selectItemAtIndexPath(sectionIndexPath, animated: false, scrollPosition: .None) // If triggereing is enabled, then let their delegate handle the reloading of view, else we will reload the data if triggerSelectionDelegate { self.collectionView(self.calendarView, didSelectItemAtIndexPath: sectionIndexPath) } else { // Although we do not want the delegate triggered, we still want counterpart cells to be selected // Because there is no triggering of the delegate, the cell will not be added to selection and it will not be reloaded. We need to do this here self.addCellToSelectedSetIfUnselected(sectionIndexPath, date: date) allIndexPathsToReload.append(sectionIndexPath) let cellState = self.cellStateFromIndexPath(sectionIndexPath, withDate: date) if let aSelectedCounterPartIndexPath = self.selectCounterPartCellIndexPathIfExists(sectionIndexPath, date: date, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then it will also need to be reloaded allIndexPathsToReload.append(aSelectedCounterPartIndexPath) } } } let deSelectTheDate = { (oldIndexPath: NSIndexPath) -> Void in if !allIndexPathsToReload.contains(oldIndexPath) { allIndexPathsToReload.append(oldIndexPath) } // To avoid adding the same indexPath twice. if let index = self.theSelectedIndexPaths.indexOf(oldIndexPath) { let oldDate = self.theSelectedDates[index] self.calendarView.deselectItemAtIndexPath(oldIndexPath, animated: false) self.theSelectedIndexPaths.removeAtIndex(index) self.theSelectedDates.removeAtIndex(index) // If delegate triggering is enabled, let the delegate function handle the cell if triggerSelectionDelegate { self.collectionView(self.calendarView, didDeselectItemAtIndexPath: oldIndexPath) } else { // Although we do not want the delegate triggered, we still want counterpart cells to be deselected let cellState = self.cellStateFromIndexPath(oldIndexPath, withDate: oldDate) if let anUnselectedCounterPartIndexPath = self.deselectCounterPartCellIndexPath(oldIndexPath, date: oldDate, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then it will also need to be reloaded allIndexPathsToReload.append(anUnselectedCounterPartIndexPath) } } } } // Remove old selections if self.calendarView.allowsMultipleSelection == false { // If single selection is ON let selectedIndexPaths = self.theSelectedIndexPaths // made a copy because the array is about to be mutated for indexPath in selectedIndexPaths { if indexPath != sectionIndexPath { deSelectTheDate(indexPath) } } // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } else { // If multiple selection is on. Multiple selection behaves differently to singleselection. It behaves like a toggle. if self.theSelectedIndexPaths.contains(sectionIndexPath) { // If this cell is already selected, then deselect it deSelectTheDate(sectionIndexPath) } else { // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } } } // If triggering was false, although the selectDelegates weren't called, we do want the cell refreshed. Reload to call itemAtIndexPath if triggerSelectionDelegate == false && allIndexPathsToReload.count > 0 { delayRunOnMainThread(0.0) { self.batchReloadIndexPaths(allIndexPathsToReload) } } } /// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToNextSegment(triggerScrollToDateDelegate: Bool = false, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage + 1 if page < monthInfo.count { scrollToSection(page, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, completionHandler: completionHandler) } } /// Scrolls the calendar view to the previous section view. It will execute a completion handler at the end of scroll animation if provided. /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToPreviousSegment(triggerScrollToDateDelegate: Bool = false, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage - 1 if page > -1 { scrollToSection(page, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, completionHandler: completionHandler) } } /// Scrolls the calendar view to the start of a section view containing a specified date. /// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Paramater preferredScrollPositionIndex: Integer indicating the end scroll position on the screen. This value indicates column number for Horizontal scrolling and row number for a vertical scrolling calendar /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToDate(date: NSDate, triggerScrollToDateDelegate: Bool = true, animateScroll: Bool = true, preferredScrollPosition: UICollectionViewScrollPosition? = nil, completionHandler:(()->Void)? = nil) { self.triggerScrollToDateDelegate = triggerScrollToDateDelegate let components = calendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = calendar.dateFromComponents(components)! scrollInProgress = true delayRunOnMainThread(0.0, closure: { // This part should be inside the mainRunLoop if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { self.scrollInProgress = false return } let retrievedPathsFromDates = self.pathsFromDates([date]) if retrievedPathsFromDates.count > 0 { let sectionIndexPath = self.pathsFromDates([date])[0] var position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top if !self.pagingEnabled { if let validPosition:UICollectionViewScrollPosition = preferredScrollPosition { if self.direction == .Horizontal { if validPosition == .Left || validPosition == .Right || validPosition == .CenteredHorizontally { position = validPosition } else { position = .Left } } else { if validPosition == .Top || validPosition == .Bottom || validPosition == .CenteredVertically { position = validPosition } else { position = .Top } } } } let scrollToIndexPath = {(iPath: NSIndexPath, withAnimation: Bool)-> Void in if let validCompletionHandler = completionHandler { self.delayedExecutionClosure.append(validCompletionHandler) } // regular movement self.calendarView.scrollToItemAtIndexPath(iPath, atScrollPosition: position, animated: animateScroll) if animateScroll { if let check = self.calendarOffsetIsAlreadyAtScrollPosition(forIndexPath: iPath) where check == true { self.scrollViewDidEndScrollingAnimation(self.calendarView) self.scrollInProgress = false return } } } if self.pagingEnabled { if self.registeredHeaderViews.count > 0 { // If both paging and header is on, then scroll to the actual date // If direction is vertical and user has a custom size that is at least the size of the collectionview. // If this check is not done, it will scroll to header, and have white space at bottom because view is smaller due to small custom user itemSize if self.direction == .Vertical && (self.calendarView.collectionViewLayout as! JTAppleCalendarLayout).sizeOfSection(sectionIndexPath.section) >= self.calendarView.frame.height { self.scrollToHeaderInSection(sectionIndexPath.section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: animateScroll, completionHandler: completionHandler) return } else { scrollToIndexPath(NSIndexPath(forItem: 0, inSection: sectionIndexPath.section), animateScroll) } } else { // If paging is on and header is off, then scroll to the start date in section scrollToIndexPath(NSIndexPath(forItem: 0, inSection: sectionIndexPath.section), animateScroll) } } else { // If paging is off, then scroll to the actual date in the section scrollToIndexPath(sectionIndexPath, animateScroll) } // Jt101 put this into a function to reduce code between this and the scroll to header function delayRunOnMainThread(0.0, closure: { if !animateScroll { self.scrollViewDidEndScrollingAnimation(self.calendarView) self.scrollInProgress = false } }) } else { self.scrollInProgress = false } }) } /// Scrolls the calendar view to the start of a section view header. If the calendar has no headers registered, then this function does nothing /// - Paramater date: The calendar view will scroll to the header of a this provided date public func scrollToHeaderForDate(date: NSDate, triggerScrollToDateDelegate: Bool = false, withAnimation animation: Bool = false, completionHandler: (()->Void)? = nil) { let path = pathsFromDates([date]) // Return if date was incalid and no path was returned if path.count < 1 { return } scrollToHeaderInSection(path[0].section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: animation, completionHandler: completionHandler) } /// Generates a range of dates from from a startDate to an endDate you provide /// Parameter startDate: Start date to generate dates from /// Parameter endDate: End date to generate dates to /// returns: /// - An array of the successfully generated dates public func generateDateRange(from startDate: NSDate, to endDate:NSDate)-> [NSDate] { if startDate > endDate { return [] } var returnDates: [NSDate] = [] var currentDate = startDate repeat { returnDates.append(currentDate) currentDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: currentDate, options: NSCalendarOptions.MatchNextTime)! } while currentDate <= endDate return returnDates } }
// // CLLocation.swift // ZamzamKit // // Created by Basem Emara on 2/17/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // import CoreLocation public extension CLLocationCoordinate2D { /// Returns a location object. var location: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } /// Returns the distance (measured in meters) from the receiver’s location to the specified location. func distance(from coordinate: CLLocationCoordinate2D) -> CLLocationDistance { return location.distance(from: coordinate.location) } } public extension Array where Element == CLLocationCoordinate2D { /// Returns the closest coordinate to the specified location. /// /// If the sequence has no elements, returns nil. func closest(to coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? { return self.min { $0.distance(from: coordinate) < $1.distance(from: coordinate) } } /// Returns the farthest coordinate from the specified location. /// /// If the sequence has no elements, returns nil. func farthest(from coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? { return self.max { $0.distance(from: coordinate) < $1.distance(from: coordinate) } } } public extension CLLocation { struct LocationMeta: CustomStringConvertible { public var coordinates: (latitude: Double, longitude: Double)? public var locality: String? public var country: String? public var countryCode: String? public var timeZone: TimeZone? public var administrativeArea: String? public var description: String { if let l = locality, let c = (Locale.current.languageCode == "en" ? countryCode : country) { return "\(l), \(c)" } else if let l = locality { return "\(l)" } else if let c = country { return "\(c)" } return "" } } /// Retrieves location details for coordinates. /// /// - Parameter completion: Async callback with retrived location details. func geocoder(completion: @escaping (LocationMeta?) -> Void) { // Reverse geocode stored coordinates CLGeocoder().reverseGeocodeLocation(self) { placemarks, error in DispatchQueue.main.async { guard let mark = placemarks?.first, error == nil else { return completion(nil) } completion( .init( coordinates: (self.coordinate.latitude, self.coordinate.longitude), locality: mark.locality, country: mark.country, countryCode: mark.isoCountryCode, timeZone: mark.timeZone, administrativeArea: mark.administrativeArea ) ) } } } } public extension CLLocationCoordinate2D { // About 100 meters accuracy // https://gis.stackexchange.com/a/8674 private static let decimalPrecision = 3 /// Approximate comparison of coordinates rounded to 3 decimal places. static func ~~ (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) == rhs.latitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) && lhs.longitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) == rhs.longitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) } /// Approximate comparison of coordinates rounded to 3 decimal places. static func !~ (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return !(lhs ~~ rhs) } } extension CLLocationCoordinate2D: CustomStringConvertible { public var description: String { return .localizedStringWithFormat("%.2f°, %.2f°", latitude, longitude) } } Add equatable to 2D coordinate // // CLLocation.swift // ZamzamKit // // Created by Basem Emara on 2/17/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // import CoreLocation public extension CLLocationCoordinate2D { /// Returns a location object. var location: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } /// Returns the distance (measured in meters) from the receiver’s location to the specified location. func distance(from coordinate: CLLocationCoordinate2D) -> CLLocationDistance { return location.distance(from: coordinate.location) } } public extension Array where Element == CLLocationCoordinate2D { /// Returns the closest coordinate to the specified location. /// /// If the sequence has no elements, returns nil. func closest(to coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? { return self.min { $0.distance(from: coordinate) < $1.distance(from: coordinate) } } /// Returns the farthest coordinate from the specified location. /// /// If the sequence has no elements, returns nil. func farthest(from coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? { return self.max { $0.distance(from: coordinate) < $1.distance(from: coordinate) } } } public extension CLLocation { struct LocationMeta: CustomStringConvertible { public var coordinates: (latitude: Double, longitude: Double)? public var locality: String? public var country: String? public var countryCode: String? public var timeZone: TimeZone? public var administrativeArea: String? public var description: String { if let l = locality, let c = (Locale.current.languageCode == "en" ? countryCode : country) { return "\(l), \(c)" } else if let l = locality { return "\(l)" } else if let c = country { return "\(c)" } return "" } } /// Retrieves location details for coordinates. /// /// - Parameter completion: Async callback with retrived location details. func geocoder(completion: @escaping (LocationMeta?) -> Void) { // Reverse geocode stored coordinates CLGeocoder().reverseGeocodeLocation(self) { placemarks, error in DispatchQueue.main.async { guard let mark = placemarks?.first, error == nil else { return completion(nil) } completion( .init( coordinates: (self.coordinate.latitude, self.coordinate.longitude), locality: mark.locality, country: mark.country, countryCode: mark.isoCountryCode, timeZone: mark.timeZone, administrativeArea: mark.administrativeArea ) ) } } } } extension CLLocationCoordinate2D: Equatable { public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude } } public extension CLLocationCoordinate2D { // About 100 meters accuracy // https://gis.stackexchange.com/a/8674 private static let decimalPrecision = 3 /// Approximate comparison of coordinates rounded to 3 decimal places. static func ~~ (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) == rhs.latitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) && lhs.longitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) == rhs.longitude.rounded(toPlaces: CLLocationCoordinate2D.decimalPrecision) } /// Approximate comparison of coordinates rounded to 3 decimal places. static func !~ (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return !(lhs ~~ rhs) } } extension CLLocationCoordinate2D: CustomStringConvertible { public var description: String { return .localizedStringWithFormat("%.2f°, %.2f°", latitude, longitude) } }
// // FunctionalAdditions.swift // SwiftFormsApplication // // Created by Alan Skipp on 25/07/2015. // Copyright (c) 2015 Alan Skipp. All rights reserved. // // Apply a function to an Optional value, or return a default value if the Optional is .None // https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base/Data-Maybe.html#v:maybe func maybe<A,B>(@autoclosure defaultValue defaultValue:() -> B, _ opt:A?, @noescape f:A -> B) -> B { switch opt { case .None : return defaultValue() case .Some(let x) : return f(x) } } func join(s: String, _ xs: [String]) -> String { return maybe(defaultValue: "", xs.first) { dropFirst(xs).reduce($0) { acc, elem in "\(acc)\(s)\(elem)" } } } Use `dropFirst` method // // FunctionalAdditions.swift // SwiftFormsApplication // // Created by Alan Skipp on 25/07/2015. // Copyright (c) 2015 Alan Skipp. All rights reserved. // // Apply a function to an Optional value, or return a default value if the Optional is .None // https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base/Data-Maybe.html#v:maybe func maybe<A,B>(@autoclosure defaultValue defaultValue:() -> B, _ opt:A?, @noescape f:A -> B) -> B { switch opt { case .None : return defaultValue() case .Some(let x) : return f(x) } } func join(s: String, _ xs: [String]) -> String { return maybe(defaultValue: "", xs.first) { xs.dropFirst().reduce($0) { acc, elem in "\(acc)\(s)\(elem)" } } }
controller -> elevationViewController
// // ReactKit.swift // ReactKit // // Created by Yasuhiro Inami on 2014/09/11. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftTask public class Stream<T>: Task<T, Void, NSError> { public typealias Producer = Void -> Stream<T> public override var description: String { return "<\(self.name); state=\(self.state.rawValue)>" } /// /// Creates a new stream (event-delivery-pipeline over time). /// Synonym of "stream", "observable", etc. /// /// :param: initClosure Closure to define returning stream's behavior. Inside this closure, `configure.pause`/`resume`/`cancel` should capture inner logic (player) object. See also comment in `SwiftTask.Task.init()`. /// /// :returns: New Stream. /// public init(initClosure: Task<T, Void, NSError>.InitClosure) { // // NOTE: // - set `weakified = true` to avoid "(inner) player -> stream" retaining // - set `paused = true` for lazy evaluation (similar to "cold stream") // super.init(weakified: true, paused: true, initClosure: initClosure) self.name = "DefaultStream" // #if DEBUG // println("[init] \(self)") // #endif } deinit { // #if DEBUG // println("[deinit] \(self)") // #endif let cancelError = _RKError(.CancelledByDeinit, "Stream=\(self.name) is cancelled via deinit.") self.cancel(error: cancelError) } /// progress-chaining with auto-resume public func react(reactClosure: T -> Void) -> Self { let stream = super.progress { _, value in reactClosure(value) } self.resume() return self } // required (Swift compiler fails...) public override func cancel(error: NSError? = nil) -> Bool { return super.cancel(error: error) } /// Easy strong referencing by owner e.g. UIViewController holding its UI component's stream /// without explicitly defining stream as property. public func ownedBy(owner: NSObject) -> Stream<T> { var owninigStreams = owner._owninigStreams owninigStreams.append(self) owner._owninigStreams = owninigStreams return self } } /// helper method to bind downstream's `fulfill`/`reject`/`configure` handlers with upstream private func _bindToUpstream<T>(upstream: Stream<T>, fulfill: (Void -> Void)?, reject: (NSError -> Void)?, configure: TaskConfiguration?) { // // NOTE: // Bind downstream's `configure` to upstream // BEFORE performing its `progress()`/`then()`/`success()`/`failure()` // so that even when downstream **immediately finishes** on its 1st resume, // upstream can know `configure.isFinished = true` // while performing its `initClosure`. // // This is especially important for stopping immediate-infinite-sequence, // e.g. `infiniteStream.take(3)` will stop infinite-while-loop at end of 3rd iteration. // // NOTE: downstream should capture upstream if let configure = configure { let oldPause = configure.pause; configure.pause = { oldPause?(); upstream.pause(); return } let oldResume = configure.resume; configure.resume = { oldResume?(); upstream.resume(); return } let oldCancel = configure.cancel; configure.cancel = { oldCancel?(); upstream.cancel(); return } } if fulfill != nil || reject != nil { let streamName = upstream.name // fulfill/reject downstream on upstream-fulfill/reject/cancel upstream.then { value, errorInfo -> Void in if value != nil { fulfill?() return } else if let errorInfo = errorInfo { // rejected if let error = errorInfo.error { reject?(error) return } // cancelled else { let cancelError = _RKError(.CancelledByUpstream, "Stream=\(streamName) is rejected or cancelled.") reject?(cancelError) } } } } } //-------------------------------------------------- // MARK: - Init Helper /// (TODO: move to new file, but doesn't work in Swift 1.1. ERROR = ld: symbol(s) not found for architecture x86_64) //-------------------------------------------------- public extension Stream { /// creates once (progress once & fulfill) stream /// NOTE: this method can't move to other file due to Swift 1.1 public class func once(value: T) -> Stream<T> { return Stream { progress, fulfill, reject, configure in progress(value) fulfill() }.name("Stream.once") } /// creates never (no progress & fulfill & reject) stream public class func never() -> Stream<T> { return Stream { progress, fulfill, reject, configure in // do nothing }.name("Stream.never") } /// creates empty (fulfilled without any progress) stream public class func fulfilled() -> Stream<T> { return Stream { progress, fulfill, reject, configure in fulfill() }.name("Stream.fulfilled") } /// creates error (rejected) stream public class func rejected(error: NSError) -> Stream<T> { return Stream { progress, fulfill, reject, configure in reject(error) }.name("Stream.rejected") } /// /// creates stream from SequenceType (e.g. Array) and fulfills at last /// /// - e.g. Stream.sequence([1, 2, 3]) /// /// a.k.a `Rx.fromArray` /// public class func sequence<S: SequenceType where S.Generator.Element == T>(values: S) -> Stream<T> { return Stream { progress, fulfill, reject, configure in var generator = values.generate() while let value: T = generator.next() { progress(value) if configure.isFinished { break } } fulfill() }.name("Stream.sequence") } } //-------------------------------------------------- // MARK: - Single Stream Operations //-------------------------------------------------- /// useful for injecting side-effects /// a.k.a Rx.do, tap public func peek<T>(peekClosure: T -> Void)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in peekClosure(value) progress(value) } }.name("\(upstream.name)-peek") } /// creates your own customizable & method-chainable stream without writing `return Stream<U> { ... }` public func customize<T, U> (customizeClosure: (upstream: Stream<T>, progress: Stream<U>.ProgressHandler, fulfill: Stream<U>.FulfillHandler, reject: Stream<U>.RejectHandler) -> Void) (upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, nil, configure) customizeClosure(upstream: upstream, progress: progress, fulfill: fulfill, reject: reject) }.name("\(upstream.name)-customize") } // MARK: transforming /// map using newValue only public func map<T, U>(transform: T -> U)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in progress(transform(value)) } }.name("\(upstream.name)-map") } /// map using newValue only & bind to transformed Stream public func flatMap<T, U>(transform: T -> Stream<U>)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) // NOTE: each of `transformToStream()` needs to be retained outside var innerStreams: [Stream<U>] = [] upstream.react { value in let innerStream = transform(value) innerStreams += [innerStream] innerStream.react { value in progress(value) } } }.name("\(upstream.name)-flatMap") } /// map using (oldValue, newValue) public func map2<T, U>(transform2: (oldValue: T?, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { var oldValue: T? let stream = upstream |> map { (newValue: T) -> U in let mappedValue = transform2(oldValue: oldValue, newValue: newValue) oldValue = newValue return mappedValue } stream.name("\(upstream.name)-map2") return stream } // NOTE: Avoid using curried function. See comments in `startWith()`. /// map using (accumulatedValue, newValue) /// a.k.a `Rx.scan()` public func mapAccumulate<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U) -> (upstream: Stream<T>) -> Stream<U> { return { (upstream: Stream<T>) -> Stream<U> in return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var accumulatedValue: U = initialValue upstream.react { value in accumulatedValue = accumulateClosure(accumulatedValue: accumulatedValue, newValue: value) progress(accumulatedValue) } }.name("\(upstream.name)-mapAccumulate") } } public func buffer<T>(_ capacity: Int = Int.max)(upstream: Stream<T>) -> Stream<[T]> { precondition(capacity >= 0) return Stream<[T]> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var buffer: [T] = [] upstream.react { value in buffer += [value] if buffer.count >= capacity { progress(buffer) buffer = [] } }.success { _ -> Void in if buffer.count > 0 { progress(buffer) } fulfill() } }.name("\(upstream.name)-buffer") } public func bufferBy<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<[T]> { return Stream<[T]> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var buffer: [T] = [] upstream.react { value in buffer += [value] }.success { _ -> Void in progress(buffer) fulfill() } triggerStream?.react { [weak upstream] _ in if let upstream = upstream { progress(buffer) buffer = [] } }.then { [weak upstream] _ -> Void in if let upstream = upstream { progress(buffer) buffer = [] } } }.name("\(upstream.name)-bufferBy") } public func groupBy<T, Key: Hashable>(groupingClosure: T -> Key)(upstream: Stream<T>) -> Stream<(Key, Stream<T>)> { return Stream<(Key, Stream<T>)> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var buffer: [Key : (stream: Stream<T>, progressHandler: Stream<T>.ProgressHandler)] = [:] upstream.react { value in let key = groupingClosure(value) if buffer[key] == nil { var progressHandler: Stream<T>.ProgressHandler? let innerStream = Stream<T> { p, _, _, _ in progressHandler = p; // steal progressHandler return } innerStream.resume() // resume to steal `progressHandler` immediately buffer[key] = (innerStream, progressHandler!) // set innerStream progress((key, buffer[key]!.stream) as (Key, Stream<T>)) } buffer[key]!.progressHandler(value) // push value to innerStream } }.name("\(upstream.name)-groupBy") } // MARK: filtering /// filter using newValue only public func filter<T>(filterClosure: T -> Bool)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in if filterClosure(value) { progress(value) } } }.name("\(upstream.name)-filter") } /// filter using (oldValue, newValue) public func filter2<T>(filterClosure2: (oldValue: T?, newValue: T) -> Bool)(upstream: Stream<T>) -> Stream<T> { var oldValue: T? let stream = upstream |> filter { (newValue: T) -> Bool in let flag = filterClosure2(oldValue: oldValue, newValue: newValue) oldValue = newValue return flag } stream.name("\(upstream.name)-filter2") return stream } public func take<T>(maxCount: Int)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var count = 0 upstream.react { value in count++ if count < maxCount { progress(value) } else if count == maxCount { progress(value) fulfill() // successfully reached maxCount } } }.name("\(upstream.name)-take(\(maxCount))") } public func takeUntil<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in if let triggerStream = triggerStream { _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in progress(value) } let cancelError = _RKError(.CancelledByTriggerStream, "Stream=\(upstream.name) is cancelled by takeUntil(\(triggerStream.name)).") triggerStream.react { [weak upstream] _ in if let upstream_ = upstream { upstream_.cancel(error: cancelError) } }.then { [weak upstream] _ -> Void in if let upstream_ = upstream { upstream_.cancel(error: cancelError) } } } else { let cancelError = _RKError(.CancelledByTriggerStream, "Stream=\(upstream.name) is cancelled by takeUntil() with `triggerStream` already been deinited.") upstream.cancel(error: cancelError) } }.name("\(upstream.name)-takeUntil") } public func skip<T>(skipCount: Int)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var count = 0 upstream.react { value in count++ if count <= skipCount { return } progress(value) } }.name("\(upstream.name)-skip(\(skipCount))") } public func skipUntil<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var shouldSkip = true upstream.react { value in if !shouldSkip { progress(value) } } if let triggerStream = triggerStream { triggerStream.react { _ in shouldSkip = false }.then { _ -> Void in shouldSkip = false } } else { shouldSkip = false } }.name("\(upstream.name)-skipUntil") } public func sample<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var lastValue: T? upstream.react { value in lastValue = value } if let triggerStream = triggerStream { triggerStream.react { _ in if let lastValue = lastValue { progress(lastValue) } } } } } public func distinct<H: Hashable>(upstream: Stream<H>) -> Stream<H> { return Stream<H> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var usedValueHashes = Set<H>() upstream.react { value in if !usedValueHashes.contains(value) { usedValueHashes.insert(value) progress(value) } } } } // MARK: combining public func merge<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<T> { return upstream |> merge([stream]) } public func merge<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<T> { let stream = (streams + [upstream]) |> mergeInner return stream.name("\(upstream.name)-merge") } public func concat<T>(nextStream: Stream<T>)(upstream: Stream<T>) -> Stream<T> { return upstream |> concat([nextStream]) } public func concat<T>(nextStreams: [Stream<T>])(upstream: Stream<T>) -> Stream<T> { let stream = ([upstream] + nextStreams) |> concatInner return stream.name("\(upstream.name)-concat") } // // NOTE: // Avoid using curried function since `initialValue` seems to get deallocated at uncertain timing // (especially for T as value-type e.g. String, but also occurs a little in reference-type e.g. NSString). // Make sure to let `initialValue` be captured by closure explicitly. // /// `concat()` initialValue first public func startWith<T>(initialValue: T) -> (upstream: Stream<T>) -> Stream<T> { return { (upstream: Stream<T>) -> Stream<T> in precondition(upstream.state == .Paused) let stream = [Stream.once(initialValue), upstream] |> concatInner return stream.name("\(upstream.name)-startWith") } } //public func startWith<T>(initialValue: T)(upstream: Stream<T>) -> Stream<T> //{ // let stream = [Stream.once(initialValue), upstream] |> concatInner // return stream.name("\(upstream.name)-startWith") //} public func combineLatest<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<[T]> { return upstream |> combineLatest([stream]) } public func combineLatest<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<[T]> { let stream = ([upstream] + streams) |> combineLatestAll return stream.name("\(upstream.name)-combineLatest") } public func zip<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<[T]> { return upstream |> zip([stream]) } public func zip<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<[T]> { let stream = ([upstream] + streams) |> zipAll return stream.name("\(upstream.name)-zip") } // MARK: timing /// delay `progress` and `fulfill` for `timerInterval` seconds public func delay<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) upstream.react { value in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in progress(value) timerStream = nil } }.success { _ -> Void in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in fulfill() timerStream = nil } } }.name("\(upstream.name)-delay(\(timeInterval))") } /// delay `progress` and `fulfill` for `timerInterval * eachProgressCount` seconds /// (incremental delay with start at t = 0sec) public func interval<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var incInterval = 0.0 upstream.react { value in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: incInterval, repeats: false) { _ in } incInterval += timeInterval timerStream!.react { _ in progress(value) timerStream = nil } }.success { _ -> Void in incInterval -= timeInterval - 0.01 var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: incInterval, repeats: false) { _ in } timerStream!.react { _ in fulfill() timerStream = nil } } }.name("\(upstream.name)-interval(\(timeInterval))") } /// limit continuous progress (reaction) for `timeInterval` seconds when first progress is triggered /// (see also: underscore.js throttle) public func throttle<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var lastProgressDate = NSDate(timeIntervalSince1970: 0) upstream.react { value in let now = NSDate() let timeDiff = now.timeIntervalSinceDate(lastProgressDate) if timeDiff > timeInterval { lastProgressDate = now progress(value) } } }.name("\(upstream.name)-throttle(\(timeInterval))") } /// delay progress (reaction) for `timeInterval` seconds and truly invoke reaction afterward if not interrupted by continuous progress /// (see also: underscore.js debounce) public func debounce<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var timerStream: Stream<Void>? = nil // retained by upstream via upstream.react() upstream.react { value in // NOTE: overwrite to deinit & cancel old timerStream timerStream = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in progress(value) } } }.name("\(upstream.name)-debounce(\(timeInterval))") } // MARK: collecting public func reduce<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in let accumulatingStream = upstream |> mapAccumulate(initialValue, accumulateClosure) _bindToUpstream(accumulatingStream, nil, nil, configure) var lastAccValue: U = initialValue // last accumulated value accumulatingStream.react { value in lastAccValue = value }.then { value, errorInfo -> Void in if value != nil { progress(lastAccValue) fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let cancelError = _RKError(.CancelledByUpstream, "Upstream is cancelled before performing `reduce()`.") reject(cancelError) } } } }.name("\(upstream.name)-reduce") } //-------------------------------------------------- // MARK: - Array Streams Operations //-------------------------------------------------- /// Merges multiple streams into single stream. /// See also: mergeInner public func mergeAll<T>(streams: [Stream<T>]) -> Stream<T> { let stream = Stream.sequence(streams) |> mergeInner return stream.name("mergeAll") } /// /// Merges multiple streams into single stream, /// combining latest values `[T?]` as well as changed value `T` together as `([T?], T)` tuple. /// /// This is a generalized method for `Rx.merge()` and `Rx.combineLatest()`. /// public func merge2All<T>(streams: [Stream<T>]) -> Stream<(values: [T?], changedValue: T)> { return Stream { progress, fulfill, reject, configure in configure.pause = { Stream<T>.pauseAll(streams) } configure.resume = { Stream<T>.resumeAll(streams) } configure.cancel = { Stream<T>.cancelAll(streams) } var states = [T?](count: streams.count, repeatedValue: nil) for i in 0..<streams.count { let stream = streams[i] stream.react { value in states[i] = value progress(values: states, changedValue: value) }.then { value, errorInfo -> Void in if value != nil { fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `merge2All()`.") reject(error) } } } } }.name("merge2All") } public func combineLatestAll<T>(streams: [Stream<T>]) -> Stream<[T]> { let stream = merge2All(streams) |> filter { values, _ in var areAllNonNil = true for value in values { if value == nil { areAllNonNil = false break } } return areAllNonNil } |> map { values, _ in values.map { $0! } } return stream.name("combineLatestAll") } public func zipAll<T>(streams: [Stream<T>]) -> Stream<[T]> { precondition(streams.count > 1) return Stream<[T]> { progress, fulfill, reject, configure in configure.pause = { Stream<T>.pauseAll(streams) } configure.resume = { Stream<T>.resumeAll(streams) } configure.cancel = { Stream<T>.cancelAll(streams) } let streamCount = streams.count var storedValuesArray: [[T]] = [] for i in 0..<streamCount { storedValuesArray.append([]) } for i in 0..<streamCount { streams[i].react { value in storedValuesArray[i] += [value] var canProgress: Bool = true for storedValues in storedValuesArray { if storedValues.count == 0 { canProgress = false break } } if canProgress { var firstStoredValues: [T] = [] for i in 0..<streamCount { let firstStoredValue = storedValuesArray[i].removeAtIndex(0) firstStoredValues.append(firstStoredValue) } progress(firstStoredValues) } }.success { _ -> Void in fulfill() } } }.name("zipAll") } //-------------------------------------------------- // MARK: - Nested Stream Operations //-------------------------------------------------- /// /// Merges multiple streams into single stream. /// /// - e.g. `let mergedStream = [stream1, stream2, ...] |> mergeInner` /// /// NOTE: This method is conceptually equal to `streams |> merge2All(streams) |> map { $1 }`. /// public func mergeInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in // NOTE: don't bind nestedStream's fulfill with returning mergeInner-stream's fulfill _bindToUpstream(nestedStream, nil, reject, configure) nestedStream.react { (innerStream: Stream<T>) in _bindToUpstream(innerStream, nil, nil, configure) innerStream.react { value in progress(value) }.then { value, errorInfo -> Void in if value != nil { fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `mergeInner()`.") reject(error) } } } } }.name("mergeInner") } /// fixed-point combinator private func _fix<T, U>(f: (T -> U) -> T -> U) -> T -> U { return { f(_fix(f))($0) } } public func concatInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(nestedStream, nil, reject, configure) var pendingInnerStreams = [Stream<T>]() let performRecursively: Void -> Void = _fix { recurse in return { if let innerStream = pendingInnerStreams.first { if pendingInnerStreams.count == 1 { _bindToUpstream(innerStream, nil, nil, configure) innerStream.react { value in progress(value) }.success { pendingInnerStreams.removeAtIndex(0) recurse() }.failure { errorInfo -> Void in if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `concatInner()`.") reject(error) } } } } } } nestedStream.react { (innerStream: Stream<T>) in pendingInnerStreams += [innerStream] performRecursively() } }.name("concatInner") } /// uses the latest innerStream and cancels previous innerStreams /// a.k.a Rx.switchLatest public func switchLatestInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(nestedStream, nil, reject, configure) var currentInnerStream: Stream<T>? nestedStream.react { (innerStream: Stream<T>) in _bindToUpstream(innerStream, nil, nil, configure) currentInnerStream?.cancel() currentInnerStream = innerStream innerStream.react { value in progress(value) } } }.name("concatInner") } //-------------------------------------------------- // MARK: - Stream Producer Operations //-------------------------------------------------- /// /// Creates an upstream from `upstreamProducer`, resumes it (prestart), /// and caches its emitted values (`capacity` as max buffer count) for future "replay" /// when returning streamProducer creates a new stream & resumes it, /// a.k.a. Rx.replay(). /// /// NOTE: `downstream`'s `pause()`/`resume()`/`cancel()` will not affect `upstream`. /// /// :Usage: /// let cachedStreamProducer = networkStream |>> prestart(capacity: 1) /// let cachedStream1 = cachedStreamProducer() /// cachedStream1 ~> { ... } /// let cachedStream2 = cachedStreamProducer() // can produce many cached streams /// ... /// /// :param: capacity max buffer count for prestarted stream /// public func prestart<T>(capacity: Int = Int.max) -> (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer { return { (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer in var buffer = [T]() let upstream = upstreamProducer() // REACT upstream ~> { value in buffer += [value] while buffer.count > capacity { buffer.removeAtIndex(0) } } return { return Stream<T> { progress, fulfill, reject, configure in // NOTE: downstream's `configure` should not bind to upstream _bindToUpstream(upstream, fulfill, reject, nil) for b in buffer { progress(b) } upstream.react { value in progress(value) } }.name("\(upstream.name)-prestart") } } } //-------------------------------------------------- /// MARK: - Rx Semantics /// (TODO: move to new file, but doesn't work in Swift 1.1. ERROR = ld: symbol(s) not found for architecture x86_64) //-------------------------------------------------- public extension Stream { /// alias for `Stream.fulfilled()` public class func just(value: T) -> Stream<T> { return self.once(value) } /// alias for `Stream.fulfilled()` public class func empty() -> Stream<T> { return self.fulfilled() } /// alias for `Stream.rejected()` public class func error(error: NSError) -> Stream<T> { return self.rejected(error) } } /// alias for `mapAccumulate()` public func scan<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { return mapAccumulate(initialValue, accumulateClosure)(upstream: upstream) } /// alias for `prestart()` public func replay<T>(capacity: Int = Int.max) -> (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer { return prestart(capacity: capacity) } //-------------------------------------------------- // MARK: - Custom Operators // + - * / % = < > ! & | ^ ~ . //-------------------------------------------------- // MARK: |> (stream pipelining) infix operator |> { associativity left precedence 95} /// single-stream pipelining operator public func |> <T, U>(stream: Stream<T>, transform: Stream<T> -> Stream<U>) -> Stream<U> { return transform(stream) } /// array-streams pipelining operator public func |> <T, U, S: SequenceType where S.Generator.Element == Stream<T>>(streams: S, transform: S -> Stream<U>) -> Stream<U> { return transform(streams) } /// nested-streams pipelining operator public func |> <T, U, S: SequenceType where S.Generator.Element == Stream<T>>(streams: S, transform: Stream<Stream<T>> -> Stream<U>) -> Stream<U> { return transform(Stream.sequence(streams)) } /// stream-transform pipelining operator public func |> <T, U, V>(transform1: Stream<T> -> Stream<U>, transform2: Stream<U> -> Stream<V>) -> Stream<T> -> Stream<V> { return { transform2(transform1($0)) } } // MARK: |>> (streamProducer pipelining) infix operator |>> { associativity left precedence 95} /// streamProducer lifting & pipelining operator public func |>> <T, U>(streamProducer: Stream<T>.Producer, transform: Stream<T> -> Stream<U>) -> Stream<U>.Producer { return { transform(streamProducer()) } } /// streamProducer(autoclosured) lifting & pipelining operator public func |>> <T, U>(@autoclosure(escaping) streamProducer: Stream<T>.Producer, transform: Stream<T> -> Stream<U>) -> Stream<U>.Producer { return { transform(streamProducer()) } } /// streamProducer pipelining operator public func |>> <T, U>(streamProducer: Stream<T>.Producer, transform: Stream<T>.Producer -> Stream<U>.Producer) -> Stream<U>.Producer { return transform(streamProducer) } /// streamProducer(autoclosured) pipelining operator public func |>> <T, U>(@autoclosure(escaping) streamProducer: Stream<T>.Producer, transform: Stream<T>.Producer -> Stream<U>.Producer) -> Stream<U>.Producer { return transform(streamProducer) } /// streamProducer-transform pipelining operator public func |>> <T, U, V>(transform1: Stream<T>.Producer -> Stream<U>.Producer, transform2: Stream<U>.Producer -> Stream<V>.Producer) -> Stream<T>.Producer -> Stream<V>.Producer { return { transform2(transform1($0)) } } // MARK: ~> (right reacting operator) // NOTE: `infix operator ~>` is already declared in Swift //infix operator ~> { associativity left precedence 255 } /// right-closure reacting operator, i.e. `stream.react { ... }` public func ~> <T>(stream: Stream<T>, reactClosure: T -> Void) -> Stream<T> { stream.react(reactClosure) return stream } // MARK: ~> (left reacting operator) infix operator <~ { associativity right precedence 50 } /// left-closure (closure-first) reacting operator, reversing `stream.react { ... }` /// e.g. ^{ ... } <~ stream public func <~ <T>(reactClosure: T -> Void, stream: Stream<T>) -> Stream<T> { return stream ~> reactClosure } // MARK: ~>! (terminal reacting operator) infix operator ~>! { associativity left precedence 50 } /// /// terminal reacting operator, which returns synchronously-emitted last value /// to gain similar functionality as Java 8's Stream API, /// /// e.g. /// let sum = Stream.sequence([1, 2, 3]) |> reduce(0) { $0 + $1 } ~>! () /// let distinctSequence = Stream.sequence([1, 2, 2, 3]) |> distinct |> buffer() ~>! () // NOTE: use `buffer()` whenever necessary /// public func ~>! <T>(stream: Stream<T>, void: Void) -> T! { var ret: T! stream.react { value in ret = value } return ret } prefix operator ^ {} /// Objective-C like 'block operator' to let Swift compiler know closure-type at start of the line /// e.g. ^{ println($0) } <~ stream public prefix func ^ <T, U>(closure: T -> U) -> (T -> U) { return closure } prefix operator + {} /// short-living operator for stream not being retained /// e.g. ^{ println($0) } <~ +KVO.stream(obj1, "value") public prefix func + <T>(stream: Stream<T>) -> Stream<T> { var holder: Stream<T>? = stream // let stream be captured by dispatch_queue to guarantee its lifetime until next runloop dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue()) { // on main-thread holder = nil } return stream } Improve terminal reacting operator '~>!' to use as less precedence of '~>'. // // ReactKit.swift // ReactKit // // Created by Yasuhiro Inami on 2014/09/11. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftTask public class Stream<T>: Task<T, Void, NSError> { public typealias Producer = Void -> Stream<T> public override var description: String { return "<\(self.name); state=\(self.state.rawValue)>" } /// /// Creates a new stream (event-delivery-pipeline over time). /// Synonym of "stream", "observable", etc. /// /// :param: initClosure Closure to define returning stream's behavior. Inside this closure, `configure.pause`/`resume`/`cancel` should capture inner logic (player) object. See also comment in `SwiftTask.Task.init()`. /// /// :returns: New Stream. /// public init(initClosure: Task<T, Void, NSError>.InitClosure) { // // NOTE: // - set `weakified = true` to avoid "(inner) player -> stream" retaining // - set `paused = true` for lazy evaluation (similar to "cold stream") // super.init(weakified: true, paused: true, initClosure: initClosure) self.name = "DefaultStream" // #if DEBUG // println("[init] \(self)") // #endif } deinit { // #if DEBUG // println("[deinit] \(self)") // #endif let cancelError = _RKError(.CancelledByDeinit, "Stream=\(self.name) is cancelled via deinit.") self.cancel(error: cancelError) } /// progress-chaining with auto-resume public func react(reactClosure: T -> Void) -> Self { let stream = super.progress { _, value in reactClosure(value) } self.resume() return self } // required (Swift compiler fails...) public override func cancel(error: NSError? = nil) -> Bool { return super.cancel(error: error) } /// Easy strong referencing by owner e.g. UIViewController holding its UI component's stream /// without explicitly defining stream as property. public func ownedBy(owner: NSObject) -> Stream<T> { var owninigStreams = owner._owninigStreams owninigStreams.append(self) owner._owninigStreams = owninigStreams return self } } /// helper method to bind downstream's `fulfill`/`reject`/`configure` handlers with upstream private func _bindToUpstream<T>(upstream: Stream<T>, fulfill: (Void -> Void)?, reject: (NSError -> Void)?, configure: TaskConfiguration?) { // // NOTE: // Bind downstream's `configure` to upstream // BEFORE performing its `progress()`/`then()`/`success()`/`failure()` // so that even when downstream **immediately finishes** on its 1st resume, // upstream can know `configure.isFinished = true` // while performing its `initClosure`. // // This is especially important for stopping immediate-infinite-sequence, // e.g. `infiniteStream.take(3)` will stop infinite-while-loop at end of 3rd iteration. // // NOTE: downstream should capture upstream if let configure = configure { let oldPause = configure.pause; configure.pause = { oldPause?(); upstream.pause(); return } let oldResume = configure.resume; configure.resume = { oldResume?(); upstream.resume(); return } let oldCancel = configure.cancel; configure.cancel = { oldCancel?(); upstream.cancel(); return } } if fulfill != nil || reject != nil { let streamName = upstream.name // fulfill/reject downstream on upstream-fulfill/reject/cancel upstream.then { value, errorInfo -> Void in if value != nil { fulfill?() return } else if let errorInfo = errorInfo { // rejected if let error = errorInfo.error { reject?(error) return } // cancelled else { let cancelError = _RKError(.CancelledByUpstream, "Stream=\(streamName) is rejected or cancelled.") reject?(cancelError) } } } } } //-------------------------------------------------- // MARK: - Init Helper /// (TODO: move to new file, but doesn't work in Swift 1.1. ERROR = ld: symbol(s) not found for architecture x86_64) //-------------------------------------------------- public extension Stream { /// creates once (progress once & fulfill) stream /// NOTE: this method can't move to other file due to Swift 1.1 public class func once(value: T) -> Stream<T> { return Stream { progress, fulfill, reject, configure in progress(value) fulfill() }.name("Stream.once") } /// creates never (no progress & fulfill & reject) stream public class func never() -> Stream<T> { return Stream { progress, fulfill, reject, configure in // do nothing }.name("Stream.never") } /// creates empty (fulfilled without any progress) stream public class func fulfilled() -> Stream<T> { return Stream { progress, fulfill, reject, configure in fulfill() }.name("Stream.fulfilled") } /// creates error (rejected) stream public class func rejected(error: NSError) -> Stream<T> { return Stream { progress, fulfill, reject, configure in reject(error) }.name("Stream.rejected") } /// /// creates stream from SequenceType (e.g. Array) and fulfills at last /// /// - e.g. Stream.sequence([1, 2, 3]) /// /// a.k.a `Rx.fromArray` /// public class func sequence<S: SequenceType where S.Generator.Element == T>(values: S) -> Stream<T> { return Stream { progress, fulfill, reject, configure in var generator = values.generate() while let value: T = generator.next() { progress(value) if configure.isFinished { break } } fulfill() }.name("Stream.sequence") } } //-------------------------------------------------- // MARK: - Single Stream Operations //-------------------------------------------------- /// useful for injecting side-effects /// a.k.a Rx.do, tap public func peek<T>(peekClosure: T -> Void)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in peekClosure(value) progress(value) } }.name("\(upstream.name)-peek") } /// creates your own customizable & method-chainable stream without writing `return Stream<U> { ... }` public func customize<T, U> (customizeClosure: (upstream: Stream<T>, progress: Stream<U>.ProgressHandler, fulfill: Stream<U>.FulfillHandler, reject: Stream<U>.RejectHandler) -> Void) (upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, nil, configure) customizeClosure(upstream: upstream, progress: progress, fulfill: fulfill, reject: reject) }.name("\(upstream.name)-customize") } // MARK: transforming /// map using newValue only public func map<T, U>(transform: T -> U)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in progress(transform(value)) } }.name("\(upstream.name)-map") } /// map using newValue only & bind to transformed Stream public func flatMap<T, U>(transform: T -> Stream<U>)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) // NOTE: each of `transformToStream()` needs to be retained outside var innerStreams: [Stream<U>] = [] upstream.react { value in let innerStream = transform(value) innerStreams += [innerStream] innerStream.react { value in progress(value) } } }.name("\(upstream.name)-flatMap") } /// map using (oldValue, newValue) public func map2<T, U>(transform2: (oldValue: T?, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { var oldValue: T? let stream = upstream |> map { (newValue: T) -> U in let mappedValue = transform2(oldValue: oldValue, newValue: newValue) oldValue = newValue return mappedValue } stream.name("\(upstream.name)-map2") return stream } // NOTE: Avoid using curried function. See comments in `startWith()`. /// map using (accumulatedValue, newValue) /// a.k.a `Rx.scan()` public func mapAccumulate<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U) -> (upstream: Stream<T>) -> Stream<U> { return { (upstream: Stream<T>) -> Stream<U> in return Stream<U> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var accumulatedValue: U = initialValue upstream.react { value in accumulatedValue = accumulateClosure(accumulatedValue: accumulatedValue, newValue: value) progress(accumulatedValue) } }.name("\(upstream.name)-mapAccumulate") } } public func buffer<T>(_ capacity: Int = Int.max)(upstream: Stream<T>) -> Stream<[T]> { precondition(capacity >= 0) return Stream<[T]> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var buffer: [T] = [] upstream.react { value in buffer += [value] if buffer.count >= capacity { progress(buffer) buffer = [] } }.success { _ -> Void in if buffer.count > 0 { progress(buffer) } fulfill() } }.name("\(upstream.name)-buffer") } public func bufferBy<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<[T]> { return Stream<[T]> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var buffer: [T] = [] upstream.react { value in buffer += [value] }.success { _ -> Void in progress(buffer) fulfill() } triggerStream?.react { [weak upstream] _ in if let upstream = upstream { progress(buffer) buffer = [] } }.then { [weak upstream] _ -> Void in if let upstream = upstream { progress(buffer) buffer = [] } } }.name("\(upstream.name)-bufferBy") } public func groupBy<T, Key: Hashable>(groupingClosure: T -> Key)(upstream: Stream<T>) -> Stream<(Key, Stream<T>)> { return Stream<(Key, Stream<T>)> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var buffer: [Key : (stream: Stream<T>, progressHandler: Stream<T>.ProgressHandler)] = [:] upstream.react { value in let key = groupingClosure(value) if buffer[key] == nil { var progressHandler: Stream<T>.ProgressHandler? let innerStream = Stream<T> { p, _, _, _ in progressHandler = p; // steal progressHandler return } innerStream.resume() // resume to steal `progressHandler` immediately buffer[key] = (innerStream, progressHandler!) // set innerStream progress((key, buffer[key]!.stream) as (Key, Stream<T>)) } buffer[key]!.progressHandler(value) // push value to innerStream } }.name("\(upstream.name)-groupBy") } // MARK: filtering /// filter using newValue only public func filter<T>(filterClosure: T -> Bool)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in if filterClosure(value) { progress(value) } } }.name("\(upstream.name)-filter") } /// filter using (oldValue, newValue) public func filter2<T>(filterClosure2: (oldValue: T?, newValue: T) -> Bool)(upstream: Stream<T>) -> Stream<T> { var oldValue: T? let stream = upstream |> filter { (newValue: T) -> Bool in let flag = filterClosure2(oldValue: oldValue, newValue: newValue) oldValue = newValue return flag } stream.name("\(upstream.name)-filter2") return stream } public func take<T>(maxCount: Int)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var count = 0 upstream.react { value in count++ if count < maxCount { progress(value) } else if count == maxCount { progress(value) fulfill() // successfully reached maxCount } } }.name("\(upstream.name)-take(\(maxCount))") } public func takeUntil<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in if let triggerStream = triggerStream { _bindToUpstream(upstream, fulfill, reject, configure) upstream.react { value in progress(value) } let cancelError = _RKError(.CancelledByTriggerStream, "Stream=\(upstream.name) is cancelled by takeUntil(\(triggerStream.name)).") triggerStream.react { [weak upstream] _ in if let upstream_ = upstream { upstream_.cancel(error: cancelError) } }.then { [weak upstream] _ -> Void in if let upstream_ = upstream { upstream_.cancel(error: cancelError) } } } else { let cancelError = _RKError(.CancelledByTriggerStream, "Stream=\(upstream.name) is cancelled by takeUntil() with `triggerStream` already been deinited.") upstream.cancel(error: cancelError) } }.name("\(upstream.name)-takeUntil") } public func skip<T>(skipCount: Int)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var count = 0 upstream.react { value in count++ if count <= skipCount { return } progress(value) } }.name("\(upstream.name)-skip(\(skipCount))") } public func skipUntil<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var shouldSkip = true upstream.react { value in if !shouldSkip { progress(value) } } if let triggerStream = triggerStream { triggerStream.react { _ in shouldSkip = false }.then { _ -> Void in shouldSkip = false } } else { shouldSkip = false } }.name("\(upstream.name)-skipUntil") } public func sample<T, U>(triggerStream: Stream<U>)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { [weak triggerStream] progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var lastValue: T? upstream.react { value in lastValue = value } if let triggerStream = triggerStream { triggerStream.react { _ in if let lastValue = lastValue { progress(lastValue) } } } } } public func distinct<H: Hashable>(upstream: Stream<H>) -> Stream<H> { return Stream<H> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var usedValueHashes = Set<H>() upstream.react { value in if !usedValueHashes.contains(value) { usedValueHashes.insert(value) progress(value) } } } } // MARK: combining public func merge<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<T> { return upstream |> merge([stream]) } public func merge<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<T> { let stream = (streams + [upstream]) |> mergeInner return stream.name("\(upstream.name)-merge") } public func concat<T>(nextStream: Stream<T>)(upstream: Stream<T>) -> Stream<T> { return upstream |> concat([nextStream]) } public func concat<T>(nextStreams: [Stream<T>])(upstream: Stream<T>) -> Stream<T> { let stream = ([upstream] + nextStreams) |> concatInner return stream.name("\(upstream.name)-concat") } // // NOTE: // Avoid using curried function since `initialValue` seems to get deallocated at uncertain timing // (especially for T as value-type e.g. String, but also occurs a little in reference-type e.g. NSString). // Make sure to let `initialValue` be captured by closure explicitly. // /// `concat()` initialValue first public func startWith<T>(initialValue: T) -> (upstream: Stream<T>) -> Stream<T> { return { (upstream: Stream<T>) -> Stream<T> in precondition(upstream.state == .Paused) let stream = [Stream.once(initialValue), upstream] |> concatInner return stream.name("\(upstream.name)-startWith") } } //public func startWith<T>(initialValue: T)(upstream: Stream<T>) -> Stream<T> //{ // let stream = [Stream.once(initialValue), upstream] |> concatInner // return stream.name("\(upstream.name)-startWith") //} public func combineLatest<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<[T]> { return upstream |> combineLatest([stream]) } public func combineLatest<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<[T]> { let stream = ([upstream] + streams) |> combineLatestAll return stream.name("\(upstream.name)-combineLatest") } public func zip<T>(stream: Stream<T>)(upstream: Stream<T>) -> Stream<[T]> { return upstream |> zip([stream]) } public func zip<T>(streams: [Stream<T>])(upstream: Stream<T>) -> Stream<[T]> { let stream = ([upstream] + streams) |> zipAll return stream.name("\(upstream.name)-zip") } // MARK: timing /// delay `progress` and `fulfill` for `timerInterval` seconds public func delay<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) upstream.react { value in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in progress(value) timerStream = nil } }.success { _ -> Void in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in fulfill() timerStream = nil } } }.name("\(upstream.name)-delay(\(timeInterval))") } /// delay `progress` and `fulfill` for `timerInterval * eachProgressCount` seconds /// (incremental delay with start at t = 0sec) public func interval<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, nil, reject, configure) var incInterval = 0.0 upstream.react { value in var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: incInterval, repeats: false) { _ in } incInterval += timeInterval timerStream!.react { _ in progress(value) timerStream = nil } }.success { _ -> Void in incInterval -= timeInterval - 0.01 var timerStream: Stream<Void>? = NSTimer.stream(timeInterval: incInterval, repeats: false) { _ in } timerStream!.react { _ in fulfill() timerStream = nil } } }.name("\(upstream.name)-interval(\(timeInterval))") } /// limit continuous progress (reaction) for `timeInterval` seconds when first progress is triggered /// (see also: underscore.js throttle) public func throttle<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var lastProgressDate = NSDate(timeIntervalSince1970: 0) upstream.react { value in let now = NSDate() let timeDiff = now.timeIntervalSinceDate(lastProgressDate) if timeDiff > timeInterval { lastProgressDate = now progress(value) } } }.name("\(upstream.name)-throttle(\(timeInterval))") } /// delay progress (reaction) for `timeInterval` seconds and truly invoke reaction afterward if not interrupted by continuous progress /// (see also: underscore.js debounce) public func debounce<T>(timeInterval: NSTimeInterval)(upstream: Stream<T>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(upstream, fulfill, reject, configure) var timerStream: Stream<Void>? = nil // retained by upstream via upstream.react() upstream.react { value in // NOTE: overwrite to deinit & cancel old timerStream timerStream = NSTimer.stream(timeInterval: timeInterval, repeats: false) { _ in } timerStream!.react { _ in progress(value) } } }.name("\(upstream.name)-debounce(\(timeInterval))") } // MARK: collecting public func reduce<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { return Stream<U> { progress, fulfill, reject, configure in let accumulatingStream = upstream |> mapAccumulate(initialValue, accumulateClosure) _bindToUpstream(accumulatingStream, nil, nil, configure) var lastAccValue: U = initialValue // last accumulated value accumulatingStream.react { value in lastAccValue = value }.then { value, errorInfo -> Void in if value != nil { progress(lastAccValue) fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let cancelError = _RKError(.CancelledByUpstream, "Upstream is cancelled before performing `reduce()`.") reject(cancelError) } } } }.name("\(upstream.name)-reduce") } //-------------------------------------------------- // MARK: - Array Streams Operations //-------------------------------------------------- /// Merges multiple streams into single stream. /// See also: mergeInner public func mergeAll<T>(streams: [Stream<T>]) -> Stream<T> { let stream = Stream.sequence(streams) |> mergeInner return stream.name("mergeAll") } /// /// Merges multiple streams into single stream, /// combining latest values `[T?]` as well as changed value `T` together as `([T?], T)` tuple. /// /// This is a generalized method for `Rx.merge()` and `Rx.combineLatest()`. /// public func merge2All<T>(streams: [Stream<T>]) -> Stream<(values: [T?], changedValue: T)> { return Stream { progress, fulfill, reject, configure in configure.pause = { Stream<T>.pauseAll(streams) } configure.resume = { Stream<T>.resumeAll(streams) } configure.cancel = { Stream<T>.cancelAll(streams) } var states = [T?](count: streams.count, repeatedValue: nil) for i in 0..<streams.count { let stream = streams[i] stream.react { value in states[i] = value progress(values: states, changedValue: value) }.then { value, errorInfo -> Void in if value != nil { fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `merge2All()`.") reject(error) } } } } }.name("merge2All") } public func combineLatestAll<T>(streams: [Stream<T>]) -> Stream<[T]> { let stream = merge2All(streams) |> filter { values, _ in var areAllNonNil = true for value in values { if value == nil { areAllNonNil = false break } } return areAllNonNil } |> map { values, _ in values.map { $0! } } return stream.name("combineLatestAll") } public func zipAll<T>(streams: [Stream<T>]) -> Stream<[T]> { precondition(streams.count > 1) return Stream<[T]> { progress, fulfill, reject, configure in configure.pause = { Stream<T>.pauseAll(streams) } configure.resume = { Stream<T>.resumeAll(streams) } configure.cancel = { Stream<T>.cancelAll(streams) } let streamCount = streams.count var storedValuesArray: [[T]] = [] for i in 0..<streamCount { storedValuesArray.append([]) } for i in 0..<streamCount { streams[i].react { value in storedValuesArray[i] += [value] var canProgress: Bool = true for storedValues in storedValuesArray { if storedValues.count == 0 { canProgress = false break } } if canProgress { var firstStoredValues: [T] = [] for i in 0..<streamCount { let firstStoredValue = storedValuesArray[i].removeAtIndex(0) firstStoredValues.append(firstStoredValue) } progress(firstStoredValues) } }.success { _ -> Void in fulfill() } } }.name("zipAll") } //-------------------------------------------------- // MARK: - Nested Stream Operations //-------------------------------------------------- /// /// Merges multiple streams into single stream. /// /// - e.g. `let mergedStream = [stream1, stream2, ...] |> mergeInner` /// /// NOTE: This method is conceptually equal to `streams |> merge2All(streams) |> map { $1 }`. /// public func mergeInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in // NOTE: don't bind nestedStream's fulfill with returning mergeInner-stream's fulfill _bindToUpstream(nestedStream, nil, reject, configure) nestedStream.react { (innerStream: Stream<T>) in _bindToUpstream(innerStream, nil, nil, configure) innerStream.react { value in progress(value) }.then { value, errorInfo -> Void in if value != nil { fulfill() } else if let errorInfo = errorInfo { if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `mergeInner()`.") reject(error) } } } } }.name("mergeInner") } /// fixed-point combinator private func _fix<T, U>(f: (T -> U) -> T -> U) -> T -> U { return { f(_fix(f))($0) } } public func concatInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(nestedStream, nil, reject, configure) var pendingInnerStreams = [Stream<T>]() let performRecursively: Void -> Void = _fix { recurse in return { if let innerStream = pendingInnerStreams.first { if pendingInnerStreams.count == 1 { _bindToUpstream(innerStream, nil, nil, configure) innerStream.react { value in progress(value) }.success { pendingInnerStreams.removeAtIndex(0) recurse() }.failure { errorInfo -> Void in if let error = errorInfo.error { reject(error) } else { let error = _RKError(.CancelledByInternalStream, "One of stream is cancelled in `concatInner()`.") reject(error) } } } } } } nestedStream.react { (innerStream: Stream<T>) in pendingInnerStreams += [innerStream] performRecursively() } }.name("concatInner") } /// uses the latest innerStream and cancels previous innerStreams /// a.k.a Rx.switchLatest public func switchLatestInner<T>(nestedStream: Stream<Stream<T>>) -> Stream<T> { return Stream<T> { progress, fulfill, reject, configure in _bindToUpstream(nestedStream, nil, reject, configure) var currentInnerStream: Stream<T>? nestedStream.react { (innerStream: Stream<T>) in _bindToUpstream(innerStream, nil, nil, configure) currentInnerStream?.cancel() currentInnerStream = innerStream innerStream.react { value in progress(value) } } }.name("concatInner") } //-------------------------------------------------- // MARK: - Stream Producer Operations //-------------------------------------------------- /// /// Creates an upstream from `upstreamProducer`, resumes it (prestart), /// and caches its emitted values (`capacity` as max buffer count) for future "replay" /// when returning streamProducer creates a new stream & resumes it, /// a.k.a. Rx.replay(). /// /// NOTE: `downstream`'s `pause()`/`resume()`/`cancel()` will not affect `upstream`. /// /// :Usage: /// let cachedStreamProducer = networkStream |>> prestart(capacity: 1) /// let cachedStream1 = cachedStreamProducer() /// cachedStream1 ~> { ... } /// let cachedStream2 = cachedStreamProducer() // can produce many cached streams /// ... /// /// :param: capacity max buffer count for prestarted stream /// public func prestart<T>(capacity: Int = Int.max) -> (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer { return { (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer in var buffer = [T]() let upstream = upstreamProducer() // REACT upstream ~> { value in buffer += [value] while buffer.count > capacity { buffer.removeAtIndex(0) } } return { return Stream<T> { progress, fulfill, reject, configure in // NOTE: downstream's `configure` should not bind to upstream _bindToUpstream(upstream, fulfill, reject, nil) for b in buffer { progress(b) } upstream.react { value in progress(value) } }.name("\(upstream.name)-prestart") } } } //-------------------------------------------------- /// MARK: - Rx Semantics /// (TODO: move to new file, but doesn't work in Swift 1.1. ERROR = ld: symbol(s) not found for architecture x86_64) //-------------------------------------------------- public extension Stream { /// alias for `Stream.fulfilled()` public class func just(value: T) -> Stream<T> { return self.once(value) } /// alias for `Stream.fulfilled()` public class func empty() -> Stream<T> { return self.fulfilled() } /// alias for `Stream.rejected()` public class func error(error: NSError) -> Stream<T> { return self.rejected(error) } } /// alias for `mapAccumulate()` public func scan<T, U>(initialValue: U, accumulateClosure: (accumulatedValue: U, newValue: T) -> U)(upstream: Stream<T>) -> Stream<U> { return mapAccumulate(initialValue, accumulateClosure)(upstream: upstream) } /// alias for `prestart()` public func replay<T>(capacity: Int = Int.max) -> (upstreamProducer: Stream<T>.Producer) -> Stream<T>.Producer { return prestart(capacity: capacity) } //-------------------------------------------------- // MARK: - Custom Operators // + - * / % = < > ! & | ^ ~ . //-------------------------------------------------- // MARK: |> (stream pipelining) infix operator |> { associativity left precedence 95} /// single-stream pipelining operator public func |> <T, U>(stream: Stream<T>, transform: Stream<T> -> Stream<U>) -> Stream<U> { return transform(stream) } /// array-streams pipelining operator public func |> <T, U, S: SequenceType where S.Generator.Element == Stream<T>>(streams: S, transform: S -> Stream<U>) -> Stream<U> { return transform(streams) } /// nested-streams pipelining operator public func |> <T, U, S: SequenceType where S.Generator.Element == Stream<T>>(streams: S, transform: Stream<Stream<T>> -> Stream<U>) -> Stream<U> { return transform(Stream.sequence(streams)) } /// stream-transform pipelining operator public func |> <T, U, V>(transform1: Stream<T> -> Stream<U>, transform2: Stream<U> -> Stream<V>) -> Stream<T> -> Stream<V> { return { transform2(transform1($0)) } } // MARK: |>> (streamProducer pipelining) infix operator |>> { associativity left precedence 95} /// streamProducer lifting & pipelining operator public func |>> <T, U>(streamProducer: Stream<T>.Producer, transform: Stream<T> -> Stream<U>) -> Stream<U>.Producer { return { transform(streamProducer()) } } /// streamProducer(autoclosured) lifting & pipelining operator public func |>> <T, U>(@autoclosure(escaping) streamProducer: Stream<T>.Producer, transform: Stream<T> -> Stream<U>) -> Stream<U>.Producer { return { transform(streamProducer()) } } /// streamProducer pipelining operator public func |>> <T, U>(streamProducer: Stream<T>.Producer, transform: Stream<T>.Producer -> Stream<U>.Producer) -> Stream<U>.Producer { return transform(streamProducer) } /// streamProducer(autoclosured) pipelining operator public func |>> <T, U>(@autoclosure(escaping) streamProducer: Stream<T>.Producer, transform: Stream<T>.Producer -> Stream<U>.Producer) -> Stream<U>.Producer { return transform(streamProducer) } /// streamProducer-transform pipelining operator public func |>> <T, U, V>(transform1: Stream<T>.Producer -> Stream<U>.Producer, transform2: Stream<U>.Producer -> Stream<V>.Producer) -> Stream<T>.Producer -> Stream<V>.Producer { return { transform2(transform1($0)) } } // MARK: ~> (right reacting operator) // NOTE: `infix operator ~>` is already declared in Swift //infix operator ~> { associativity left precedence 255 } /// right-closure reacting operator, i.e. `stream.react { ... }` public func ~> <T>(stream: Stream<T>, reactClosure: T -> Void) -> Stream<T> { stream.react(reactClosure) return stream } // MARK: ~> (left reacting operator) infix operator <~ { associativity right precedence 50 } /// left-closure (closure-first) reacting operator, reversing `stream.react { ... }` /// e.g. ^{ ... } <~ stream public func <~ <T>(reactClosure: T -> Void, stream: Stream<T>) -> Stream<T> { return stream ~> reactClosure } // MARK: ~>! (terminal reacting operator) infix operator ~>! { associativity left precedence 50 } /// /// terminal reacting operator, which returns synchronously-emitted last value /// to gain similar functionality as Java 8's Stream API, /// /// e.g. /// let sum = Stream.sequence([1, 2, 3]) |> reduce(0) { $0 + $1 } ~>! () /// let distinctSequence = Stream.sequence([1, 2, 2, 3]) |> distinct |> buffer() ~>! () // NOTE: use `buffer()` whenever necessary /// public func ~>! <T>(stream: Stream<T>, void: Void) -> T! { var ret: T! stream.react { value in ret = value } return ret } /// terminal reacting operator (less precedence for '~>') public func ~>! <T>(stream: Stream<T>, reactClosure: T -> Void) { stream ~> reactClosure } prefix operator ^ {} /// Objective-C like 'block operator' to let Swift compiler know closure-type at start of the line /// e.g. ^{ println($0) } <~ stream public prefix func ^ <T, U>(closure: T -> U) -> (T -> U) { return closure } prefix operator + {} /// short-living operator for stream not being retained /// e.g. ^{ println($0) } <~ +KVO.stream(obj1, "value") public prefix func + <T>(stream: Stream<T>) -> Stream<T> { var holder: Stream<T>? = stream // let stream be captured by dispatch_queue to guarantee its lifetime until next runloop dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue()) { // on main-thread holder = nil } return stream }
import TensorFlow struct ConvBN: Layer { var conv: Conv2D<Float> var norm: BatchNorm<Float> public init(filterShape: (Int, Int, Int, Int), strides: (Int, Int) = (1, 1), padding: Padding) { self.conv = Conv2D(filterShape: filterShape, strides: strides, padding: padding) self.norm = BatchNorm(featureCount: filterShape.3) } @differentiable public func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { return norm.applied(to: conv.applied(to: input, in: context), in: context) } } // AD on indirect passing would let us have ResidualBlock<Shortcut : Layer> // where Shortcut is one of ConvBN or // struct Identity: Layer { // public func applied(to input: Tensor<Float>) -> Tensor<Float> { // return input // } // } struct ResidualConvBlock: Layer { var layer1: ConvBN var layer2: ConvBN var layer3: ConvBN var shortcut: ConvBN public init( featureCounts: (Int, Int, Int, Int), kernelSize: Int = 3, strides: (Int, Int) = (2, 2) ) { self.layer1 = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.1), strides: strides, padding: .valid) self.layer2 = ConvBN( filterShape: ( kernelSize, kernelSize, featureCounts.1, featureCounts.2), padding: .same) self.layer3 = ConvBN( filterShape: (1, 1, featureCounts.2, featureCounts.3), padding: .valid) self.shortcut = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.3), strides: strides, padding: .same) } @differentiable func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = relu(layer1.applied(to: input, in: context)) tmp = relu(layer2.applied(to: tmp, in: context)) tmp = layer3.applied(to: tmp, in: context) return relu(tmp + shortcut.applied(to: input, in: context)) } } struct ResidualIdentityBlock: Layer { var layer1: ConvBN var layer2: ConvBN var layer3: ConvBN public init(featureCounts: (Int, Int, Int, Int), kernelSize: Int = 3) { self.layer1 = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.1), padding: .valid) self.layer2 = ConvBN( filterShape: ( kernelSize, kernelSize, featureCounts.1, featureCounts.2), padding: .same) self.layer3 = ConvBN( filterShape: (1, 1, featureCounts.2, featureCounts.3), padding: .valid) } @differentiable func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = relu(layer1.applied(to: input, in: context)) tmp = relu(layer2.applied(to: tmp, in: context)) tmp = layer3.applied(to: tmp, in: context) return relu(tmp + input) } } public struct ResNet50: Layer { var l1: ConvBN @noDerivative let maxPool: MaxPool2D<Float> var l2a: ResidualConvBlock var l2b: ResidualIdentityBlock var l2c: ResidualIdentityBlock var l3a: ResidualConvBlock var l3b: ResidualIdentityBlock var l3c: ResidualIdentityBlock var l3d: ResidualIdentityBlock var l4a: ResidualConvBlock var l4b: ResidualIdentityBlock var l4c: ResidualIdentityBlock var l4d: ResidualIdentityBlock var l4e: ResidualIdentityBlock var l4f: ResidualIdentityBlock var l5a: ResidualConvBlock var l5b: ResidualIdentityBlock var l5c: ResidualIdentityBlock @noDerivative let avgPool: AvgPool2D<Float> var classifier: Dense<Float> public init( classCount: Int ) { self.l1 = ConvBN( filterShape: (7, 7, 3, 64), strides: (2, 2), padding: .same) self.maxPool = MaxPool2D<Float>( poolSize: (3, 3), strides: (2, 2), padding: .valid) self.l2a = ResidualConvBlock( featureCounts: (64, 64, 64, 256), strides: (1, 1)) self.l2b = ResidualIdentityBlock( featureCounts: (256, 64, 64, 256)) self.l2c = ResidualIdentityBlock( featureCounts: (256, 64, 64, 256)) self.l3a = ResidualConvBlock( featureCounts: (256, 128, 128, 512)) self.l3b = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l3c = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l3d = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l4a = ResidualConvBlock( featureCounts: (512, 256, 256, 1024)) self.l4b = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4c = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4d = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4e = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4f = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l5a = ResidualConvBlock( featureCounts: (1024, 512, 512, 2048)) self.l5b = ResidualIdentityBlock( featureCounts: (2048, 512, 512, 2048)) self.l5c = ResidualIdentityBlock( featureCounts: (2048, 512, 512, 2048)) self.avgPool = AvgPool2D<Float>( poolSize: (7, 7), strides: (7, 7), padding: .valid) self.classifier = Dense<Float>( inputSize: 2048, outputSize: classCount, activation: { $0 }) } @differentiable public func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = input tmp = maxPool.applied(to: relu(l1.applied(to: input, in: context)), in: context) tmp = l2a.applied(to: tmp, in: context) tmp = l2b.applied(to: tmp, in: context) tmp = l2c.applied(to: tmp, in: context) tmp = l3a.applied(to: tmp, in: context) tmp = l3b.applied(to: tmp, in: context) tmp = l3c.applied(to: tmp, in: context) tmp = l3d.applied(to: tmp, in: context) tmp = l4a.applied(to: tmp, in: context) tmp = l4b.applied(to: tmp, in: context) tmp = l4c.applied(to: tmp, in: context) tmp = l4d.applied(to: tmp, in: context) tmp = l4e.applied(to: tmp, in: context) tmp = l4f.applied(to: tmp, in: context) tmp = l5a.applied(to: tmp, in: context) tmp = l5b.applied(to: tmp, in: context) tmp = avgPool.applied(to: l5c.applied(to: tmp, in: context), in: context) tmp = tmp.reshaped(toShape: Tensor<Int32>( [tmp.shape[Int32(0)], tmp.shape[Int32(3)]])) return classifier.applied(to: tmp, in: context) } } let batchSize: Int32 = 128 let classCount = 1000 let fakeImageBatch = Tensor<Float>(zeros: [batchSize, 224, 224, 3]) let fakeLabelBatch = Tensor<Int32>(zeros: [batchSize]) var resnet = ResNet50(classCount: classCount) let context = Context(learningPhase: .training) let optimizer = SGD<ResNet50, Float>(learningRate: 0.1, momentum: 0.9) for _ in 0..<10 { let gradients = gradient(at: resnet) { model -> Tensor<Float> in let logits = model.applied(to: fakeImageBatch, in: context) let oneHotLabels = Tensor<Float>(oneHotAtIndices: fakeLabelBatch, depth: logits.shape[1]) return softmaxCrossEntropy(logits: logits, labels: oneHotLabels) } optimizer.update(&resnet.allDifferentiableVariables, along: gradients) } tweak resnet variable name (#68) labels --> oneHotLabels Fixes #67. import TensorFlow struct ConvBN: Layer { var conv: Conv2D<Float> var norm: BatchNorm<Float> public init(filterShape: (Int, Int, Int, Int), strides: (Int, Int) = (1, 1), padding: Padding) { self.conv = Conv2D(filterShape: filterShape, strides: strides, padding: padding) self.norm = BatchNorm(featureCount: filterShape.3) } @differentiable public func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { return norm.applied(to: conv.applied(to: input, in: context), in: context) } } // AD on indirect passing would let us have ResidualBlock<Shortcut : Layer> // where Shortcut is one of ConvBN or // struct Identity: Layer { // public func applied(to input: Tensor<Float>) -> Tensor<Float> { // return input // } // } struct ResidualConvBlock: Layer { var layer1: ConvBN var layer2: ConvBN var layer3: ConvBN var shortcut: ConvBN public init( featureCounts: (Int, Int, Int, Int), kernelSize: Int = 3, strides: (Int, Int) = (2, 2) ) { self.layer1 = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.1), strides: strides, padding: .valid) self.layer2 = ConvBN( filterShape: ( kernelSize, kernelSize, featureCounts.1, featureCounts.2), padding: .same) self.layer3 = ConvBN( filterShape: (1, 1, featureCounts.2, featureCounts.3), padding: .valid) self.shortcut = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.3), strides: strides, padding: .same) } @differentiable func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = relu(layer1.applied(to: input, in: context)) tmp = relu(layer2.applied(to: tmp, in: context)) tmp = layer3.applied(to: tmp, in: context) return relu(tmp + shortcut.applied(to: input, in: context)) } } struct ResidualIdentityBlock: Layer { var layer1: ConvBN var layer2: ConvBN var layer3: ConvBN public init(featureCounts: (Int, Int, Int, Int), kernelSize: Int = 3) { self.layer1 = ConvBN( filterShape: (1, 1, featureCounts.0, featureCounts.1), padding: .valid) self.layer2 = ConvBN( filterShape: ( kernelSize, kernelSize, featureCounts.1, featureCounts.2), padding: .same) self.layer3 = ConvBN( filterShape: (1, 1, featureCounts.2, featureCounts.3), padding: .valid) } @differentiable func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = relu(layer1.applied(to: input, in: context)) tmp = relu(layer2.applied(to: tmp, in: context)) tmp = layer3.applied(to: tmp, in: context) return relu(tmp + input) } } public struct ResNet50: Layer { var l1: ConvBN @noDerivative let maxPool: MaxPool2D<Float> var l2a: ResidualConvBlock var l2b: ResidualIdentityBlock var l2c: ResidualIdentityBlock var l3a: ResidualConvBlock var l3b: ResidualIdentityBlock var l3c: ResidualIdentityBlock var l3d: ResidualIdentityBlock var l4a: ResidualConvBlock var l4b: ResidualIdentityBlock var l4c: ResidualIdentityBlock var l4d: ResidualIdentityBlock var l4e: ResidualIdentityBlock var l4f: ResidualIdentityBlock var l5a: ResidualConvBlock var l5b: ResidualIdentityBlock var l5c: ResidualIdentityBlock @noDerivative let avgPool: AvgPool2D<Float> var classifier: Dense<Float> public init( classCount: Int ) { self.l1 = ConvBN( filterShape: (7, 7, 3, 64), strides: (2, 2), padding: .same) self.maxPool = MaxPool2D<Float>( poolSize: (3, 3), strides: (2, 2), padding: .valid) self.l2a = ResidualConvBlock( featureCounts: (64, 64, 64, 256), strides: (1, 1)) self.l2b = ResidualIdentityBlock( featureCounts: (256, 64, 64, 256)) self.l2c = ResidualIdentityBlock( featureCounts: (256, 64, 64, 256)) self.l3a = ResidualConvBlock( featureCounts: (256, 128, 128, 512)) self.l3b = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l3c = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l3d = ResidualIdentityBlock( featureCounts: (512, 128, 128, 512)) self.l4a = ResidualConvBlock( featureCounts: (512, 256, 256, 1024)) self.l4b = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4c = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4d = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4e = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l4f = ResidualIdentityBlock( featureCounts: (1024, 256, 256, 1024)) self.l5a = ResidualConvBlock( featureCounts: (1024, 512, 512, 2048)) self.l5b = ResidualIdentityBlock( featureCounts: (2048, 512, 512, 2048)) self.l5c = ResidualIdentityBlock( featureCounts: (2048, 512, 512, 2048)) self.avgPool = AvgPool2D<Float>( poolSize: (7, 7), strides: (7, 7), padding: .valid) self.classifier = Dense<Float>( inputSize: 2048, outputSize: classCount, activation: { $0 }) } @differentiable public func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> { var tmp = input tmp = maxPool.applied(to: relu(l1.applied(to: input, in: context)), in: context) tmp = l2a.applied(to: tmp, in: context) tmp = l2b.applied(to: tmp, in: context) tmp = l2c.applied(to: tmp, in: context) tmp = l3a.applied(to: tmp, in: context) tmp = l3b.applied(to: tmp, in: context) tmp = l3c.applied(to: tmp, in: context) tmp = l3d.applied(to: tmp, in: context) tmp = l4a.applied(to: tmp, in: context) tmp = l4b.applied(to: tmp, in: context) tmp = l4c.applied(to: tmp, in: context) tmp = l4d.applied(to: tmp, in: context) tmp = l4e.applied(to: tmp, in: context) tmp = l4f.applied(to: tmp, in: context) tmp = l5a.applied(to: tmp, in: context) tmp = l5b.applied(to: tmp, in: context) tmp = avgPool.applied(to: l5c.applied(to: tmp, in: context), in: context) tmp = tmp.reshaped(toShape: Tensor<Int32>( [tmp.shape[Int32(0)], tmp.shape[Int32(3)]])) return classifier.applied(to: tmp, in: context) } } let batchSize: Int32 = 128 let classCount = 1000 let fakeImageBatch = Tensor<Float>(zeros: [batchSize, 224, 224, 3]) let fakeLabelBatch = Tensor<Int32>(zeros: [batchSize]) var resnet = ResNet50(classCount: classCount) let context = Context(learningPhase: .training) let optimizer = SGD<ResNet50, Float>(learningRate: 0.1, momentum: 0.9) for _ in 0..<10 { let gradients = gradient(at: resnet) { model -> Tensor<Float> in let logits = model.applied(to: fakeImageBatch, in: context) let oneHotLabels = Tensor<Float>(oneHotAtIndices: fakeLabelBatch, depth: logits.shape[1]) return softmaxCrossEntropy(logits: logits, oneHotLabels: oneHotLabels) } optimizer.update(&resnet.allDifferentiableVariables, along: gradients) }
// // Recorded.swift // RxTest // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import Swift /// Record of a value including the virtual time it was produced on. public struct Recorded<Value> : CustomDebugStringConvertible { /// Gets the virtual time the value was produced on. public let time: TestTime /// Gets the recorded value. public let value: Value public init(time: TestTime, value: Value) { self.time = time self.value = value } } extension Recorded { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return "\(value) @ \(time)" } } extension Recorded : Equatable where Value : Equatable { public static func == (lhs: Recorded<Value>, rhs: Recorded<Value>) -> Bool { return lhs.time == rhs.time && lhs.value == rhs.value } } Minor lint. // // Recorded.swift // RxTest // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import Swift /// Record of a value including the virtual time it was produced on. public struct Recorded<Value> : CustomDebugStringConvertible { /// Gets the virtual time the value was produced on. public let time: TestTime /// Gets the recorded value. public let value: Value public init(time: TestTime, value: Value) { self.time = time self.value = value } } extension Recorded { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return "\(value) @ \(time)" } } extension Recorded: Equatable where Value: Equatable { public static func == (lhs: Recorded<Value>, rhs: Recorded<Value>) -> Bool { return lhs.time == rhs.time && lhs.value == rhs.value } }
// // Decoder.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // 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 /** Decodes JSON to objects. */ public struct Decoder { /** Decodes JSON to a generic value. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decode<T>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let value = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? T { return value } return nil } } /** Decodes JSON to a date. - parameter key: Key used in JSON for decoded value. - parameter dateFormatter: Date formatter used to create date. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDate(key: String, dateFormatter: NSDateFormatter, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSDate? { return { json in if let dateString = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? String { return dateFormatter.dateFromString(dateString) } return nil } } /** Decodes JSON to a date array. - parameter key: Key used in JSON for decoded value. - parameter dateFormatter: Date formatter used to create date. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateArray(key: String, dateFormatter: NSDateFormatter, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSDate]? { return { json in if let dateStrings = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String] { var dates: [NSDate] = [] for dateString in dateStrings { guard let date = dateFormatter.dateFromString(dateString) else { return nil } dates.append(date) } return dates } return nil } } /** Decodes JSON to an ISO8601 date. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateISO8601(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSDate? { return Decoder.decodeDate(key, dateFormatter: GlossDateFormatterISO8601, keyPathDelimiter: keyPathDelimiter) } /** Decodes JSON to an ISO8601 date array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateISO8601Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSDate]? { return Decoder.decodeDateArray(key, dateFormatter: GlossDateFormatterISO8601, keyPathDelimiter: keyPathDelimiter) } /** Decodes JSON to a Decodable object. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodable<T: Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let subJSON = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? JSON { return T(json: subJSON) } return nil } } /** Decodes JSON to a Decodable object array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableArray<T: Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [T]? { return { json in if let jsonArray = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [JSON] { var models: [T] = [] for subJSON in jsonArray { guard let model = T(json: subJSON) else { return nil } models.append(model) } return models } return nil } } /** Decodes JSON to a dictionary of String to Decodable. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableDictionary<T:Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [String : T]? { return { json in guard let dictionary = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String : JSON] else { return nil } return dictionary.flatMap { (key, value) in guard let decoded = T(json: value) else { return nil } return (key, decoded) } } } /** Decodes JSON to a dictionary of String to Decodable array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableDictionary<T:Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [String : [T]]? { return { json in guard let dictionary = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String : [JSON]] else { return nil } return dictionary.flatMap { (key, value) in guard let decoded = [T].fromJSONArray(value) else { return nil } return (key, decoded) } } } /** Decodes JSON to an enum value. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeEnum<T: RawRepresentable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let rawValue = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? T.RawValue { return T(rawValue: rawValue) } return nil } } /** Decodes JSON to an enum value array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeEnumArray<T: RawRepresentable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [T]? { return { json in if let rawValues = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [T.RawValue] { var enumValues: [T] = [] for rawValue in rawValues { guard let enumValue = T(rawValue: rawValue) else { return nil } enumValues.append(enumValue) } return enumValues } return nil } } /** Decodes JSON to an Int32. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt32(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> Int32? { return { json in if let number = json[key] as? NSNumber { return number.intValue } return nil } } /** Decodes JSON to an Int32 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt32Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [Int32]? { return { json in if let numbers = json[key] as? [NSNumber] { let ints: [Int32] = numbers.map { $0.intValue } return ints } return nil } } /** Decodes JSON to an UInt32. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt32(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> UInt32? { return { json in if let number = json[key] as? NSNumber { return number.unsignedIntValue } return nil } } /** Decodes JSON to an UInt32 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt32Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [UInt32]? { return { json in if let numbers = json[key] as? [NSNumber] { let uints: [UInt32] = numbers.map { $0.unsignedIntValue } return uints } return nil } } /** Decodes JSON to an Int64. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt64(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> Int64? { return { json in if let number = json[key] as? NSNumber { return number.longLongValue } return nil } } /** Decodes JSON to an Int64 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt64Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [Int64]? { return { json in if let numbers = json[key] as? [NSNumber] { let ints: [Int64] = numbers.map { $0.longLongValue } return ints } return nil } } /** Decodes JSON to an UInt64. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt64(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> UInt64? { return { json in if let number = json[key] as? NSNumber { return number.unsignedLongLongValue } return nil } } /** Decodes JSON to an UInt64 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt64Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [UInt64]? { return { json in if let numbers = json[key] as? [NSNumber] { let uints: [UInt64] = numbers.map { $0.unsignedLongLongValue } return uints } return nil } } /** Decodes JSON to a URL. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeURL(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSURL? { return { json in if let urlString = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? String, encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { return NSURL(string: encodedString) } return nil } } /** Decodes JSON to a URL array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeURLArray(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSURL]? { return { json in if let urlStrings = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String] { var urls: [NSURL] = [] for urlString in urlStrings { guard let url = NSURL(string: urlString) else { return nil } urls.append(url) } return urls } return nil } } } Updated Decoder syntax for Swift 2.3 // // Decoder.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // 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 /** Decodes JSON to objects. */ public struct Decoder { /** Decodes JSON to a generic value. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decode<T>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let value = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? T { return value } return nil } } /** Decodes JSON to a date. - parameter key: Key used in JSON for decoded value. - parameter dateFormatter: Date formatter used to create date. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDate(key: String, dateFormatter: NSDateFormatter, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSDate? { return { json in if let dateString = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? String { return dateFormatter.dateFromString(dateString) } return nil } } /** Decodes JSON to a date array. - parameter key: Key used in JSON for decoded value. - parameter dateFormatter: Date formatter used to create date. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateArray(key: String, dateFormatter: NSDateFormatter, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSDate]? { return { json in if let dateStrings = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String] { var dates: [NSDate] = [] for dateString in dateStrings { guard let date = dateFormatter.dateFromString(dateString) else { return nil } dates.append(date) } return dates } return nil } } /** Decodes JSON to an ISO8601 date. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateISO8601(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSDate? { return Decoder.decodeDate(key, dateFormatter: GlossDateFormatterISO8601, keyPathDelimiter: keyPathDelimiter) } /** Decodes JSON to an ISO8601 date array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDateISO8601Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSDate]? { return Decoder.decodeDateArray(key, dateFormatter: GlossDateFormatterISO8601, keyPathDelimiter: keyPathDelimiter) } /** Decodes JSON to a Decodable object. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodable<T: Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let subJSON = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? JSON { return T(json: subJSON) } return nil } } /** Decodes JSON to a Decodable object array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableArray<T: Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [T]? { return { json in if let jsonArray = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [JSON] { var models: [T] = [] for subJSON in jsonArray { guard let model = T(json: subJSON) else { return nil } models.append(model) } return models } return nil } } /** Decodes JSON to a dictionary of String to Decodable. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableDictionary<T:Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [String : T]? { return { json in guard let dictionary = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String : JSON] else { return nil } return dictionary.flatMap { (key, value) in guard let decoded = T(json: value) else { return nil } return (key, decoded) } } } /** Decodes JSON to a dictionary of String to Decodable array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeDecodableDictionary<T:Decodable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [String : [T]]? { return { json in guard let dictionary = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String : [JSON]] else { return nil } return dictionary.flatMap { (key, value) in guard let decoded = [T].fromJSONArray(value) else { return nil } return (key, decoded) } } } /** Decodes JSON to an enum value. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeEnum<T: RawRepresentable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> T? { return { json in if let rawValue = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? T.RawValue { return T(rawValue: rawValue) } return nil } } /** Decodes JSON to an enum value array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeEnumArray<T: RawRepresentable>(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [T]? { return { json in if let rawValues = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [T.RawValue] { var enumValues: [T] = [] for rawValue in rawValues { guard let enumValue = T(rawValue: rawValue) else { return nil } enumValues.append(enumValue) } return enumValues } return nil } } /** Decodes JSON to an Int32. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt32(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> Int32? { return { json in if let number = json[key] as? NSNumber { return number.intValue } return nil } } /** Decodes JSON to an Int32 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt32Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [Int32]? { return { json in if let numbers = json[key] as? [NSNumber] { let ints: [Int32] = numbers.map { $0.intValue } return ints } return nil } } /** Decodes JSON to an UInt32. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt32(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> UInt32? { return { json in if let number = json[key] as? NSNumber { return number.unsignedIntValue } return nil } } /** Decodes JSON to an UInt32 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt32Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [UInt32]? { return { json in if let numbers = json[key] as? [NSNumber] { let uints: [UInt32] = numbers.map { $0.unsignedIntValue } return uints } return nil } } /** Decodes JSON to an Int64. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt64(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> Int64? { return { json in if let number = json[key] as? NSNumber { return number.longLongValue } return nil } } /** Decodes JSON to an Int64 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeInt64Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [Int64]? { return { json in if let numbers = json[key] as? [NSNumber] { let ints: [Int64] = numbers.map { $0.longLongValue } return ints } return nil } } /** Decodes JSON to an UInt64. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt64(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> UInt64? { return { json in if let number = json[key] as? NSNumber { return number.unsignedLongLongValue } return nil } } /** Decodes JSON to an UInt64 array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeUInt64Array(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [UInt64]? { return { json in if let numbers = json[key] as? [NSNumber] { let uints: [UInt64] = numbers.map { $0.unsignedLongLongValue } return uints } return nil } } /** Decodes JSON to a URL. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeURL(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> NSURL? { return { json in if let urlString = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? String, let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { return NSURL(string: encodedString) } return nil } } /** Decodes JSON to a URL array. - parameter key: Key used in JSON for decoded value. - parameter keyPathDelimiter: Delimiter used for nested key path. - returns: Value decoded from JSON. */ public static func decodeURLArray(key: String, keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON -> [NSURL]? { return { json in if let urlStrings = json.valueForKeyPath(key, withDelimiter: keyPathDelimiter) as? [String] { var urls: [NSURL] = [] for urlString in urlStrings { guard let url = NSURL(string: urlString) else { return nil } urls.append(url) } return urls } return nil } } }
/* SBUtilS.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike 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. 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 Foundation func SBGetLocalizableTextSetS(path: String) -> (([[String]])?, ([[NSTextField]])?, NSSize?) { let localizableString = NSString.stringWithContentsOfFile(path, encoding: NSUTF16StringEncoding, error: nil) if localizableString.length > 0 { let fieldSize = NSSize(width: 300, height: 22) let offset = NSPoint(x: 45, y: 12) let margin = CGFloat(20) let lines = localizableString.componentsSeparatedByString("\n") as [String] let count = CGFloat(lines.count) var size = NSSize( width: offset.x + (fieldSize.width * 2) + margin * 2, height: (fieldSize.height + offset.y) * count + offset.y + margin * 2) if count > 1 { var textSet: [[String]] = [] var fieldSet: [[NSTextField]] = [] for (i, line) in enumerate(lines) { var fieldRect = NSRect() var texts: [String] = [] var fields: [NSTextField] = [] let components = line.componentsSeparatedByString(" = ") fieldRect.size = fieldSize fieldRect.origin.y = size.height - margin - (fieldSize.height * CGFloat(i + 1)) - (offset.y * CGFloat(i)) for (j, component) in enumerate(components) { if !component.isEmpty { let isMenuItem = !component.hasPrefix("//") let editable = isMenuItem && j == 1 var string = component fieldRect.origin.x = CGFloat(j) * (fieldSize.width + offset.x) let field = NSTextField(frame: fieldRect) field.editable = editable field.selectable = isMenuItem field.bordered = isMenuItem field.drawsBackground = isMenuItem field.bezeled = editable (field.cell() as NSCell).scrollable = isMenuItem if isMenuItem { string = (component as NSString).stringByDeletingQuotations() } texts.append(string) fields.append(field) } } if texts.count >= 1 { textSet.append(texts) } if fields.count >= 1 { fieldSet.append(fields) } } return (textSet, fieldSet, size) } } return (nil, nil, nil) } // Return value for key in "com.apple.internetconfig.plist" func SBDefaultHomePageS() -> String? { if let path = SBSearchFileInDirectory("com.apple.internetconfig", SBLibraryDirectory("Preferences")) { if NSFileManager.defaultManager().fileExistsAtPath(path) { let internetConfig = NSDictionary(contentsOfFile: path) if internetConfig.count > 0 { return SBValueForKey("WWWHomePage", internetConfig) as? String } } } return nil } func SBDefaultSaveDownloadedFilesToPathS() -> String? { if let path = SBSearchPath(.DownloadsDirectory, nil) { return path.stringByExpandingTildeInPath } return nil } func SBGraphicsPortFromContext(context: NSGraphicsContext) -> CGContext { let ctxPtr = COpaquePointer(context.graphicsPort) return Unmanaged<CGContext>.fromOpaque(ctxPtr).takeUnretainedValue() } var SBCurrentGraphicsPort: CGContext { return SBGraphicsPortFromContext(NSGraphicsContext.currentContext()) } func SBDispatch(block: dispatch_block_t) { dispatch_async(dispatch_get_main_queue(), block) } func SBDispatchDelay(delay: Double, block: dispatch_block_t) { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * delay)) let queue = dispatch_get_main_queue() dispatch_after(time, queue, block) } /* func SBCreateBookmarkItemS(title: String?, url: String?, imageData: NSData?, date: NSDate?, labelName: String?, offsetString: String?) -> BookmarkItem { var item = BookmarkItem() if title? { item[kSBBookmarkTitle] = title! } if url? { item[kSBBookmarkURL] = url! } if imageData? { item[kSBBookmarkImage] = imageData! } if date? { item[kSBBookmarkDate] = date! } if labelName? { item[kSBBookmarkLabelName] = labelName! } if offsetString? { item[kSBBookmarkOffset] = offsetString! } return item } */ let SBAlternateSelectedControlColor = NSColor.alternateSelectedControlColor().colorUsingColorSpace(NSColorSpace.genericRGBColorSpace()) func SBConstrain<T: Comparable>(value: T, min minValue: T? = nil, max maxValue: T? = nil) -> T { var v = value if minValue != nil { v = max(v, minValue!) } if maxValue != nil { v = min(v, maxValue!) } return r } SBConstrain fix /* SBUtilS.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike 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. 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 Foundation func SBGetLocalizableTextSetS(path: String) -> (([[String]])?, ([[NSTextField]])?, NSSize?) { let localizableString = NSString.stringWithContentsOfFile(path, encoding: NSUTF16StringEncoding, error: nil) if localizableString.length > 0 { let fieldSize = NSSize(width: 300, height: 22) let offset = NSPoint(x: 45, y: 12) let margin = CGFloat(20) let lines = localizableString.componentsSeparatedByString("\n") as [String] let count = CGFloat(lines.count) var size = NSSize( width: offset.x + (fieldSize.width * 2) + margin * 2, height: (fieldSize.height + offset.y) * count + offset.y + margin * 2) if count > 1 { var textSet: [[String]] = [] var fieldSet: [[NSTextField]] = [] for (i, line) in enumerate(lines) { var fieldRect = NSRect() var texts: [String] = [] var fields: [NSTextField] = [] let components = line.componentsSeparatedByString(" = ") fieldRect.size = fieldSize fieldRect.origin.y = size.height - margin - (fieldSize.height * CGFloat(i + 1)) - (offset.y * CGFloat(i)) for (j, component) in enumerate(components) { if !component.isEmpty { let isMenuItem = !component.hasPrefix("//") let editable = isMenuItem && j == 1 var string = component fieldRect.origin.x = CGFloat(j) * (fieldSize.width + offset.x) let field = NSTextField(frame: fieldRect) field.editable = editable field.selectable = isMenuItem field.bordered = isMenuItem field.drawsBackground = isMenuItem field.bezeled = editable (field.cell() as NSCell).scrollable = isMenuItem if isMenuItem { string = (component as NSString).stringByDeletingQuotations() } texts.append(string) fields.append(field) } } if texts.count >= 1 { textSet.append(texts) } if fields.count >= 1 { fieldSet.append(fields) } } return (textSet, fieldSet, size) } } return (nil, nil, nil) } // Return value for key in "com.apple.internetconfig.plist" func SBDefaultHomePageS() -> String? { if let path = SBSearchFileInDirectory("com.apple.internetconfig", SBLibraryDirectory("Preferences")) { if NSFileManager.defaultManager().fileExistsAtPath(path) { let internetConfig = NSDictionary(contentsOfFile: path) if internetConfig.count > 0 { return SBValueForKey("WWWHomePage", internetConfig) as? String } } } return nil } func SBDefaultSaveDownloadedFilesToPathS() -> String? { if let path = SBSearchPath(.DownloadsDirectory, nil) { return path.stringByExpandingTildeInPath } return nil } func SBGraphicsPortFromContext(context: NSGraphicsContext) -> CGContext { let ctxPtr = COpaquePointer(context.graphicsPort) return Unmanaged<CGContext>.fromOpaque(ctxPtr).takeUnretainedValue() } var SBCurrentGraphicsPort: CGContext { return SBGraphicsPortFromContext(NSGraphicsContext.currentContext()) } func SBDispatch(block: dispatch_block_t) { dispatch_async(dispatch_get_main_queue(), block) } func SBDispatchDelay(delay: Double, block: dispatch_block_t) { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * delay)) let queue = dispatch_get_main_queue() dispatch_after(time, queue, block) } /* func SBCreateBookmarkItemS(title: String?, url: String?, imageData: NSData?, date: NSDate?, labelName: String?, offsetString: String?) -> BookmarkItem { var item = BookmarkItem() if title? { item[kSBBookmarkTitle] = title! } if url? { item[kSBBookmarkURL] = url! } if imageData? { item[kSBBookmarkImage] = imageData! } if date? { item[kSBBookmarkDate] = date! } if labelName? { item[kSBBookmarkLabelName] = labelName! } if offsetString? { item[kSBBookmarkOffset] = offsetString! } return item } */ let SBAlternateSelectedControlColor = NSColor.alternateSelectedControlColor().colorUsingColorSpace(NSColorSpace.genericRGBColorSpace()) func SBConstrain<T: Comparable>(value: T, min minValue: T? = nil, max maxValue: T? = nil) -> T { var v = value if minValue != nil { v = max(v, minValue!) } if maxValue != nil { v = min(v, maxValue!) } return v }
// Copyright (c) 2016, Yuji // 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. // // 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 6/2/16. // Copyright © 2016 yuuji. All rights reserved. // public class SXQueue: KqueueManagable { public var ident: Int32 public var readAgent: Readable public var writeAgent: Writable public var service: SXService public var manager: SXKernel? public init(fd: Int32, readFrom r: Readable, writeTo w: Writable, with service: SXService) throws { self.readAgent = r self.writeAgent = w self.service = service self.ident = fd SXKernelManager.default?.register(service: service, queue: self) } public func terminate() { self.readAgent.done() self.writeAgent.done() // SXKernelManager.default?.unregister(for: ident) } // #if os(Linux) // public func runloop() { // do { // if let data = try self.fd_r.read() { // // if !self.service.dataHandler(self, data) { // return terminate() // } // // } else { // return terminate() // } // // } catch { // self.service.errHandler?(self, error) // } // } // #else // public func runloop(kdata: Int, udata: UnsafeRawPointer!) { public func runloop(_ ev: event) { do { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) self.readAgent.readBufsize = ev.data + 1 #endif if let data = try self.readAgent.read() { if !self.service.dataHandler(self, data) { return terminate() } } else { return terminate() } } catch { self.service.errHandler?(self, error) } print("re-register") self.manager?.register(self) } // #endif } test kernel // Copyright (c) 2016, Yuji // 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. // // 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 6/2/16. // Copyright © 2016 yuuji. All rights reserved. // public class SXQueue: KqueueManagable { public var ident: Int32 public var readAgent: Readable public var writeAgent: Writable public var service: SXService public var manager: SXKernel? public init(fd: Int32, readFrom r: Readable, writeTo w: Writable, with service: SXService) throws { self.readAgent = r self.writeAgent = w self.service = service self.ident = fd SXKernelManager.default?.register(service: service, queue: self) } public func terminate() { self.readAgent.done() self.writeAgent.done() SXKernelManager.default?.unregister(for: ident) } // #if os(Linux) // public func runloop() { // do { // if let data = try self.fd_r.read() { // // if !self.service.dataHandler(self, data) { // return terminate() // } // // } else { // return terminate() // } // // } catch { // self.service.errHandler?(self, error) // } // } // #else // public func runloop(kdata: Int, udata: UnsafeRawPointer!) { public func runloop(_ ev: event) { do { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) self.readAgent.readBufsize = ev.data + 1 #endif if let data = try self.readAgent.read() { if !self.service.dataHandler(self, data) { return terminate() } } else { return terminate() } } catch { self.service.errHandler?(self, error) } print("re-register") self.manager?.register(self) } // #endif }
// // Copyright (c) 2016 Anton Mironov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Foundation public extension Executor { static func operationQueue(_ queue: OperationQueue) -> Executor { return Executor(handler: queue.addOperation) } } public protocol ObjCInjectedExecutionContext : ExecutionContext, NSObjectProtocol { } public extension ObjCInjectedExecutionContext { func releaseOnDeinit(_ object: AnyObject) { Statics.withUniqueKey { objc_setAssociatedObject(self, $0, object, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } public protocol ObjCUIInjectedExecutionContext : ObjCInjectedExecutionContext { } public extension ObjCUIInjectedExecutionContext { var executor: Executor { return .main } } private struct Statics { static var increment: OSAtomic_int64_aligned64_t = 0 static func withUniqueKey(_ block: (UnsafeRawPointer) -> Void) { let unique = OSAtomicIncrement64Barrier(&increment) let capacity = 2 let key = UnsafeMutablePointer<Int64>.allocate(capacity: capacity) defer { key.deallocate(capacity: capacity) } key.initialize(from: [unique, 0]) block(key) } } import CoreData extension NSManagedObjectContext : ObjCInjectedExecutionContext { public var executor: Executor { return Executor { [weak self] in self?.perform($0) } } } extension NSPersistentStoreCoordinator : ObjCInjectedExecutionContext { public var executor: Executor { return Executor { [weak self] in self?.perform($0) } } } #endif #if os(macOS) import AppKit extension NSResponder : ObjCUIInjectedExecutionContext {} #endif #if os(iOS) || os(tvOS) import UIKit extension UIResponder : ObjCUIInjectedExecutionContext {} #endif #if os(watchOS) import WatchKit extension WKInterfaceController : ObjCUIInjectedExecutionContext {} extension WKInterfaceObject : ObjCUIInjectedExecutionContext {} #endif Extension for URLSession added // // Copyright (c) 2016 Anton Mironov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Foundation public extension Executor { static func operationQueue(_ queue: OperationQueue) -> Executor { return Executor(handler: queue.addOperation) } } public protocol ObjCInjectedExecutionContext : ExecutionContext, NSObjectProtocol { } private class DeinitNotifier { let block: () -> Void init(block: @escaping () -> Void) { self.block = block } deinit { self.block() } } public extension ObjCInjectedExecutionContext { func releaseOnDeinit(_ object: AnyObject) { Statics.withUniqueKey { objc_setAssociatedObject(self, $0, object, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func notifyDeinit(_ block: @escaping () -> Void) { self.releaseOnDeinit(DeinitNotifier(block: block)) } } public protocol ObjCUIInjectedExecutionContext : ObjCInjectedExecutionContext { } public extension ObjCUIInjectedExecutionContext { var executor: Executor { return .main } } private struct Statics { static var increment: OSAtomic_int64_aligned64_t = 0 static func withUniqueKey(_ block: (UnsafeRawPointer) -> Void) { let unique = OSAtomicIncrement64Barrier(&increment) let capacity = 2 let key = UnsafeMutablePointer<Int64>.allocate(capacity: capacity) defer { key.deallocate(capacity: capacity) } key.initialize(from: [unique, 0]) block(key) } } import CoreData extension NSManagedObjectContext : ObjCInjectedExecutionContext { public var executor: Executor { return Executor { [weak self] in self?.perform($0) } } } extension NSPersistentStoreCoordinator : ObjCInjectedExecutionContext { public var executor: Executor { return Executor { [weak self] in self?.perform($0) } } } public extension URLSession { private func dataFuture(context: ExecutionContext?, cancellationToken: CancellationToken?, makeTask: (@escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask) -> FallibleFuture<(Data?, URLResponse)> { let promise = FalliblePromise<(Data?, URLResponse)>() let task = makeTask { [weak promise] (data, response, error) in guard let promise = promise else { return } guard let error = error else { promise.succeed(with: (data, response!)); return } if let error = error as? URLError, error.code == .cancelled { promise.fail(with: ConcurrencyError.cancelled) } else { promise.fail(with: error) } } promise.releasePool.notifyDrain { [weak task] in task?.cancel() } cancellationToken?.notifyCancellation { [weak task, weak promise] in task?.cancel() promise?.cancel() } context?.notifyDeinit { [weak task, weak promise] in task?.cancel() promise?.cancel() } task.resume() return promise } func data(at url: URL, context: ExecutionContext? = nil, cancellationToken: CancellationToken? = nil) -> FallibleFuture<(Data?, URLResponse)> { return self.dataFuture(context: context, cancellationToken: cancellationToken) { self.dataTask(with: url, completionHandler: $0) } } func data(with request: URLRequest, context: ExecutionContext? = nil, cancellationToken: CancellationToken? = nil) -> FallibleFuture<(Data?, URLResponse)> { return self.dataFuture(context: context, cancellationToken: cancellationToken) { self.dataTask(with: request, completionHandler: $0) } } func upload(with request: URLRequest, fromFile fileURL: URL, context: ExecutionContext? = nil, cancellationToken: CancellationToken? = nil) -> FallibleFuture<(Data?, URLResponse)> { return self.dataFuture(context: context, cancellationToken: cancellationToken) { self.uploadTask(with: request, fromFile: fileURL, completionHandler: $0) } } func upload(with request: URLRequest, from bodyData: Data?, context: ExecutionContext? = nil, cancellationToken: CancellationToken? = nil) -> FallibleFuture<(Data?, URLResponse)> { return self.dataFuture(context: context, cancellationToken: cancellationToken) { self.uploadTask(with: request, from: bodyData, completionHandler: $0) } } } #endif #if os(macOS) import AppKit extension NSResponder : ObjCUIInjectedExecutionContext {} #endif #if os(iOS) || os(tvOS) import UIKit extension UIResponder : ObjCUIInjectedExecutionContext {} #endif #if os(watchOS) import WatchKit extension WKInterfaceController : ObjCUIInjectedExecutionContext {} extension WKInterfaceObject : ObjCUIInjectedExecutionContext {} #endif
// // Spotify.swift // SpotMenu // // Created by Miklós Kristyán on 02/09/16. // Copyright © 2016 KM. All rights reserved. // import Foundation open class Spotify: NSObject { // MARK: - Variables open static var currentTrack = Track() open static var playerState: PlayerState { get { if let state = Spotify.executeAppleScriptWithString("get player state") { //print(state) if let stateEnum = PlayerState(rawValue: state) { return stateEnum } } return PlayerState.paused } set { switch newValue { case .paused: _ = Spotify.executeAppleScriptWithString("pause") case .playing: _ = Spotify.executeAppleScriptWithString("play") } NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } } // MARK: - Methods open static func playNext(_ completionHandler: (()->())? = nil){ _ = Spotify.executeAppleScriptWithString("play (next track)") completionHandler?() NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } open static func playPrevious(_ completionHandler: (() -> ())? = nil){ _ = Spotify.executeAppleScriptWithString("play (previous track)") completionHandler?() NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } // MARK: - Helpers static func executeAppleScriptWithString(_ command: String) -> String? { let myAppleScript = "if application \"Spotify\" is running then tell application \"Spotify\" to \(command)" //print(myAppleScript) var error: NSDictionary? if let scriptObject = NSAppleScript(source: myAppleScript) { if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError( &error) { return output.stringValue } else if (error != nil) { print("error: \(error)") } } return nil } } spotify module, option to start spotify added // // Spotify.swift // SpotMenu // // Created by Miklós Kristyán on 02/09/16. // Copyright © 2016 KM. All rights reserved. // import Foundation open class Spotify: NSObject { // MARK: - Variables open static var currentTrack = Track() open static var playerState: PlayerState { get { if let state = Spotify.executeAppleScriptWithString("get player state") { //print(state) if let stateEnum = PlayerState(rawValue: state) { return stateEnum } } return PlayerState.paused } set { switch newValue { case .paused: _ = Spotify.executeAppleScriptWithString("pause") case .playing: _ = Spotify.executeAppleScriptWithString("play") } NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } } // MARK: - Methods open static func playNext(_ completionHandler: (()->())? = nil){ _ = Spotify.executeAppleScriptWithString("play (next track)") completionHandler?() NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } open static func playPrevious(_ completionHandler: (() -> ())? = nil){ _ = Spotify.executeAppleScriptWithString("play (previous track)") completionHandler?() NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } open static func startSpotify(hidden: Bool = true, completionHandler: (() -> ())? = nil){ let option: StartOptions switch hidden { case true: option = .withoutUI case false: option = .withUI } _ = Spotify.startSpotify(option: option) completionHandler?() NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotification.key), object: self) } // MARK: - Helpers static func executeAppleScriptWithString(_ command: String) -> String? { let myAppleScript = "if application \"Spotify\" is running then tell application \"Spotify\" to \(command)" var error: NSDictionary? if let scriptObject = NSAppleScript(source: myAppleScript) { return scriptObject.executeAndReturnError(&error).stringValue } return nil } enum StartOptions { case withUI case withoutUI } static func startSpotify(option:StartOptions) -> String?{ let command:String; switch option { case .withoutUI: command = "run" case .withUI: command = "launch" } let myAppleScript = "if application \"Spotify\" is not running then \(command) application \"Spotify\"" //print(myAppleScript) var error: NSDictionary? if let scriptObject = NSAppleScript(source: myAppleScript) { return scriptObject.executeAndReturnError(&error).stringValue } return nil } }
// // Drop.swift // SwiftyDrop // // Created by MORITANAOKI on 2015/06/18. // import UIKit public enum DropState { case Default, Info, Success, Warning, Error private func backgroundColor() -> UIColor? { switch self { case Default: return UIColor(red: 41/255.0, green: 128/255.0, blue: 185/255.0, alpha: 1.0) case Info: return UIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0) case Success: return UIColor(red: 39/255.0, green: 174/255.0, blue: 96/255.0, alpha: 1.0) case Warning: return UIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0) case Error: return UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1.0) } } } public enum DropBlur { case Light, ExtraLight, Dark private func blurEffect() -> UIBlurEffect { switch self { case .Light: return UIBlurEffect(style: .Light) case .ExtraLight: return UIBlurEffect(style: .ExtraLight) case .Dark: return UIBlurEffect(style: .Dark) } } } public final class Drop: UIView { private var backgroundView: UIView! private var statusLabel: UILabel! private var topConstraint: NSLayoutConstraint! private var heightConstraint: NSLayoutConstraint! private let statusTopMargin: CGFloat = 8.0 private let statusBottomMargin: CGFloat = 8.0 private var upTimer: NSTimer? override init(frame: CGRect) { super.init(frame: frame) heightConstraint = NSLayoutConstraint( item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100.0 ) self.addConstraint(heightConstraint) restartUpTimer(4.0) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { upTimer?.invalidate() upTimer = nil } func up() { restartUpTimer(0.0) } func upFromTimer(timer: NSTimer) { if let interval = timer.userInfo as? Double { Drop.up(self, interval: interval) } } private func restartUpTimer(after: Double) { restartUpTimer(after, interval: 0.25) } private func restartUpTimer(after: Double, interval: Double) { upTimer?.invalidate() upTimer = nil upTimer = NSTimer.scheduledTimerWithTimeInterval(after, target: self, selector: "upFromTimer:", userInfo: interval, repeats: false) } private func updateHeight() { heightConstraint.constant = self.statusLabel.frame.size.height + Drop.statusBarHeight() + statusTopMargin + statusBottomMargin self.layoutIfNeeded() } } extension Drop { public class func down(status: String) { down(status, state: .Default) } public class func down(status: String, state: DropState) { down(status, state: state, blur: nil) } public class func down(status: String, blur: DropBlur) { down(status, state: nil, blur: blur) } private class func down(status: String, state: DropState?, blur: DropBlur?) { self.upAll() let drop = Drop(frame: CGRectZero) Drop.window().addSubview(drop) let sideConstraints = ([.Left, .Right] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: drop, attribute: $0, relatedBy: .Equal, toItem: Drop.window(), attribute: $0, multiplier: 1.0, constant: 0.0 ) } drop.topConstraint = NSLayoutConstraint( item: drop, attribute: .Top, relatedBy: .Equal, toItem: Drop.window(), attribute: .Top, multiplier: 1.0, constant: -drop.heightConstraint.constant ) Drop.window().addConstraints(sideConstraints) Drop.window().addConstraint(drop.topConstraint) drop.setup(status, state: state, blur: blur) drop.updateHeight() drop.topConstraint.constant = 0.0 UIView.animateWithDuration( NSTimeInterval(0.25), delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseOut, animations: { [weak drop] () -> Void in if let drop = drop { drop.layoutIfNeeded() } }, completion: nil ) } private class func up(drop: Drop, interval: NSTimeInterval) { drop.topConstraint.constant = -drop.heightConstraint.constant UIView.animateWithDuration( interval, delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseIn, animations: { [weak drop] () -> Void in if let drop = drop { drop.layoutIfNeeded() } }) { [weak drop] finished -> Void in if let drop = drop { drop.removeFromSuperview() } } } public class func upAll() { for view in Drop.window().subviews { if let drop = view as? Drop { drop.up() } } } } extension Drop { private func setup(status: String, state: DropState?, blur: DropBlur?) { self.setTranslatesAutoresizingMaskIntoConstraints(false) if let blur = blur { let blurEffect = blur.blurEffect() // Visual Effect View let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(visualEffectView) let visualEffectViewConstraints = ([.Top, .Right, .Bottom, .Left] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: visualEffectView, attribute: $0, relatedBy: .Equal, toItem: self, attribute: $0, multiplier: 1.0, constant: 0.0 ) } self.addConstraints(visualEffectViewConstraints) self.backgroundView = visualEffectView // Vibrancy Effect View let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) vibrancyEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) visualEffectView.contentView.addSubview(vibrancyEffectView) let vibrancyLeft = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Left, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .LeftMargin, multiplier: 1.0, constant: 0.0 ) let vibrancyRight = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Right, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .RightMargin, multiplier: 1.0, constant: 0.0 ) let vibrancyTop = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Top, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .Top, multiplier: 1.0, constant: Drop.statusBarHeight() + statusTopMargin ) let vibrancyBottom = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0 ) visualEffectView.contentView.addConstraints([vibrancyTop, vibrancyRight, vibrancyBottom, vibrancyLeft]) // STATUS LABEL let statusLabel = createStatusLabel(status, isVisualEffect: true) vibrancyEffectView.contentView.addSubview(statusLabel) let statusLeft = NSLayoutConstraint( item: statusLabel, attribute: .Left, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Left, multiplier: 1.0, constant: 0.0 ) let statusRight = NSLayoutConstraint( item: statusLabel, attribute: .Right, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Right, multiplier: 1.0, constant: 0.0 ) let statusTop = NSLayoutConstraint( item: statusLabel, attribute: .Top, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Top, multiplier: 1.0, constant: 0.0 ) vibrancyEffectView.contentView.addConstraints([statusTop, statusRight, statusLeft]) self.statusLabel = statusLabel } if let state = state { // Background View let backgroundView = UIView(frame: CGRectZero) backgroundView.setTranslatesAutoresizingMaskIntoConstraints(false) backgroundView.alpha = 0.9 backgroundView.backgroundColor = state.backgroundColor() self.addSubview(backgroundView) let backgroundConstraints = ([.Top, .Right, .Bottom, .Left] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: backgroundView, attribute: $0, relatedBy: .Equal, toItem: self, attribute: $0, multiplier: 1.0, constant: 0.0 ) } self.addConstraints(backgroundConstraints) self.backgroundView = backgroundView // Status Label let statusLabel = createStatusLabel(status, isVisualEffect: false) self.addSubview(statusLabel) let statusLeft = NSLayoutConstraint( item: statusLabel, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .LeftMargin, multiplier: 1.0, constant: 0.0 ) let statusRight = NSLayoutConstraint( item: statusLabel, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .RightMargin, multiplier: 1.0, constant: 0.0 ) let statusTop = NSLayoutConstraint( item: statusLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: Drop.statusBarHeight() + statusTopMargin ) self.addConstraints([statusLeft, statusRight, statusTop]) self.statusLabel = statusLabel } self.layoutIfNeeded() let tapRecognizer = UITapGestureRecognizer(target: self, action: "up:") self.addGestureRecognizer(tapRecognizer) let panRecognizer = UIPanGestureRecognizer(target: self, action: "pan:") self.addGestureRecognizer(panRecognizer) } private func createStatusLabel(status: String, isVisualEffect: Bool) -> UILabel { let label = UILabel(frame: CGRectZero) label.setTranslatesAutoresizingMaskIntoConstraints(false) label.numberOfLines = 0 label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.textAlignment = .Center label.text = status if !isVisualEffect { label.textColor = UIColor.whiteColor() } return label } } extension Drop { func up(sender: AnyObject) { self.up() } func pan(sender: AnyObject) { let pan = sender as! UIPanGestureRecognizer switch pan.state { case .Began: upTimer?.invalidate() upTimer = nil case .Changed: if let window = Drop.window() { let point = pan.translationInView(window) let location = pan.locationInView(window) let y = topConstraint.constant - point.y if y < 0 { topConstraint.constant = 0.0; break } if location.y > self.frame.size.height { break } topConstraint.constant = y self.layoutIfNeeded() pan.setTranslation(CGPointZero, inView: window) } case .Ended: if topConstraint.constant > 0.0 { restartUpTimer(0.0, interval: 0.1) } else { restartUpTimer(2.0) topConstraint.constant = 0.0 UIView.animateWithDuration( NSTimeInterval(0.1), delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseOut, animations: { [weak self] () -> Void in if let s = self { s.layoutIfNeeded() } }, completion: nil ) } case .Failed, .Cancelled: restartUpTimer(2.0) case .Possible: break } } } extension Drop { private class func window() -> UIWindow { return UIApplication.sharedApplication().keyWindow! } private class func statusBarHeight() -> CGFloat { return UIApplication.sharedApplication().statusBarFrame.size.height } } Change animation // // Drop.swift // SwiftyDrop // // Created by MORITANAOKI on 2015/06/18. // import UIKit public enum DropState { case Default, Info, Success, Warning, Error private func backgroundColor() -> UIColor? { switch self { case Default: return UIColor(red: 41/255.0, green: 128/255.0, blue: 185/255.0, alpha: 1.0) case Info: return UIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0) case Success: return UIColor(red: 39/255.0, green: 174/255.0, blue: 96/255.0, alpha: 1.0) case Warning: return UIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0) case Error: return UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1.0) } } } public enum DropBlur { case Light, ExtraLight, Dark private func blurEffect() -> UIBlurEffect { switch self { case .Light: return UIBlurEffect(style: .Light) case .ExtraLight: return UIBlurEffect(style: .ExtraLight) case .Dark: return UIBlurEffect(style: .Dark) } } } public final class Drop: UIView { private var backgroundView: UIView! private var statusLabel: UILabel! private var topConstraint: NSLayoutConstraint! private var heightConstraint: NSLayoutConstraint! private let statusTopMargin: CGFloat = 8.0 private let statusBottomMargin: CGFloat = 8.0 private var upTimer: NSTimer? private var startTop: CGFloat? override init(frame: CGRect) { super.init(frame: frame) heightConstraint = NSLayoutConstraint( item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100.0 ) self.addConstraint(heightConstraint) restartUpTimer(4.0) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { upTimer?.invalidate() upTimer = nil } func up() { restartUpTimer(0.0) } func upFromTimer(timer: NSTimer) { if let interval = timer.userInfo as? Double { Drop.up(self, interval: interval) } } private func restartUpTimer(after: Double) { restartUpTimer(after, interval: 0.25) } private func restartUpTimer(after: Double, interval: Double) { upTimer?.invalidate() upTimer = nil upTimer = NSTimer.scheduledTimerWithTimeInterval(after, target: self, selector: "upFromTimer:", userInfo: interval, repeats: false) } private func updateHeight() { heightConstraint.constant = self.statusLabel.frame.size.height + Drop.statusBarHeight() + statusTopMargin + statusBottomMargin self.layoutIfNeeded() } } extension Drop { public class func down(status: String) { down(status, state: .Default) } public class func down(status: String, state: DropState) { down(status, state: state, blur: nil) } public class func down(status: String, blur: DropBlur) { down(status, state: nil, blur: blur) } private class func down(status: String, state: DropState?, blur: DropBlur?) { self.upAll() let drop = Drop(frame: CGRectZero) Drop.window().addSubview(drop) let sideConstraints = ([.Left, .Right] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: drop, attribute: $0, relatedBy: .Equal, toItem: Drop.window(), attribute: $0, multiplier: 1.0, constant: 0.0 ) } drop.topConstraint = NSLayoutConstraint( item: drop, attribute: .Top, relatedBy: .Equal, toItem: Drop.window(), attribute: .Top, multiplier: 1.0, constant: -drop.heightConstraint.constant ) Drop.window().addConstraints(sideConstraints) Drop.window().addConstraint(drop.topConstraint) drop.setup(status, state: state, blur: blur) drop.updateHeight() drop.topConstraint.constant = 0.0 UIView.animateWithDuration( NSTimeInterval(0.25), delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseOut, animations: { [weak drop] () -> Void in if let drop = drop { drop.layoutIfNeeded() } }, completion: nil ) } private class func up(drop: Drop, interval: NSTimeInterval) { drop.topConstraint.constant = -drop.heightConstraint.constant UIView.animateWithDuration( interval, delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseIn, animations: { [weak drop] () -> Void in if let drop = drop { drop.layoutIfNeeded() } }) { [weak drop] finished -> Void in if let drop = drop { drop.removeFromSuperview() } } } public class func upAll() { for view in Drop.window().subviews { if let drop = view as? Drop { drop.up() } } } } extension Drop { private func setup(status: String, state: DropState?, blur: DropBlur?) { self.setTranslatesAutoresizingMaskIntoConstraints(false) if let blur = blur { let blurEffect = blur.blurEffect() // Visual Effect View let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(visualEffectView) let visualEffectViewConstraints = ([.Top, .Right, .Bottom, .Left] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: visualEffectView, attribute: $0, relatedBy: .Equal, toItem: self, attribute: $0, multiplier: 1.0, constant: 0.0 ) } self.addConstraints(visualEffectViewConstraints) self.backgroundView = visualEffectView // Vibrancy Effect View let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) vibrancyEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) visualEffectView.contentView.addSubview(vibrancyEffectView) let vibrancyLeft = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Left, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .LeftMargin, multiplier: 1.0, constant: 0.0 ) let vibrancyRight = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Right, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .RightMargin, multiplier: 1.0, constant: 0.0 ) let vibrancyTop = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Top, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .Top, multiplier: 1.0, constant: Drop.statusBarHeight() + statusTopMargin ) let vibrancyBottom = NSLayoutConstraint( item: vibrancyEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: visualEffectView.contentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0 ) visualEffectView.contentView.addConstraints([vibrancyTop, vibrancyRight, vibrancyBottom, vibrancyLeft]) // STATUS LABEL let statusLabel = createStatusLabel(status, isVisualEffect: true) vibrancyEffectView.contentView.addSubview(statusLabel) let statusLeft = NSLayoutConstraint( item: statusLabel, attribute: .Left, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Left, multiplier: 1.0, constant: 0.0 ) let statusRight = NSLayoutConstraint( item: statusLabel, attribute: .Right, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Right, multiplier: 1.0, constant: 0.0 ) let statusTop = NSLayoutConstraint( item: statusLabel, attribute: .Top, relatedBy: .Equal, toItem: vibrancyEffectView.contentView, attribute: .Top, multiplier: 1.0, constant: 0.0 ) vibrancyEffectView.contentView.addConstraints([statusTop, statusRight, statusLeft]) self.statusLabel = statusLabel } if let state = state { // Background View let backgroundView = UIView(frame: CGRectZero) backgroundView.setTranslatesAutoresizingMaskIntoConstraints(false) backgroundView.alpha = 0.9 backgroundView.backgroundColor = state.backgroundColor() self.addSubview(backgroundView) let backgroundConstraints = ([.Top, .Right, .Bottom, .Left] as [NSLayoutAttribute]).map { return NSLayoutConstraint( item: backgroundView, attribute: $0, relatedBy: .Equal, toItem: self, attribute: $0, multiplier: 1.0, constant: 0.0 ) } self.addConstraints(backgroundConstraints) self.backgroundView = backgroundView // Status Label let statusLabel = createStatusLabel(status, isVisualEffect: false) self.addSubview(statusLabel) let statusLeft = NSLayoutConstraint( item: statusLabel, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .LeftMargin, multiplier: 1.0, constant: 0.0 ) let statusRight = NSLayoutConstraint( item: statusLabel, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .RightMargin, multiplier: 1.0, constant: 0.0 ) let statusTop = NSLayoutConstraint( item: statusLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: Drop.statusBarHeight() + statusTopMargin ) self.addConstraints([statusLeft, statusRight, statusTop]) self.statusLabel = statusLabel } self.layoutIfNeeded() let tapRecognizer = UITapGestureRecognizer(target: self, action: "up:") self.addGestureRecognizer(tapRecognizer) let panRecognizer = UIPanGestureRecognizer(target: self, action: "pan:") self.addGestureRecognizer(panRecognizer) } private func createStatusLabel(status: String, isVisualEffect: Bool) -> UILabel { let label = UILabel(frame: CGRectZero) label.setTranslatesAutoresizingMaskIntoConstraints(false) label.numberOfLines = 0 label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.textAlignment = .Center label.text = status if !isVisualEffect { label.textColor = UIColor.whiteColor() } return label } } extension Drop { func up(sender: AnyObject) { self.up() } func pan(sender: AnyObject) { let pan = sender as! UIPanGestureRecognizer switch pan.state { case .Began: upTimer?.invalidate() upTimer = nil startTop = topConstraint.constant case .Changed: let location = pan.locationInView(Drop.window()) let translation = pan.translationInView(Drop.window()) let top = startTop! + translation.y topConstraint.constant = top case .Ended: if topConstraint.constant < 0.0 { restartUpTimer(0.0, interval: 0.1) } else { restartUpTimer(4.0) topConstraint.constant = 0.0 UIView.animateWithDuration( NSTimeInterval(0.1), delay: NSTimeInterval(0.0), options: .AllowUserInteraction | .CurveEaseOut, animations: { [weak self] () -> Void in if let s = self { s.layoutIfNeeded() } }, completion: nil ) } break case .Failed, .Cancelled: restartUpTimer(2.0) case .Possible: break } } } extension Drop { private class func window() -> UIWindow { return UIApplication.sharedApplication().keyWindow! } private class func statusBarHeight() -> CGFloat { return UIApplication.sharedApplication().statusBarFrame.size.height } }
// // Client.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Argo import Foundation import ReactiveCocoa import Result extension NSJSONSerialization { internal static func deserializeJSON(data: NSData) -> Result<NSDictionary, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary) } } extension NSURLRequest { internal static func create(server: Server, _ endpoint: Client.Endpoint) -> NSURLRequest { let URL = NSURL(string: server.endpoint)!.URLByAppendingPathComponent(endpoint.path) return NSURLRequest(URL: URL) } } /// A GitHub API Client public final class Client { /// An error from the Client. public enum Error: ErrorType { /// An error occurred in a network operation. case NetworkError(NSError) /// An error occurred while deserializing JSON. case JSONDeserializationError(NSError) /// An error occurred while decoding JSON. case JSONDecodingError(DecodeError) } /// A GitHub API endpoint. internal enum Endpoint: Hashable { case ReleaseByTagName(owner: String, repository: String, tag: String) var path: String { switch self { case let .ReleaseByTagName(owner, repo, tag): return "/repos/\(owner)/\(repo)/releases/tags/\(tag)" } } var hashValue: Int { switch self { case let .ReleaseByTagName(owner, repo, tag): return owner.hashValue ^ repo.hashValue ^ tag.hashValue } } } /// The Server that the Client connects to. public let server: Server /// Create an unauthenticated client for the given Server. public init(_ server: Server) { self.server = server } /// Fetch the release corresponding to the given tag in the given repository. public func releaseForTag(tag: String, inRepository repository: Repository) -> SignalProducer<Release, Error> { precondition(repository.server == server) return fetchOne(Endpoint.ReleaseByTagName(owner: repository.owner, repository: repository.name, tag: tag)) } /// Fetch an object from the API. internal func fetchOne<Object: Decodable where Object.DecodedType == Object>(endpoint: Endpoint) -> SignalProducer<Object, Error> { return NSURLSession .sharedSession() .rac_dataWithRequest(NSURLRequest.create(server, endpoint)) .mapError(Error.NetworkError) .flatMap(FlattenStrategy.Concat) { data, response in return SignalProducer .attempt { NSJSONSerialization.deserializeJSON(data) } .mapError(Error.JSONDeserializationError) } .attemptMap { JSON in switch Object.decode(.parse(JSON)) { case let .Success(object): return .Success(object) case let .Failure(error): return .Failure(.JSONDecodingError(error)) } } } } internal func ==(lhs: Client.Endpoint, rhs: Client.Endpoint) -> Bool { switch (lhs, rhs) { case let (.ReleaseByTagName(owner1, repo1, tag1), .ReleaseByTagName(owner2, repo2, tag2)): return owner1 == owner2 && repo1 == repo2 && tag1 == tag2 } } Simplify JSON decoding // // Client.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Argo import Foundation import ReactiveCocoa import Result extension Decodable { internal static func decode(JSON: NSDictionary) -> Result<DecodedType, DecodeError> { switch decode(.parse(JSON)) { case let .Success(object): return .Success(object) case let .Failure(error): return .Failure(error) } } } extension NSJSONSerialization { internal static func deserializeJSON(data: NSData) -> Result<NSDictionary, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary) } } extension NSURLRequest { internal static func create(server: Server, _ endpoint: Client.Endpoint) -> NSURLRequest { let URL = NSURL(string: server.endpoint)!.URLByAppendingPathComponent(endpoint.path) return NSURLRequest(URL: URL) } } /// A GitHub API Client public final class Client { /// An error from the Client. public enum Error: ErrorType { /// An error occurred in a network operation. case NetworkError(NSError) /// An error occurred while deserializing JSON. case JSONDeserializationError(NSError) /// An error occurred while decoding JSON. case JSONDecodingError(DecodeError) } /// A GitHub API endpoint. internal enum Endpoint: Hashable { case ReleaseByTagName(owner: String, repository: String, tag: String) var path: String { switch self { case let .ReleaseByTagName(owner, repo, tag): return "/repos/\(owner)/\(repo)/releases/tags/\(tag)" } } var hashValue: Int { switch self { case let .ReleaseByTagName(owner, repo, tag): return owner.hashValue ^ repo.hashValue ^ tag.hashValue } } } /// The Server that the Client connects to. public let server: Server /// Create an unauthenticated client for the given Server. public init(_ server: Server) { self.server = server } /// Fetch the release corresponding to the given tag in the given repository. public func releaseForTag(tag: String, inRepository repository: Repository) -> SignalProducer<Release, Error> { precondition(repository.server == server) return fetchOne(Endpoint.ReleaseByTagName(owner: repository.owner, repository: repository.name, tag: tag)) } /// Fetch an object from the API. internal func fetchOne<Object: Decodable where Object.DecodedType == Object>(endpoint: Endpoint) -> SignalProducer<Object, Error> { return NSURLSession .sharedSession() .rac_dataWithRequest(NSURLRequest.create(server, endpoint)) .mapError(Error.NetworkError) .flatMap(.Concat) { data, response in return SignalProducer .attempt { return NSJSONSerialization.deserializeJSON(data).mapError(Error.JSONDeserializationError) } .attemptMap { JSON in return Object.decode(JSON).mapError(Error.JSONDecodingError) } } } } internal func ==(lhs: Client.Endpoint, rhs: Client.Endpoint) -> Bool { switch (lhs, rhs) { case let (.ReleaseByTagName(owner1, repo1, tag1), .ReleaseByTagName(owner2, repo2, tag2)): return owner1 == owner2 && repo1 == repo2 && tag1 == tag2 } }
// Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation struct Constants { /* Contents of test files: - test1: text file with "Hello, World!\n". - test2: text file with copyright free song lyrics from http://www.freesonglyrics.co.uk/lyrics13.html - test3: text file with random string from https://www.random.org/strings/ - test4: text file with string "I'm a tester" repeated several times. - test5: empty file. // TODO: Rename to empty_file - test6: file with size of 5MB containing nulls from /dev/null. - test7: file with size of 5MB containing random bytes from /dev/urandom. - test8: text file from lzma_specification. - test9: file with size of 10KB containing random bytes from /dev/urandom. */ static func data(forTest name: String, withType ext: String) -> Data? { if let url = Constants.url(forTest: name, withType: ext) { return try? Data(contentsOf: url, options: .mappedIfSafe) } else { return nil } } private static func url(forTest name: String, withType ext: String) -> URL? { return testBundle.url(forResource: name, withExtension: ext) } static func data(forAnswer name: String) -> Data? { if name == "empty_file" { return Data() } if let url = Constants.url(forAnswer: name) { return try? Data(contentsOf: url, options: .mappedIfSafe) } else { return nil } } private static func url(forAnswer name: String) -> URL? { return testBundle.url(forResource: name, withExtension: "answer") } private static let testBundle: Bundle = Bundle(for: DeflateTests.self) } Remove empty_file special case in getting test data // Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation struct Constants { /* Contents of test files: - test1: text file with "Hello, World!\n". - test2: text file with copyright free song lyrics from http://www.freesonglyrics.co.uk/lyrics13.html - test3: text file with random string from https://www.random.org/strings/ - test4: text file with string "I'm a tester" repeated several times. - test6: file with size of 5MB containing nulls from /dev/null. - test7: file with size of 5MB containing random bytes from /dev/urandom. - test8: text file from lzma_specification. - test9: file with size of 10KB containing random bytes from /dev/urandom. */ static func data(forTest name: String, withType ext: String) -> Data? { if let url = Constants.url(forTest: name, withType: ext) { return try? Data(contentsOf: url, options: .mappedIfSafe) } else { return nil } } private static func url(forTest name: String, withType ext: String) -> URL? { return testBundle.url(forResource: name, withExtension: ext) } static func data(forAnswer name: String) -> Data? { if let url = Constants.url(forAnswer: name) { return try? Data(contentsOf: url, options: .mappedIfSafe) } else { return nil } } private static func url(forAnswer name: String) -> URL? { return testBundle.url(forResource: name, withExtension: "answer") } private static let testBundle: Bundle = Bundle(for: DeflateTests.self) }
import XCTest import MySQLTestSuite var tests = [XCTestCaseEntry]() tests += MySQLTestSuite.allTests() XCTMain(tests) Fixed Linux testing import XCTest @testable import MySQLTests XCTMain([ testCase(MySQLTests.allTests), ])
import XCTest import CoreTests import FileTests // import HTTPClientTests // import HTTPFileTests import HTTPServerTests import HTTPTests import IPTests // import OpenSSLTests import POSIXTests import ReflectionTests import TCPTests import VeniceTests var testCases = [ // POSIX testCase(POSIXTests.allTests), testCase(EnvironmentTests.allTests), // Core testCase(JSONTests.allTests), testCase(LoggerTests.allTests), testCase(InternalTests.allTests), testCase(MapConvertibleTests.allTests), testCase(PerformanceTests.allTests), testCase(PublicTests.allTests), testCase(StringTests.allTests), testCase(MapTests.allTests), testCase(URLEncodedFormParserTests.allTests), // HTTP testCase(RequestContentTests.allTests), testCase(ResponseContentTests.allTests), testCase(AttributedCookieTests.allTests), testCase(BodyTests.allTests), testCase(CookieTests.allTests), testCase(MessageTests.allTests), testCase(RequestTests.allTests), testCase(ResponseTests.allTests), testCase(BasicAuthMiddlewareTests.allTests), testCase(ContentNegotiationMiddlewareTests.allTests), testCase(LogMiddlewareTests.allTests), testCase(RecoveryMiddlewareTests.allTests), testCase(RedirectMiddlewareTests.allTests), testCase(SessionMiddlewareTests.allTests), testCase(RequestParserTests.allTests), testCase(ResponseParserTests.allTests), testCase(ResourceTests.allTests), testCase(RouterTests.allTests), testCase(RoutesTests.allTests), testCase(TrieRouteMatcherTests.allTests), testCase(HTTPSerializerTests.allTests), testCase(ServerTests.allTests), ] #if os(macOS) testCases += [ testCase(CoroutineTests.allTests), testCase(ChannelTests.allTests), testCase(FallibleChannelTests.allTests), testCase(FileTests.allTests), testCase(IPTests.allTests), testCase(SelectTests.allTests), testCase(TCPTests.allTests), testCase(TickerTests.allTests), testCase(TimerTests.allTests), ] #endif XCTMain(testCases) add back Venice tests on Linux import XCTest import CoreTests import FileTests // import HTTPClientTests // import HTTPFileTests import HTTPServerTests import HTTPTests import IPTests // import OpenSSLTests import POSIXTests import ReflectionTests import TCPTests import VeniceTests var testCases = [ // POSIX testCase(POSIXTests.allTests), testCase(EnvironmentTests.allTests), // Core testCase(JSONTests.allTests), testCase(LoggerTests.allTests), testCase(InternalTests.allTests), testCase(MapConvertibleTests.allTests), testCase(PerformanceTests.allTests), testCase(PublicTests.allTests), testCase(StringTests.allTests), testCase(MapTests.allTests), testCase(URLEncodedFormParserTests.allTests), // HTTP testCase(RequestContentTests.allTests), testCase(ResponseContentTests.allTests), testCase(AttributedCookieTests.allTests), testCase(BodyTests.allTests), testCase(CookieTests.allTests), testCase(MessageTests.allTests), testCase(ResponseTests.allTests), testCase(BasicAuthMiddlewareTests.allTests), testCase(ContentNegotiationMiddlewareTests.allTests), testCase(LogMiddlewareTests.allTests), testCase(RecoveryMiddlewareTests.allTests), testCase(RedirectMiddlewareTests.allTests), testCase(SessionMiddlewareTests.allTests), testCase(RequestParserTests.allTests), testCase(ResponseParserTests.allTests), testCase(ResourceTests.allTests), testCase(RouterTests.allTests), testCase(RoutesTests.allTests), testCase(TrieRouteMatcherTests.allTests), testCase(HTTPSerializerTests.allTests), testCase(ServerTests.allTests), // Venice testCase(CoroutineTests.allTests), testCase(ChannelTests.allTests), testCase(FallibleChannelTests.allTests), testCase(FileTests.allTests), testCase(IPTests.allTests), testCase(SelectTests.allTests), testCase(TCPTests.allTests), testCase(TickerTests.allTests), testCase(TimerTests.allTests), ] #if os(macOS) testCases += [ testCase(RequestTests.allTests), ] #endif XCTMain(testCases)
// // Decks.swift // HSTracker // // Created by Benjamin Michotte on 17/04/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import CleanroomLogger import RealmSwift final class Decks { static let instance = Decks() private var _decks = [String: Deck]() private var savePath: String? { if let path = Settings.instance.deckPath { return path } return nil } func loadDecks(splashscreen: Splashscreen?) { let fileManager = FileManager.default if let destination = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first { let realm = "\(destination)/HSTracker/hstracker.realm" if fileManager.fileExists(atPath: realm) { do { try fileManager.copyItem(atPath: realm, toPath: "\(realm).backup") Log.info?.message("Database backuped") } catch { Log.error?.message("Can not save backup : \(error)") } } } if let path = savePath { // load decks var files: [String]? = nil do { files = try fileManager.contentsOfDirectory(atPath: path) } catch { Log.error?.message("Can not read content of \(path)") } if let files = files { let jsonFiles = files.filter({ $0.hasSuffix(".json") }) DispatchQueue.main.async { splashscreen?.display(String(format: NSLocalizedString("Loading decks", comment: "")), total: Double(jsonFiles.count)) } do { let realm = try Realm() for file in jsonFiles { DispatchQueue.main.async { splashscreen?.increment() } load(file: file, realm: realm) } } catch { Log.error?.message("\(error)") } } } } fileprivate func load(file: String, realm: Realm) { guard let path = savePath else { Log.warning?.message("SavePath does not exists for decks") return } guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: "\(path)/\(file)")) else { Log.error?.message("\(path)/\(file) is not a valid file ???") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)") } return } let json: [String: Any]? do { json = try JSONSerialization .jsonObject(with: jsonData, options: .allowFragments) as? [String: Any] } catch { Log.error?.message("\(path)/\(file) is not a valid json file") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } guard let data = json else { do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } guard let cardClass = data["playerClass"] as? String, let playerClass = CardClass(rawValue: cardClass.lowercased()) else { Log.error?.message("\(data["playerClass"]) is not a valid class") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } let deck = Deck() deck.isArena = data["isArena"] as? Bool ?? false deck.name = data["name"] as? String ?? "unknown deck" deck.isActive = data["isActive"] as? Bool ?? true if let date = data["creationDate"] as? String { deck.creationDate = Date(fromString: date, inFormat: "YYYY-MM-dd HH:mm:ss") } deck.hearthstatsId.value = data["hearthstatsId"] as? Int deck.hearthstatsVersionId.value = data["hearthstatsVersionId"] as? Int deck.playerClass = playerClass deck.version = data["version"] as? String ?? "1.0" if let cards = data["cards"] as? [String: Int] { for (id, count) in cards { deck.cards.append(RealmCard(id: id, count: count)) } } if let jsonStats = data["statistics"] as? [[String: Any]] { for stats in jsonStats { guard let opClass = stats["opponentClass"] as? String, let opponentClass = CardClass(rawValue: opClass.lowercased()) else { continue } let stat = Statistic() stat.opponentClass = opponentClass stat.hsReplayId = stats["hsReplayId"] as? String stat.gameResult = GameResult(rawValue: stats["gameResult"] as? Int ?? 0) ?? .unknow stat.duration = stats["duration"] as? Int ?? 0 stat.opponentRank.value = stats["opponentRank"] as? Int stat.playerRank = stats["playerRank"] as? Int ?? 0 stat.playerMode = GameMode(rawValue: stats["playerMode"] as? Int ?? GameMode.none.rawValue) ?? .none stat.note = stats["note"] as? String ?? "" if let date = data["date"] as? String { stat.date = Date(fromString: date, inFormat: "YYYY-MM-dd HH:mm:ss") } stat.season.value = stats["season"] as? Int stat.numTurns = stats["numTurns"] as? Int ?? 0 stat.hasCoin = stats["hasCoin"] as? Bool ?? false stat.opponentName = stats["opponentName"] as? String ?? "Unknown" guard let cards = stats["cards"] as? [String: Int] else { continue } for (id, count) in cards { stat.cards.append(RealmCard(id: id, count: count)) } deck.statistics.append(stat) } } if deck.isValid() { do { try realm.write { realm.add(deck) } } catch { Log.error?.message("Can not save deck") } } do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } } } realm.backup is correctly backuped // // Decks.swift // HSTracker // // Created by Benjamin Michotte on 17/04/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import CleanroomLogger import RealmSwift final class Decks { static let instance = Decks() private var _decks = [String: Deck]() private var savePath: String? { if let path = Settings.instance.deckPath { return path } return nil } func loadDecks(splashscreen: Splashscreen?) { let fileManager = FileManager.default if let destination = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first { let realm = "\(destination)/HSTracker/hstracker.realm" if fileManager.fileExists(atPath: realm) { do { let backup = "\(realm).backup" if fileManager.fileExists(atPath: backup) { try fileManager.replaceItem(at: URL(fileURLWithPath: backup), withItemAt: URL(fileURLWithPath: realm), backupItemName: nil, resultingItemURL: nil) } else { try fileManager.copyItem(atPath: realm, toPath: backup) } Log.info?.message("Database backuped") } catch { Log.error?.message("Can not save backup : \(error)") } } } if let path = savePath { // load decks var files: [String]? = nil do { files = try fileManager.contentsOfDirectory(atPath: path) } catch { Log.error?.message("Can not read content of \(path)") } if let files = files { let jsonFiles = files.filter({ $0.hasSuffix(".json") }) DispatchQueue.main.async { splashscreen?.display(String(format: NSLocalizedString("Loading decks", comment: "")), total: Double(jsonFiles.count)) } do { let realm = try Realm() for file in jsonFiles { DispatchQueue.main.async { splashscreen?.increment() } load(file: file, realm: realm) } } catch { Log.error?.message("\(error)") } } } } fileprivate func load(file: String, realm: Realm) { guard let path = savePath else { Log.warning?.message("SavePath does not exists for decks") return } guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: "\(path)/\(file)")) else { Log.error?.message("\(path)/\(file) is not a valid file ???") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)") } return } let json: [String: Any]? do { json = try JSONSerialization .jsonObject(with: jsonData, options: .allowFragments) as? [String: Any] } catch { Log.error?.message("\(path)/\(file) is not a valid json file") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } guard let data = json else { do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } guard let cardClass = data["playerClass"] as? String, let playerClass = CardClass(rawValue: cardClass.lowercased()) else { Log.error?.message("\(data["playerClass"]) is not a valid class") do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } return } let deck = Deck() deck.isArena = data["isArena"] as? Bool ?? false deck.name = data["name"] as? String ?? "unknown deck" deck.isActive = data["isActive"] as? Bool ?? true if let date = data["creationDate"] as? String { deck.creationDate = Date(fromString: date, inFormat: "YYYY-MM-dd HH:mm:ss") } deck.hearthstatsId.value = data["hearthstatsId"] as? Int deck.hearthstatsVersionId.value = data["hearthstatsVersionId"] as? Int deck.playerClass = playerClass deck.version = data["version"] as? String ?? "1.0" if let cards = data["cards"] as? [String: Int] { for (id, count) in cards { deck.cards.append(RealmCard(id: id, count: count)) } } if let jsonStats = data["statistics"] as? [[String: Any]] { for stats in jsonStats { guard let opClass = stats["opponentClass"] as? String, let opponentClass = CardClass(rawValue: opClass.lowercased()) else { continue } let stat = Statistic() stat.opponentClass = opponentClass stat.hsReplayId = stats["hsReplayId"] as? String stat.gameResult = GameResult(rawValue: stats["gameResult"] as? Int ?? 0) ?? .unknow stat.duration = stats["duration"] as? Int ?? 0 stat.opponentRank.value = stats["opponentRank"] as? Int stat.playerRank = stats["playerRank"] as? Int ?? 0 stat.playerMode = GameMode(rawValue: stats["playerMode"] as? Int ?? GameMode.none.rawValue) ?? .none stat.note = stats["note"] as? String ?? "" if let date = data["date"] as? String { stat.date = Date(fromString: date, inFormat: "YYYY-MM-dd HH:mm:ss") } stat.season.value = stats["season"] as? Int stat.numTurns = stats["numTurns"] as? Int ?? 0 stat.hasCoin = stats["hasCoin"] as? Bool ?? false stat.opponentName = stats["opponentName"] as? String ?? "Unknown" guard let cards = stats["cards"] as? [String: Int] else { continue } for (id, count) in cards { stat.cards.append(RealmCard(id: id, count: count)) } deck.statistics.append(stat) } } if deck.isValid() { do { try realm.write { realm.add(deck) } } catch { Log.error?.message("Can not save deck") } } do { try FileManager.default.removeItem(atPath: "\(path)/\(file)") } catch { Log.error?.message("Can not delete \(path)/\(file)") } } }
// // HardwareModel.swift // Hardware // // Created by larryhou on 10/7/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import CoreTelephony import AdSupport import UIKit import SystemConfiguration.CaptiveNetwork import CoreBluetooth enum CategoryType:Int { case telephony = 5, bluetooth = 6, process = 1, device = 0, screen = 2, network = 7, language = 3, timezone = 4 } struct ItemInfo { let id:Int, name, value:String let parent:Int init(name:String, value:String) { self.init(id: -1, name: name, value: value) } init(name:String, value:String, parent:Int) { self.init(id: -1, name: name, value: value, parent: parent) } init(id:Int, name:String, value:String, parent:Int = -1) { self.id = id self.name = name self.value = value self.parent = parent } } class HardwareModel:NSObject, CBCentralManagerDelegate { static private(set) var shared = HardwareModel() private var data:[CategoryType:[ItemInfo]] = [:] @discardableResult func reload()->[CategoryType:[ItemInfo]] { var result:[CategoryType:[ItemInfo]] = [:] let categories:[CategoryType] = [.telephony, .process, .device, .screen, .network, .language, .bluetooth] for cate in categories { result[cate] = get(category: cate, reload: true) } return result } func get(category:CategoryType, reload:Bool = false)->[ItemInfo] { if !reload, let data = self.data[category] { return data } let data:[ItemInfo] switch category { case .telephony: data = getTelephony() case .process: data = getProcess() case .device: data = getDevice() case .screen: data = getScreen() case .network: data = getNetwork() case .language: data = getLanguage() case .timezone: data = getTimezone() case .bluetooth: data = getBluetooth() } self.data[category] = data return data } var bluetooth:CBCentralManager! private func getBluetooth()->[ItemInfo] { if bluetooth == nil { var result:[ItemInfo] = [] let options:[String:Any] = [CBCentralManagerOptionShowPowerAlertKey:0] bluetooth = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: options) result.append(ItemInfo(name: "state", value: format(of: bluetooth.state))) return result } else { return self.data[.bluetooth]! } } private func format(of type:CBManagerState)->String { switch type { case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" case .resetting: return "resetting" case .unauthorized: return "unauthorized" case .unsupported: return "unsupported" default: return "unknown" } } @available(iOS 5.0, *) func centralManagerDidUpdateState(_ central: CBCentralManager) { if var data = self.data[.bluetooth] { data.remove(at: 0) data.insert(ItemInfo(name:"state", value:format(of: central.state)), at: 0) self.data[.bluetooth] = data } } private func getTimezone()->[ItemInfo] { var result:[ItemInfo] = [] let zone = TimeZone.current result.append(ItemInfo(name: "identifier", value: zone.identifier)) if let abbr = zone.abbreviation() { result.append(ItemInfo(name: "abbreviation", value: abbr)) } result.append(ItemInfo(name: "secondsFromGMT", value: format(duration: TimeInterval(zone.secondsFromGMT())))) return result } private func getLanguage()->[ItemInfo] { var result:[ItemInfo] = [] let current = Locale.current result.append(ItemInfo(name: "current", value: "\(current.identifier) | \(current.localizedString(forIdentifier: current.identifier)!)")) var index = 0 for id in Locale.preferredLanguages { index += 1 if let name = current.localizedString(forIdentifier: id) { result.append(ItemInfo(name: "prefer_lang_\(index)", value: "\(id) | \(name)")) } else { result.append(ItemInfo(name: "prefer_lang_\(index)", value: id)) } } return result } private func getNetwork()->[ItemInfo] { var inames:[String] = [] var result:[ItemInfo] = [] if let interfaces = CNCopySupportedInterfaces() as? [CFString] { for iname in interfaces { inames.append(iname as String) let node = ItemInfo(id: result.count, name: "interface", value: iname as String) result.append(node) if let data = CNCopyCurrentNetworkInfo(iname) as? [String:Any] { for (name, value) in data { if name == "BSSID" || name == "SSID" { result.append(ItemInfo(name: name, value: "\(value)", parent:node.id)) } } } } } var ifaddr:UnsafeMutablePointer<ifaddrs>? if getifaddrs(&ifaddr) == 0 { var pointer = ifaddr while pointer != nil { let interface = pointer!.pointee let family = interface.ifa_addr.pointee.sa_family if family == UInt8(AF_INET) || family == UInt8(AF_INET6) { let name = String(cString: interface.ifa_name) var host = [CChar](repeating:0, count:Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &host, socklen_t(host.count), nil, socklen_t(0), NI_NUMERICHOST) let address = String(cString:host) result.append(ItemInfo(name: name, value: address)) } pointer = pointer?.pointee.ifa_next } } return result } private func getScreen()->[ItemInfo] { var result:[ItemInfo] = [] let info = UIScreen.main result.append(ItemInfo(name: "width", value: "\(info.bounds.width)")) result.append(ItemInfo(name: "height", value: "\(info.bounds.height)")) result.append(ItemInfo(name: "nativeScale", value: "\(info.nativeScale)")) result.append(ItemInfo(name: "scale", value: "\(info.scale)")) result.append(ItemInfo(name: "brightness", value: String(format: "%.4f", info.brightness))) result.append(ItemInfo(name: "softwareDimming", value: "\(info.wantsSoftwareDimming)")) return result } private func getDevice()->[ItemInfo] { var result:[ItemInfo] = [] let info = UIDevice.current result.append(ItemInfo(name: "name", value: info.name)) result.append(ItemInfo(name: "systemName", value: info.systemName)) result.append(ItemInfo(name: "systemVersion", value: info.systemVersion)) result.append(ItemInfo(name: "localizedModel", value: info.localizedModel)) var system:utsname = utsname() if uname(&system) == 0 { withUnsafePointer(to: &system.machine.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "model", value: value)) } withUnsafePointer(to: &system.nodename.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "nodename", value: value)) } withUnsafePointer(to: &system.release.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "release", value: value)) } withUnsafePointer(to: &system.sysname.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "sysname", value: value)) } withUnsafePointer(to: &system.version.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "version", value: value)) } } result.append(ItemInfo(name: "idiom", value: format(of: info.userInterfaceIdiom))) if let uuid = info.identifierForVendor { result.append(ItemInfo(name: "IDFV", value: uuid.description)) } result.append(ItemInfo(name: "IDFA", value: ASIdentifierManager.shared().advertisingIdentifier.description)) info.isBatteryMonitoringEnabled = true result.append(ItemInfo(name: "batteryLevel", value: String(format: "%3.0f%%", info.batteryLevel * 100))) result.append(ItemInfo(name: "batterState", value: format(of: info.batteryState))) info.isProximityMonitoringEnabled = true result.append(ItemInfo(name: "proximityState", value: "\(info.proximityState)")) result.append(ItemInfo(name: "architecture", value: arch())) if let value:String = sysctl(TYPE_NAME: HW_MACHINE) { result.append(ItemInfo(name: "HW_MACHINE", value: value)) } if let value:String = sysctl(TYPE_NAME: HW_MODEL) { result.append(ItemInfo(name: "HW_MODEL", value: value)) } if let value:Int = sysctl(TYPE_NAME: HW_CPU_FREQ) { result.append(ItemInfo(name: "HW_CPU_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_BUS_FREQ) { result.append(ItemInfo(name: "HW_BUS_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_TB_FREQ) { result.append(ItemInfo(name: "HW_TB_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_BYTEORDER) { result.append(ItemInfo(name: "HW_BYTEORDER", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_PHYSMEM) { result.append(ItemInfo(name: "HW_PHYSMEM", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_USERMEM) { result.append(ItemInfo(name: "HW_USERMEM", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_PAGESIZE) { result.append(ItemInfo(name: "HW_PAGESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L1ICACHESIZE) { result.append(ItemInfo(name: "HW_L1ICACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L1DCACHESIZE) { result.append(ItemInfo(name: "HW_L1DCACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L2CACHESIZE) { result.append(ItemInfo(name: "HW_L2CACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L3CACHESIZE) { result.append(ItemInfo(name: "HW_L3CACHESIZE", value: format(memory: UInt64(value)))) } return result } private func sysctl(TYPE_NAME:Int32, CTL_TYPE:Int32 = CTL_HW)->Int? { var value = 0 var size:size_t = MemoryLayout<Int>.size var data = [CTL_TYPE, TYPE_NAME] Darwin.sysctl(&data, 2, &value, &size, nil, 0) return value } private func sysctl(TYPE_NAME:Int32, CTL_TYPE:Int32 = CTL_HW)->String? { var params = [CTL_TYPE, TYPE_NAME] var size:size_t = 0 Darwin.sysctl(&params, 2, nil, &size, nil, 0) if let pointer = malloc(size) { Darwin.sysctl(&params, 2, pointer, &size, nil, 0) return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl(name:String, hexMode:Bool = false)->String? { var size:size_t = 0 sysctlbyname(name, nil, &size, nil, 0) if let pointer = malloc(size) { sysctlbyname(name, pointer, &size, nil, 0) if hexMode { let value = Data(bytes: pointer, count: size).map({String(format: "%02X", $0)}).joined() free(pointer) return "0x\(value)" } return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl<T>(name:String)->T? where T:SignedInteger { var value:T = 0 var size:size_t = MemoryLayout<T>.size sysctlbyname(name, &value, &size, nil, 0) return value } private func arch()->String { print(CPU_SUBTYPE_ARM_V7, CPU_TYPE_ARM) var value = "" if let type:cpu_type_t = sysctl(name:"hw.cputype") { switch type { case CPU_TYPE_X86:value = "x86" case CPU_TYPE_ARM:value = "ARM" case CPU_TYPE_ANY:value = "ANY" default: value = String(format:"0x%08x", type) } if let subtype:cpu_subtype_t = sysctl(name: "hw.cpusubtype") { switch subtype { case CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V7F, CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_ARM_V7M, CPU_SUBTYPE_ARM_V7S, CPU_SUBTYPE_ARM_V7EM: value += "|ARM_V7" case CPU_SUBTYPE_ARM_V8: value += "|ARM_V8" case CPU_SUBTYPE_ARM_V6: value += "|ARM_V6" case CPU_SUBTYPE_X86_ALL: value += "|x86_ALL" case CPU_SUBTYPE_X86_ARCH1: value += "|x86_ARCH1" case CPU_SUBTYPE_X86_64_ALL: value += "|x86_64_ALL" case CPU_SUBTYPE_X86_64_H: value += "|x86_64_H" default:value += "|" + String(format:"0x%08x", subtype) } } } return value } private func getProcess()->[ItemInfo] { var result:[ItemInfo] = [] let info = ProcessInfo.processInfo result.append(ItemInfo(name: "name", value: info.processName)) result.append(ItemInfo(name: "guid", value: info.globallyUniqueString)) result.append(ItemInfo(name: "id", value: "\(info.processIdentifier)")) result.append(ItemInfo(name: "hostName", value: info.hostName)) result.append(ItemInfo(name: "osVersion", value: info.operatingSystemVersionString)) result.append(ItemInfo(name: "coreCount", value: "\(info.processorCount)")) result.append(ItemInfo(name: "activeCoreCount", value: "\(info.activeProcessorCount)")) result.append(ItemInfo(name: "physicalMemory", value: format(memory: info.physicalMemory))) result.append(ItemInfo(name: "systemUptime", value: format(duration: info.systemUptime))) result.append(ItemInfo(name: "thermalState", value: format(of: info.thermalState))) result.append(ItemInfo(name: "lowPowerMode", value: "\(info.isLowPowerModeEnabled)")) var usage = rusage() if getrusage(RUSAGE_SELF, &usage) == 0 { result.append(ItemInfo(name: "cpu_time_user", value: format(of: usage.ru_utime))) result.append(ItemInfo(name: "cpu_time_system", value: format(of: usage.ru_stime))) } return result } private func format(of type:timeval)->String { return String(format: "%d.%06ds", type.tv_sec, type.tv_usec) } private func format(memory:UInt64)->String { var components:[String] = [] var memory = Double(memory) while memory > 1024 { memory /= 1024 components.append("1024") } if memory - floor(memory) > 0 { components.insert(String(format:"%.3f", memory), at: 0) } else { components.insert(String(format:"%.0f", memory), at: 0) } return components.joined(separator: "x") } private func format(of type:UIDeviceBatteryState)->String { switch type { case .charging: return "charging" case .full: return "full" case .unplugged: return "unplugged" case .unknown: return "unknown" } } private func format(of type:ProcessInfo.ThermalState)->String { switch type { case .critical: return "critical" case .fair: return "fair" case .nominal: return "nominal" case .serious: return "serious" } } private func format(of type:UIUserInterfaceIdiom)->String { switch type { case .carPlay: return "carPlay" case .pad: return "pad" case .phone: return "phone" case .tv: return "tv" case .unspecified: return "unspecified" } } private func format(duration:TimeInterval)->String { var duration = duration let bases:[Double] = [60, 60, 24] var list:[Double] = [] for value in bases { list.insert(fmod(duration, value), at: 0) duration = floor(duration / value) } if duration > 0 { list.insert(duration, at: 0) return String(format: "%.0f %02.0f:%02.0f:%.3f", arguments: list) } else { return String(format: "%02.0f:%02.0f:%06.3f", arguments: list) } } private func getTelephony()->[ItemInfo] { var result:[ItemInfo] = [] let info = CTTelephonyNetworkInfo() if let telephony = info.currentRadioAccessTechnology { switch telephony { case CTRadioAccessTechnologyLTE: result.append(ItemInfo(name: "radio", value: "LTE")) case CTRadioAccessTechnologyEdge: result.append(ItemInfo(name: "radio", value: "EDGE")) case CTRadioAccessTechnologyGPRS: result.append(ItemInfo(name: "radio", value: "GPRS")) case CTRadioAccessTechnologyHSDPA: result.append(ItemInfo(name: "radio", value: "HSDPA")) case CTRadioAccessTechnologyHSUPA: result.append(ItemInfo(name: "radio", value: "HSUPA")) case CTRadioAccessTechnologyWCDMA: result.append(ItemInfo(name: "radio", value: "WCDMA")) case CTRadioAccessTechnologyCDMA1x: result.append(ItemInfo(name: "radio", value: "CDMA_1x")) case CTRadioAccessTechnologyCDMAEVDORev0: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_0")) case CTRadioAccessTechnologyCDMAEVDORevA: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_A")) case CTRadioAccessTechnologyCDMAEVDORevB: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_B")) default: result.append(ItemInfo(name: "radio", value: telephony)) } } if let carrier = info.subscriberCellularProvider { if let name = carrier.carrierName { result.append(ItemInfo(name: "carrier", value: name)) } result.append(ItemInfo(name: "VOIP", value: "\(carrier.allowsVOIP)")) if let isoCode = carrier.isoCountryCode { result.append(ItemInfo(name: "isoCode", value: isoCode)) } if let mobileCode = carrier.mobileCountryCode { result.append(ItemInfo(name: "mobileCode", value: mobileCode)) } if let networkCode = carrier.mobileNetworkCode { result.append(ItemInfo(name: "networkCode", value: networkCode)) } } return result } } update // // HardwareModel.swift // Hardware // // Created by larryhou on 10/7/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import CoreTelephony import AdSupport import UIKit import SystemConfiguration.CaptiveNetwork import CoreBluetooth enum CategoryType:Int { case telephony = 5, bluetooth = 6, process = 1, device = 0, screen = 2, network = 7, language = 3, timezone = 4 } struct ItemInfo { let id:Int, name, value:String let parent:Int init(name:String, value:String) { self.init(id: -1, name: name, value: value) } init(name:String, value:String, parent:Int) { self.init(id: -1, name: name, value: value, parent: parent) } init(id:Int, name:String, value:String, parent:Int = -1) { self.id = id self.name = name self.value = value self.parent = parent } } class HardwareModel:NSObject, CBCentralManagerDelegate { static private(set) var shared = HardwareModel() private var data:[CategoryType:[ItemInfo]] = [:] @discardableResult func reload()->[CategoryType:[ItemInfo]] { var result:[CategoryType:[ItemInfo]] = [:] let categories:[CategoryType] = [.telephony, .process, .device, .screen, .network, .language, .bluetooth] for cate in categories { result[cate] = get(category: cate, reload: true) } return result } func get(category:CategoryType, reload:Bool = false)->[ItemInfo] { if !reload, let data = self.data[category] { return data } let data:[ItemInfo] switch category { case .telephony: data = getTelephony() case .process: data = getProcess() case .device: data = getDevice() case .screen: data = getScreen() case .network: data = getNetwork() case .language: data = getLanguage() case .timezone: data = getTimezone() case .bluetooth: data = getBluetooth() } self.data[category] = data return data } var bluetooth:CBCentralManager! private func getBluetooth()->[ItemInfo] { if bluetooth == nil { var result:[ItemInfo] = [] let options:[String:Any] = [CBCentralManagerOptionShowPowerAlertKey:0] bluetooth = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: options) result.append(ItemInfo(name: "state", value: format(of: bluetooth.state))) return result } else { return self.data[.bluetooth]! } } private func format(of type:CBManagerState)->String { switch type { case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" case .resetting: return "resetting" case .unauthorized: return "unauthorized" case .unsupported: return "unsupported" default: return "unknown" } } @available(iOS 5.0, *) func centralManagerDidUpdateState(_ central: CBCentralManager) { if var data = self.data[.bluetooth] { data.remove(at: 0) data.insert(ItemInfo(name:"state", value:format(of: central.state)), at: 0) self.data[.bluetooth] = data } } private func getTimezone()->[ItemInfo] { var result:[ItemInfo] = [] let zone = TimeZone.current result.append(ItemInfo(name: "identifier", value: zone.identifier)) if let abbr = zone.abbreviation() { result.append(ItemInfo(name: "abbreviation", value: abbr)) } result.append(ItemInfo(name: "secondsFromGMT", value: format(duration: TimeInterval(zone.secondsFromGMT())))) return result } private func getLanguage()->[ItemInfo] { var result:[ItemInfo] = [] let current = Locale.current result.append(ItemInfo(name: "current", value: "\(current.identifier) | \(current.localizedString(forIdentifier: current.identifier)!)")) var index = 0 for id in Locale.preferredLanguages { index += 1 if let name = current.localizedString(forIdentifier: id) { result.append(ItemInfo(name: "prefer_lang_\(index)", value: "\(id) | \(name)")) } else { result.append(ItemInfo(name: "prefer_lang_\(index)", value: id)) } } return result } private func getNetwork()->[ItemInfo] { var inames:[String] = [] var result:[ItemInfo] = [] if let interfaces = CNCopySupportedInterfaces() as? [CFString] { for iname in interfaces { inames.append(iname as String) let node = ItemInfo(id: result.count, name: "interface", value: iname as String) result.append(node) if let data = CNCopyCurrentNetworkInfo(iname) as? [String:Any] { for (name, value) in data { if name == "BSSID" || name == "SSID" { result.append(ItemInfo(name: name, value: "\(value)", parent:node.id)) } } } } } var ifaddr:UnsafeMutablePointer<ifaddrs>? if getifaddrs(&ifaddr) == 0 { var pointer = ifaddr while pointer != nil { let interface = pointer!.pointee let family = interface.ifa_addr.pointee.sa_family if family == UInt8(AF_INET) || family == UInt8(AF_INET6) { let name = String(cString: interface.ifa_name) var host = [CChar](repeating:0, count:Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &host, socklen_t(host.count), nil, socklen_t(0), NI_NUMERICHOST) let address = String(cString:host) result.append(ItemInfo(name: name, value: address)) } pointer = pointer?.pointee.ifa_next } } return result } private func getScreen()->[ItemInfo] { var result:[ItemInfo] = [] let info = UIScreen.main result.append(ItemInfo(name: "width", value: "\(info.bounds.width)")) result.append(ItemInfo(name: "height", value: "\(info.bounds.height)")) result.append(ItemInfo(name: "nativeScale", value: "\(info.nativeScale)")) result.append(ItemInfo(name: "scale", value: "\(info.scale)")) result.append(ItemInfo(name: "brightness", value: String(format: "%.4f", info.brightness))) result.append(ItemInfo(name: "softwareDimming", value: "\(info.wantsSoftwareDimming)")) return result } private func getDevice()->[ItemInfo] { var result:[ItemInfo] = [] let info = UIDevice.current result.append(ItemInfo(name: "name", value: info.name)) result.append(ItemInfo(name: "systemName", value: info.systemName)) result.append(ItemInfo(name: "systemVersion", value: info.systemVersion)) result.append(ItemInfo(name: "localizedModel", value: info.localizedModel)) var system:utsname = utsname() if uname(&system) == 0 { withUnsafePointer(to: &system.machine.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "model", value: value)) } withUnsafePointer(to: &system.nodename.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "nodename", value: value)) } withUnsafePointer(to: &system.release.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "release", value: value)) } withUnsafePointer(to: &system.sysname.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "sysname", value: value)) } withUnsafePointer(to: &system.version.0) { (pointer:UnsafePointer<Int8>) in let value = String(cString: pointer) result.append(ItemInfo(name: "version", value: value)) } } result.append(ItemInfo(name: "idiom", value: format(of: info.userInterfaceIdiom))) if let uuid = info.identifierForVendor { result.append(ItemInfo(name: "IDFV", value: uuid.description)) } result.append(ItemInfo(name: "IDFA", value: ASIdentifierManager.shared().advertisingIdentifier.description)) info.isBatteryMonitoringEnabled = true result.append(ItemInfo(name: "batteryLevel", value: String(format: "%3.0f%%", info.batteryLevel * 100))) result.append(ItemInfo(name: "batterState", value: format(of: info.batteryState))) info.isProximityMonitoringEnabled = true result.append(ItemInfo(name: "proximityState", value: "\(info.proximityState)")) result.append(ItemInfo(name: "architecture", value: arch())) if let value:String = sysctl(TYPE_NAME: HW_MACHINE) { result.append(ItemInfo(name: "HW_MACHINE", value: value)) } if let value:String = sysctl(TYPE_NAME: HW_MODEL) { result.append(ItemInfo(name: "HW_MODEL", value: value)) } if let value:Int = sysctl(TYPE_NAME: HW_CPU_FREQ) { result.append(ItemInfo(name: "HW_CPU_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_BUS_FREQ) { result.append(ItemInfo(name: "HW_BUS_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_TB_FREQ) { result.append(ItemInfo(name: "HW_TB_FREQ", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_BYTEORDER) { result.append(ItemInfo(name: "HW_BYTEORDER", value: "\(value)")) } if let value:Int = sysctl(TYPE_NAME: HW_PHYSMEM) { result.append(ItemInfo(name: "HW_PHYSMEM", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_USERMEM) { result.append(ItemInfo(name: "HW_USERMEM", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_PAGESIZE) { result.append(ItemInfo(name: "HW_PAGESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L1ICACHESIZE) { result.append(ItemInfo(name: "HW_L1ICACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L1DCACHESIZE) { result.append(ItemInfo(name: "HW_L1DCACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L2CACHESIZE) { result.append(ItemInfo(name: "HW_L2CACHESIZE", value: format(memory: UInt64(value)))) } if let value:Int = sysctl(TYPE_NAME: HW_L3CACHESIZE) { result.append(ItemInfo(name: "HW_L3CACHESIZE", value: format(memory: UInt64(value)))) } return result } private func sysctl(TYPE_NAME:Int32, CTL_TYPE:Int32 = CTL_HW)->Int? { var value = 0 var size:size_t = MemoryLayout<Int>.size var data = [CTL_TYPE, TYPE_NAME] Darwin.sysctl(&data, 2, &value, &size, nil, 0) return value } private func sysctl(TYPE_NAME:Int32, CTL_TYPE:Int32 = CTL_HW)->String? { var params = [CTL_TYPE, TYPE_NAME] var size:size_t = 0 Darwin.sysctl(&params, 2, nil, &size, nil, 0) if let pointer = malloc(size) { Darwin.sysctl(&params, 2, pointer, &size, nil, 0) return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl(name:String, hexMode:Bool = false)->String? { var size:size_t = 0 sysctlbyname(name, nil, &size, nil, 0) if let pointer = malloc(size) { sysctlbyname(name, pointer, &size, nil, 0) if hexMode { let value = Data(bytes: pointer, count: size).map({String(format: "%02X", $0)}).joined() free(pointer) return "0x\(value)" } return String(bytesNoCopy: pointer, length: size, encoding: .utf8, freeWhenDone: true) } return nil } private func sysctl<T>(name:String)->T? where T:SignedInteger { var value:T = 0 var size:size_t = MemoryLayout<T>.size sysctlbyname(name, &value, &size, nil, 0) return value } private func arch()->String { print(CPU_SUBTYPE_ARM_V7) var value = "" if let type:cpu_type_t = sysctl(name:"hw.cputype") { switch type { case CPU_TYPE_X86:value = "x86" case CPU_TYPE_ARM:value = "ARM" case CPU_TYPE_ANY:value = "ANY" default: value = String(format:"0x%08x", type) } } if let subtype:cpu_subtype_t = sysctl(name: "hw.cpusubtype") { switch subtype { case CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V7F, CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_ARM_V7M, CPU_SUBTYPE_ARM_V7S, CPU_SUBTYPE_ARM_V7EM: value += "|ARM_v7" case CPU_SUBTYPE_ARM_V8: value += "|ARM_v8" case CPU_SUBTYPE_ARM_V6: value += "|ARM_v6" case CPU_SUBTYPE_X86_ALL: value += "|x86_all" case CPU_SUBTYPE_X86_ARCH1: value += "|x86_ARCH1" case CPU_SUBTYPE_X86_64_ALL: value += "|x86_64_all" case CPU_SUBTYPE_X86_64_H: value += "|x86_64_H" default:value += "|" + String(format:"0x%08x", subtype) } } return value } private func getProcess()->[ItemInfo] { var result:[ItemInfo] = [] let info = ProcessInfo.processInfo result.append(ItemInfo(name: "name", value: info.processName)) result.append(ItemInfo(name: "guid", value: info.globallyUniqueString)) result.append(ItemInfo(name: "id", value: "\(info.processIdentifier)")) result.append(ItemInfo(name: "hostName", value: info.hostName)) result.append(ItemInfo(name: "osVersion", value: info.operatingSystemVersionString)) result.append(ItemInfo(name: "coreCount", value: "\(info.processorCount)")) result.append(ItemInfo(name: "activeCoreCount", value: "\(info.activeProcessorCount)")) result.append(ItemInfo(name: "physicalMemory", value: format(memory: info.physicalMemory))) result.append(ItemInfo(name: "systemUptime", value: format(duration: info.systemUptime))) result.append(ItemInfo(name: "thermalState", value: format(of: info.thermalState))) result.append(ItemInfo(name: "lowPowerMode", value: "\(info.isLowPowerModeEnabled)")) var usage = rusage() if getrusage(RUSAGE_SELF, &usage) == 0 { result.append(ItemInfo(name: "cpu_time_user", value: format(of: usage.ru_utime))) result.append(ItemInfo(name: "cpu_time_system", value: format(of: usage.ru_stime))) } return result } private func format(of type:timeval)->String { return String(format: "%d.%06ds", type.tv_sec, type.tv_usec) } private func format(memory:UInt64)->String { var components:[String] = [] var memory = Double(memory) while memory > 1024 { memory /= 1024 components.append("1024") } if memory - floor(memory) > 0 { components.insert(String(format:"%.3f", memory), at: 0) } else { components.insert(String(format:"%.0f", memory), at: 0) } return components.joined(separator: "x") } private func format(of type:UIDeviceBatteryState)->String { switch type { case .charging: return "charging" case .full: return "full" case .unplugged: return "unplugged" case .unknown: return "unknown" } } private func format(of type:ProcessInfo.ThermalState)->String { switch type { case .critical: return "critical" case .fair: return "fair" case .nominal: return "nominal" case .serious: return "serious" } } private func format(of type:UIUserInterfaceIdiom)->String { switch type { case .carPlay: return "carPlay" case .pad: return "pad" case .phone: return "phone" case .tv: return "tv" case .unspecified: return "unspecified" } } private func format(duration:TimeInterval)->String { var duration = duration let bases:[Double] = [60, 60, 24] var list:[Double] = [] for value in bases { list.insert(fmod(duration, value), at: 0) duration = floor(duration / value) } if duration > 0 { list.insert(duration, at: 0) return String(format: "%.0f %02.0f:%02.0f:%.3f", arguments: list) } else { return String(format: "%02.0f:%02.0f:%06.3f", arguments: list) } } private func getTelephony()->[ItemInfo] { var result:[ItemInfo] = [] let info = CTTelephonyNetworkInfo() if let telephony = info.currentRadioAccessTechnology { switch telephony { case CTRadioAccessTechnologyLTE: result.append(ItemInfo(name: "radio", value: "LTE")) case CTRadioAccessTechnologyEdge: result.append(ItemInfo(name: "radio", value: "EDGE")) case CTRadioAccessTechnologyGPRS: result.append(ItemInfo(name: "radio", value: "GPRS")) case CTRadioAccessTechnologyHSDPA: result.append(ItemInfo(name: "radio", value: "HSDPA")) case CTRadioAccessTechnologyHSUPA: result.append(ItemInfo(name: "radio", value: "HSUPA")) case CTRadioAccessTechnologyWCDMA: result.append(ItemInfo(name: "radio", value: "WCDMA")) case CTRadioAccessTechnologyCDMA1x: result.append(ItemInfo(name: "radio", value: "CDMA_1x")) case CTRadioAccessTechnologyCDMAEVDORev0: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_0")) case CTRadioAccessTechnologyCDMAEVDORevA: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_A")) case CTRadioAccessTechnologyCDMAEVDORevB: result.append(ItemInfo(name: "radio", value: "CDMA_EVDO_B")) default: result.append(ItemInfo(name: "radio", value: telephony)) } } if let carrier = info.subscriberCellularProvider { if let name = carrier.carrierName { result.append(ItemInfo(name: "carrier", value: name)) } result.append(ItemInfo(name: "VOIP", value: "\(carrier.allowsVOIP)")) if let isoCode = carrier.isoCountryCode { result.append(ItemInfo(name: "isoCode", value: isoCode)) } if let mobileCode = carrier.mobileCountryCode { result.append(ItemInfo(name: "mobileCode", value: mobileCode)) } if let networkCode = carrier.mobileNetworkCode { result.append(ItemInfo(name: "networkCode", value: networkCode)) } } return result } }
// // WebViewController.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // Copyright © 2017 Carlos D. Santiago. All rights reserved. // import Cocoa import WebKit import AVFoundation import Carbon.HIToolbox extension WKWebViewConfiguration { /// Async Factory method to acquire WKWebViewConfigurations packaged with system cookies static func cookiesIncluded(completion: @escaping (WKWebViewConfiguration?) -> Void) { let config = WKWebViewConfiguration() guard let cookies = HTTPCookieStorage.shared.cookies else { completion(config) return } // Use nonPersistent() or default() depending on if you want cookies persisted to disk // and shared between WKWebViews of the same app (default), or not persisted and not shared // across WKWebViews in the same app. let dataStore = WKWebsiteDataStore.nonPersistent() let waitGroup = DispatchGroup() for cookie in cookies { waitGroup.enter() if #available(OSX 10.13, *) { dataStore.httpCookieStore.setCookie(cookie) { waitGroup.leave() } } else { // Fallback on earlier versions } } waitGroup.notify(queue: DispatchQueue.main) { config.websiteDataStore = dataStore completion(config) } } } class WebBorderView : NSView { var isReceivingDrag = false { didSet { needsDisplay = true } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) self.isHidden = !isReceivingDrag // Swift.print("web borderView drawing \(isHidden ? "NO" : "YES")....") if isReceivingDrag { NSColor.selectedKnobColor.set() let path = NSBezierPath(rect:bounds) path.lineWidth = 4 path.stroke() } } } class MyWebView : WKWebView { var appDelegate: AppDelegate = NSApp.delegate as! AppDelegate override class func handlesURLScheme(_ urlScheme: String) -> Bool { Swift.print("handleURLScheme: \(urlScheme)") return true } var selectedText : String? var selectedURL : URL? var chromeType: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "org.chromium.drag-dummy-type") } var finderNode: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "com.apple.finder.node") } var webarchive: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "com.apple.webarchive") } var acceptableTypes: Set<NSPasteboard.PasteboardType> { return [.URL, .fileURL, .list, .item, .html, .pdf, .png, .rtf, .rtfd, .tiff, finderNode, webarchive] } var filteringOptions = [NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes:NSImage.imageTypes] @objc internal func menuClicked(_ sender: AnyObject) { if let menuItem = sender as? NSMenuItem { Swift.print("Menu \(menuItem.title) clicked") } } override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) { // Pick off javascript items we want to ignore or handle for title in ["Open Link", "Open Link in New Window", "Download Linked File"] { if let item = menu.item(withTitle: title) { if title == "Download Linked File" { menu.removeItem(item) } else if title == "Open Link" { item.action = #selector(MyWebView.openLinkInWindow(_:)) item.target = self } else { item.tag = ViewOptions.w_view.rawValue item.action = #selector(MyWebView.openLinkInNewWindow(_:)) item.target = self } } } publishApplicationMenu(menu); } @objc func openLinkInWindow(_ item: NSMenuItem) { if let urlString = self.selectedText, let url = URL.init(string: urlString) { load(URLRequest.init(url: url)) } else if let url = self.selectedURL { load(URLRequest.init(url: url)) } } @objc func openLinkInNewWindow(_ item: NSMenuItem) { if let urlString = self.selectedText, let url = URL.init(string: urlString) { _ = appDelegate.openURLInNewWindow(url, attachTo: item.representedObject as? NSWindow) } else if let url = self.selectedURL { _ = appDelegate.openURLInNewWindow(url, attachTo: item.representedObject as? NSWindow) } } override var mouseDownCanMoveWindow: Bool { get { if let window = self.window { return window.isMovableByWindowBackground } else { return false } } } var heliumPanelController : HeliumPanelController? { get { guard let hpc : HeliumPanelController = self.window?.windowController as? HeliumPanelController else { return nil } return hpc } } var webViewController : WebViewController? { get { guard let wvc : WebViewController = self.window?.contentViewController as? WebViewController else { return nil } return wvc } } /* override func load(_ request: URLRequest) -> WKNavigation? { Swift.print("we got \(request)") return super.load(request) } */ @objc @IBAction internal func cut(_ sender: Any) { let pb = NSPasteboard.general pb.clearContents() if let urlString = self.url?.absoluteString { pb.setString(urlString, forType: NSPasteboard.PasteboardType.string) (self.uiDelegate as! WebViewController).clear() } } @objc @IBAction internal func copy(_ sender: Any) { let pb = NSPasteboard.general pb.clearContents() if let urlString = self.url?.absoluteString { pb.setString(urlString, forType: NSPasteboard.PasteboardType.string) } } @objc @IBAction internal func paste(_ sender: Any) { let pb = NSPasteboard.general guard let rawString = pb.string(forType: NSPasteboard.PasteboardType.string), rawString.isValidURL() else { return } self.load(URLRequest.init(url: URL.init(string: rawString)!)) } @objc @IBAction internal func delete(_ sender: Any) { self.cancelOperation(sender) Swift.print("cancel") } func html(_ html : String) { self.loadHTMLString(html, baseURL: nil) } func next(url: URL) { let doc = self.heliumPanelController?.document as! Document var nextURL = url // Resolve alias before sandbox bookmarking if let webloc = nextURL.webloc { next(url: webloc) return } if nextURL.isFileURL { if let original = (nextURL as NSURL).resolvedFinderAlias() { nextURL = original } if nextURL.isFileURL, appDelegate.isSandboxed() && !appDelegate.storeBookmark(url: nextURL) { Swift.print("Yoink, unable to sandbox \(nextURL)") return } } // h3w files are playlist extractions, presented as a sheet or window guard nextURL.pathExtension == k.h3w, let dict = NSDictionary(contentsOf: url) else { // keep document in sync with webView url doc.update(to: nextURL) self.load(URLRequest(url: nextURL)) ///self.loadFileURL(nextURL, allowingReadAccessTo: nextURL) return } // We could have 3 keys: <source-name>, k.playlists, k.playitems or promise file of playlists var playlists = [PlayList]() if let names : [String] = dict.value(forKey: k.playlists) as? [String] { for name in names { if let items = dict.value(forKey: name) as? [Dictionary<String,Any>] { let playlist = PlayList.init(name: name, list: [PlayItem]()) for item in items { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } } } else if let items = dict.value(forKey: k.playitems) as? [Dictionary<String,Any>] { let playlist = PlayList.init(name: nextURL.lastPathComponent, list: [PlayItem]()) for item in items { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } else { for (name,list) in dict { let playlist = PlayList.init(name: name as! String, list: [PlayItem]()) for item in (list as? [Dictionary<String,Any>])! { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } } if let wvc = self.webViewController, wvc.presentedViewControllers?.count == 0 { let storyboard = NSStoryboard(name: "Main", bundle: nil) let pvc = storyboard.instantiateController(withIdentifier: "PlaylistViewController") as! PlaylistViewController pvc.playlists.append(contentsOf: playlists) pvc.webViewController = self.webViewController wvc.presentAsSheet(pvc) } } func text(_ text : String) { if FileManager.default.fileExists(atPath: text) { let url = URL.init(fileURLWithPath: text) next(url: url) return } if let url = URL.init(string: text) { do { if try url.checkResourceIsReachable() { next(url: url) return } } catch let error as NSError { Swift.print("url?: \(error.code):\(error.localizedDescription): \(text)") } } if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) let wvc = self.window?.contentViewController (wvc as! WebViewController).loadAttributes(dict: json as! Dictionary<String, Any>) return } catch let error as NSError { Swift.print("json: \(error.code):\(error.localizedDescription): \(text)") } } let html = String(format: """ <html> <body> <code> %@ </code> </body> </html> """, text); self.loadHTMLString(html, baseURL: nil) } func text(attrributedString text: NSAttributedString) { do { let docAttrs = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html] let data = try text.data(from: NSMakeRange(0, text.length), documentAttributes: docAttrs) if let attrs = String(data: data, encoding: .utf8) { let html = String(format: """ <html> <body> <code> %@ </code> </body> </html> """, attrs); self.loadHTMLString(html, baseURL: nil) } } catch let error as NSError { Swift.print("attributedString -> html: \(error.code):\(error.localizedDescription): \(text)") } } // MARK: Drag and Drop - Before Release func shouldAllowDrag(_ info: NSDraggingInfo) -> Bool { guard let doc = webViewController?.document, doc.docType == .helium else { return false } let pboard = info.draggingPasteboard let items = pboard.pasteboardItems! var canAccept = false let readableClasses = [NSURL.self, NSString.self, NSAttributedString.self, NSPasteboardItem.self, PlayList.self, PlayItem.self] if pboard.canReadObject(forClasses: readableClasses, options: filteringOptions) { canAccept = true } else { for item in items { Swift.print("item: \(item)") } } Swift.print("web shouldAllowDrag -> \(canAccept) \(items.count) item(s)") return canAccept } var borderView: WebBorderView { get { return (uiDelegate as! WebViewController).borderView } } var isReceivingDrag : Bool { get { return borderView.isReceivingDrag } set (value) { borderView.isReceivingDrag = value } } override func draggingEntered(_ info: NSDraggingInfo) -> NSDragOperation { let pboard = info.draggingPasteboard let items = pboard.pasteboardItems! let allow = shouldAllowDrag(info) if uiDelegate != nil { isReceivingDrag = allow } let dragOperation = allow ? .copy : NSDragOperation() Swift.print("web draggingEntered -> \(dragOperation) \(items.count) item(s)") return dragOperation } override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { let allow = shouldAllowDrag(sender) sender.animatesToDestination = true Swift.print("web prepareForDragOperation -> \(allow)") return allow } override func draggingExited(_ sender: NSDraggingInfo?) { Swift.print("web draggingExited") if uiDelegate != nil { isReceivingDrag = false } } var lastDragSequence : Int = 0 override func draggingUpdated(_ info: NSDraggingInfo) -> NSDragOperation { appDelegate.newViewOptions = appDelegate.getViewOptions let sequence = info.draggingSequenceNumber if sequence != lastDragSequence { Swift.print("web draggingUpdated -> .copy") lastDragSequence = sequence } return .copy } // MARK: Drag and Drop - After Release override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { var viewOptions = appDelegate.newViewOptions let options : [NSPasteboard.ReadingOptionKey: Any] = [NSPasteboard.ReadingOptionKey.urlReadingFileURLsOnly : true, NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes : [ kUTTypeImage, kUTTypeVideo, kUTTypeMovie], NSPasteboard.ReadingOptionKey(rawValue: PlayList.className()) : true, NSPasteboard.ReadingOptionKey(rawValue: PlayItem.className()) : true] let pboard = sender.draggingPasteboard let items = pboard.pasteboardItems var parent : NSWindow? = self.window var latest : Document? var handled = 0 for item in items! { if handled == items!.count { break } if let urlString = item.string(forType: NSPasteboard.PasteboardType(rawValue: kUTTypeURL as String)) { self.next(url: URL(string: urlString)!) handled += 1 continue } for type in pboard.types! { Swift.print("web type: \(type)") switch type { case .files: if let files = pboard.propertyList(forType: type) { Swift.print("files \(files)") } break case .URL, .fileURL: if let urlString = item.string(forType: type), let url = URL.init(string: urlString) { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } else if let data = item.data(forType: type), let url = NSKeyedUnarchiver.unarchiveObject(with: data) { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url as! URL , attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url as! URL) } else { self.next(url: url as! URL) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } else if let urls: Array<AnyObject> = pboard.readObjects(forClasses: [NSURL.classForCoder()], options: options) as Array<AnyObject>? { for url in urls as! [URL] { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url , attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } } break case .list: if let playlists: Array<AnyObject> = pboard.readObjects(forClasses: [PlayList.classForCoder()], options: options) as Array<AnyObject>? { var parent : NSWindow? = self.window var latest : Document? for playlist in playlists { for playitem in playlist.list { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link) } else { self.next(url: playitem.link) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) } handled += 1 } } break case .item: if let playitems: Array<AnyObject> = pboard.readObjects(forClasses: [PlayItem.classForCoder()], options: options) as Array<AnyObject>? { var parent : NSWindow? = self.window var latest : Document? for playitem in playitems { Swift.print("item: \(playitem)") if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link) } else { self.next(url: playitem.link) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } } break case .data: if let data = item.data(forType: type), let item = NSKeyedUnarchiver.unarchiveObject(with: data) { if let playlist = item as? PlayList { Swift.print("list: \(playlist)") handled += 1 } else if let playitem = item as? PlayItem { Swift.print("item: \(playitem)") handled += 1 } else { Swift.print("data: \(data)") } } break case .rtf, .rtfd, .tiff: if let data = item.data(forType: type), let text = NSAttributedString(rtf: data, documentAttributes: nil) { self.text(text.string) handled += 1 } break case .string, .tabularText: if let text = item.string(forType: type) { self.text(text) handled += 1 } break case webarchive: if let data = item.data(forType: type) { let html = String(decoding: data, as: UTF8.self) self.html(html) handled += 1 } if let text = item.string(forType: type) { Swift.print("\(type) text \(String(describing: text))") self.text(text) handled += 1 } if let prop = item.propertyList(forType: type) { if let html = String.init(data: prop as! Data, encoding: .utf8) { self.html(html) handled += 1 } else { Swift.print("\(type) prop \(String(describing: prop))") } } break case chromeType: if let data = item.data(forType: type) { let html = String(decoding: data, as: UTF8.self) if html.count > 0 { self.html(html) handled += 1 } } if let text = item.string(forType: type) { Swift.print("\(type) text \(String(describing: text))") if text.count > 0 { self.text(text) handled += 1 } } if let prop = item.propertyList(forType: type) { if let html = String.init(data: prop as! Data, encoding: .utf8) { self.html(html) handled += 1 } else { Swift.print("\(type) prop \(String(describing: prop))") } } break default: Swift.print("unkn: \(type)") if let data = item.data(forType: type) { Swift.print("data: \(data.count) bytes") //self.load(data, mimeType: <#T##String#>, characterEncodingName: UTF8, baseURL: <#T##URL#>) } } if handled == items?.count { break } } } Swift.print("web performDragOperation -> \(handled == items?.count ? "true" : "false")") return handled == items?.count } // MARK: Context Menu // // Intercepted actions; capture state needed for avToggle() var playPressMenuItem = NSMenuItem() @objc @IBAction func playActionPress(_ sender: NSMenuItem) { // Swift.print("\(playPressMenuItem.title) -> target:\(String(describing: playPressMenuItem.target)) action:\(String(describing: playPressMenuItem.action)) tag:\(playPressMenuItem.tag)") _ = playPressMenuItem.target?.perform(playPressMenuItem.action, with: playPressMenuItem.representedObject) // this releases original menu item sender.representedObject = self let notif = Notification(name: Notification.Name(rawValue: "HeliumItemAction"), object: sender) NotificationCenter.default.post(notif) } var mutePressMenuItem = NSMenuItem() @objc @IBAction func muteActionPress(_ sender: NSMenuItem) { // Swift.print("\(mutePressMenuItem.title) -> target:\(String(describing: mutePressMenuItem.target)) action:\(String(describing: mutePressMenuItem.action)) tag:\(mutePressMenuItem.tag)") _ = mutePressMenuItem.target?.perform(mutePressMenuItem.action, with: mutePressMenuItem.representedObject) // this releases original menu item sender.representedObject = self let notif = Notification(name: Notification.Name(rawValue: "HeliumItemAction"), object: sender) NotificationCenter.default.post(notif) } // // Actions used by contextual menu, or status item, or our app menu func publishApplicationMenu(_ menu: NSMenu) { let wvc = self.window?.contentViewController as! WebViewController let hpc = self.window?.windowController as! HeliumPanelController let settings = (hpc.document as! Document).settings let autoHideTitle = hpc.autoHideTitlePreference let translucency = hpc.translucencyPreference // Remove item(s) we cannot support for title in ["Enter Picture in Picture", "Download Video"] { if let item = menu.item(withTitle: title) { menu.removeItem(item) } } // Alter item(s) we want to support for title in ["Enter Full Screen", "Open Video in New Window"] { if let item = menu.item(withTitle: title) { // Swift.print("old: \(title) -> target:\(String(describing: item.target)) action:\(String(describing: item.action)) tag:\(item.tag)") if item.title.hasSuffix("Enter Full Screen") { item.target = appDelegate item.action = #selector(appDelegate.toggleFullScreen(_:)) item.state = appDelegate.fullScreen != nil ? .on : .off } else if self.url != nil { item.representedObject = self.url item.target = appDelegate item.action = #selector(appDelegate.openVideoInNewWindowPress(_:)) } else { item.isEnabled = false } // Swift.print("new: \(title) -> target:\(String(describing: item.target)) action:\(String(describing: item.action)) tag:\(item.tag)") } } // Intercept these actions so we can record them for later // NOTE: cache original menu item so it does not disappear for title in ["Play", "Pause", "Mute"] { if let item = menu.item(withTitle: title) { if item.title == "Mute" { mutePressMenuItem.action = item.action mutePressMenuItem.target = item.target mutePressMenuItem.title = item.title mutePressMenuItem.state = item.state mutePressMenuItem.tag = item.tag mutePressMenuItem.representedObject = item item.action = #selector(self.muteActionPress(_:)) item.target = self } else { playPressMenuItem.action = item.action playPressMenuItem.target = item.target playPressMenuItem.title = item.title playPressMenuItem.state = item.state playPressMenuItem.tag = item.tag playPressMenuItem.representedObject = item item.action = #selector(self.playActionPress(_:)) item.target = self } // let state = item.state == .on ? "yes" : "no" // Swift.print("target: \(title) -> \(String(describing: item.action)) state: \(state) tag:\(item.tag)") } } var item: NSMenuItem item = NSMenuItem(title: "Cut", action: #selector(MyWebView.cut(_:)), keyEquivalent: "") menu.addItem(item) item = NSMenuItem(title: "Copy", action: #selector(MyWebView.copy(_:)), keyEquivalent: "") menu.addItem(item) item = NSMenuItem(title: "Paste", action: #selector(MyWebView.paste(_:)), keyEquivalent: "") menu.addItem(item) menu.addItem(NSMenuItem.separator()) item = NSMenuItem(title: "New Window", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.target = appDelegate item.tag = 1 menu.addItem(item) item = NSMenuItem(title: "New Tab", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.target = appDelegate item.isAlternate = true item.tag = 3 menu.addItem(item) item = NSMenuItem(title: "Open", action: #selector(menuClicked(_:)), keyEquivalent: "") menu.addItem(item) let subOpen = NSMenu() item.submenu = subOpen item = NSMenuItem(title: "File…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.target = wvc subOpen.addItem(item) item = NSMenuItem(title: "File in new window…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.shift item.isAlternate = true item.target = wvc item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "File in new tab…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.isAlternate = true item.target = wvc item.tag = 3 subOpen.addItem(item) item = NSMenuItem(title: "URL…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.target = wvc subOpen.addItem(item) item = NSMenuItem(title: "URL in new window…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.shift item.isAlternate = true item.target = wvc item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "URL in new tab…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.isAlternate = true item.target = wvc item.tag = 3 subOpen.addItem(item) item = NSMenuItem(title: "New Window", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.target = appDelegate item.isAlternate = true item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "Playlists", action: #selector(AppDelegate.presentPlaylistSheet(_:)), keyEquivalent: "") item.representedObject = self.window item.target = appDelegate menu.addItem(item) item = NSMenuItem(title: "Appearance", action: #selector(menuClicked(_:)), keyEquivalent: "") menu.addItem(item) let subPref = NSMenu() item.submenu = subPref item = NSMenuItem(title: "Auto-hide Title Bar", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subAuto = NSMenu() item.submenu = subAuto item = NSMenuItem(title: "Never", action: #selector(hpc.autoHideTitlePress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.AutoHideTitlePreference.never.rawValue item.state = autoHideTitle == .never ? .on : .off item.target = hpc subAuto.addItem(item) item = NSMenuItem(title: "Outside", action: #selector(hpc.autoHideTitlePress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.AutoHideTitlePreference.outside.rawValue item.state = autoHideTitle == .outside ? .on : .off item.target = hpc subAuto.addItem(item) item = NSMenuItem(title: "Float Above", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subFloat = NSMenu() item.submenu = subFloat item = NSMenuItem(title: "All Spaces Disabled", action: #selector(hpc.floatOverAllSpacesPress), keyEquivalent: "") item.state = settings.floatAboveAllPreference.value.contains(.disabled) ? .on : .off item.target = hpc subFloat.addItem(item) item = NSMenuItem(title: "Full Screen", action: #selector(hpc.floatOverFullScreenAppsPress(_:)), keyEquivalent: "") item.state = settings.floatAboveAllPreference.value.contains(.screen) ? .on : .off item.target = hpc subFloat.addItem(item) item = NSMenuItem(title: "User Agent", action: #selector(wvc.userAgentPress(_:)), keyEquivalent: "") item.target = wvc subPref.addItem(item) item = NSMenuItem(title: "Translucency", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subTranslucency = NSMenu() item.submenu = subTranslucency item = NSMenuItem(title: "Opacity", action: #selector(menuClicked(_:)), keyEquivalent: "") let opacity = settings.opacityPercentage.value subTranslucency.addItem(item) let subOpacity = NSMenu() item.submenu = subOpacity item = NSMenuItem(title: "10%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (10 == opacity ? .on : .off) item.target = hpc item.tag = 10 subOpacity.addItem(item) item = NSMenuItem(title: "20%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.isEnabled = translucency.rawValue > 0 item.state = (20 == opacity ? .on : .off) item.target = hpc item.tag = 20 subOpacity.addItem(item) item = NSMenuItem(title: "30%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (30 == opacity ? .on : .off) item.target = hpc item.tag = 30 subOpacity.addItem(item) item = NSMenuItem(title: "40%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (40 == opacity ? .on : .off) item.target = hpc item.tag = 40 subOpacity.addItem(item) item = NSMenuItem(title: "50%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (50 == opacity ? .on : .off) item.target = hpc item.tag = 50 subOpacity.addItem(item) item = NSMenuItem(title: "60%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (60 == opacity ? .on : .off) item.target = hpc item.tag = 60 subOpacity.addItem(item) item = NSMenuItem(title: "70%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (70 == opacity ? .on : .off) item.target = hpc item.tag = 70 subOpacity.addItem(item) item = NSMenuItem(title: "80%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (80 == opacity ? .on : .off) item.target = hpc item.tag = 80 subOpacity.addItem(item) item = NSMenuItem(title: "90%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (90 == opacity ? .on : .off) item.target = hpc item.tag = 90 subOpacity.addItem(item) item = NSMenuItem(title: "100%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (100 == opacity ? .on : .off) item.target = hpc item.tag = 100 subOpacity.addItem(item) item = NSMenuItem(title: "Never", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.never.rawValue item.state = translucency == .never ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Always", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.always.rawValue item.state = translucency == .always ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Mouse Over", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.mouseOver.rawValue item.state = translucency == .mouseOver ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Mouse Outside", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.mouseOutside.rawValue item.state = translucency == .mouseOutside ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Save", action: #selector(hpc.saveDocument(_:)), keyEquivalent: "") item.representedObject = self.window item.target = hpc menu.addItem(item) item = NSMenuItem(title: "Search…", action: #selector(WebViewController.openSearchPress(_:)), keyEquivalent: "") item.representedObject = self.window item.target = wvc menu.addItem(item) item = NSMenuItem(title: "Close", action: #selector(HeliumPanel.performClose(_:)), keyEquivalent: "") item.target = hpc.window menu.addItem(item) menu.addItem(NSMenuItem.separator()) item = NSMenuItem(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "") item.target = NSApp menu.addItem(item) } @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool{ switch menuItem.title { default: return true } } } extension NSView { func fit(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true } func center(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true self.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true } func vCenter(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true } func top(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } } class WebViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, NSMenuDelegate, NSTabViewDelegate, WKHTTPCookieStoreObserver { @available(OSX 10.13, *) public func cookiesDidChange(in cookieStore: WKHTTPCookieStore) { DispatchQueue.main.async { cookieStore.getAllCookies { cookies in // Process cookies } } } var defaults = UserDefaults.standard var document : Document? { get { if let document : Document = self.view.window?.windowController?.document as? Document { return document } return nil } } var heliumPanelController : HeliumPanelController? { get { guard let hpc : HeliumPanelController = self.view.window?.windowController as? HeliumPanelController else { return nil } return hpc } } var trackingTag: NSView.TrackingRectTag? { get { return (self.webView.window?.windowController as? HeliumPanelController)?.viewTrackingTag } set (value) { (self.webView.window?.windowController as? HeliumPanelController)?.viewTrackingTag = value } } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() webView.becomeFirstResponder() NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.loadURL(urlFileURL:)), name: NSNotification.Name(rawValue: "HeliumLoadURL"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.loadURL(urlString:)), name: NSNotification.Name(rawValue: "HeliumLoadURLString"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(wkFlippedView(_:)), name: NSNotification.Name(rawValue: "WKFlippedView"), object: nil) // We want to be notified when a player is added let originalDidAddSubviewMethod = class_getInstanceMethod(NSView.self, #selector(NSView.didAddSubview(_:))) let originalDidAddSubviewImplementation = method_getImplementation(originalDidAddSubviewMethod!) typealias DidAddSubviewCFunction = @convention(c) (AnyObject, Selector, NSView) -> Void let castedOriginalDidAddSubviewImplementation = unsafeBitCast(originalDidAddSubviewImplementation, to: DidAddSubviewCFunction.self) let newDidAddSubviewImplementationBlock: @convention(block) (AnyObject?, NSView) -> Void = { (view: AnyObject!, subview: NSView) -> Void in castedOriginalDidAddSubviewImplementation(view, Selector(("didAddsubview:")), subview) // Swift.print("view: \(subview.className)") if subview.className == "WKFlippedView" { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WKFlippedView"), object: subview) } } let newDidAddSubviewImplementation = imp_implementationWithBlock(unsafeBitCast(newDidAddSubviewImplementationBlock, to: AnyObject.self)) method_setImplementation(originalDidAddSubviewMethod!, newDidAddSubviewImplementation) } @objc func wkFlippedView(_ note: NSNotification) { print("A Player \(String(describing: note.object)) will be opened now") guard let view = note.object as? NSView, let scrollView = view.enclosingScrollView else { return } if scrollView.hasHorizontalScroller { scrollView.horizontalScroller?.isHidden = true } if scrollView.hasVerticalScroller { scrollView.verticalScroller?.isHidden = true } } func scrollView(_ note: NSNotification) { print("Scroll View \(String(describing: note.object)) will be opened now") if let scrollView : NSScrollView = note.object as? NSScrollView { scrollView.autohidesScrollers = true } } override func viewDidAppear() { guard let doc = self.document, doc.docType == .helium else { return } // https://stackoverflow.com/questions/32056874/programmatically-wkwebview-inside-an-uiview-with-auto-layout // the autolayout is complete only when the view has appeared. if self.webView != nil { setupWebView() } // Final panel updates, called by view, when document is available if let hpc = self.heliumPanelController { hpc.documentDidLoad() } // load developer panel if asked - initially no self.webView?.configuration.preferences.setValue(UserSettings.DeveloperExtrasEnabled.value, forKey: "developerExtrasEnabled") } fileprivate func setupWebView() { webView.autoresizingMask = [NSView.AutoresizingMask.height, NSView.AutoresizingMask.width] if webView.constraints.count == 0 { webView.fit(webView.superview!) } // Allow plug-ins such as silverlight webView.configuration.preferences.plugInsEnabled = true // Custom user agent string for Netflix HTML5 support webView.customUserAgent = UserSettings.UserAgent.value // Allow zooming webView.allowsMagnification = true // Alow back and forth webView.allowsBackForwardNavigationGestures = true // Allow look ahead views webView.allowsLinkPreview = true // ditch loading indicator background loadingIndicator.appearance = NSAppearance.init(named: NSAppearance.Name.aqua) // Fetch, synchronize and observe data store for cookie changes if #available(OSX 10.13, *) { let websiteDataStore = WKWebsiteDataStore.nonPersistent() let configuration = webView.configuration configuration.websiteDataStore = websiteDataStore configuration.processPool = WKProcessPool() let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]() cookies.forEach({ configuration.websiteDataStore.httpCookieStore.setCookie($0, completionHandler: nil) }) WKWebsiteDataStore.default().httpCookieStore.add(self) } // Listen for load progress webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) observing = true // Watch command key changes NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.commandKeyDown(_:)), name: NSNotification.Name(rawValue: "commandKeyDown"), object: nil) // Intercept drags webView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0)}) webView.registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL]) webView.registerForDraggedTypes(Array(webView.acceptableTypes)) // Watch javascript selection messages unless already done let controller = webView.configuration.userContentController if controller.userScripts.count > 0 { return } controller.add(self, name: "newWindowWithUrlDetected") controller.add(self, name: "newSelectionDetected") controller.add(self, name: "newUrlDetected") let js = NSString.string(fromAsset: "Helium-js") let script = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true) controller.addUserScript(script) // make http: -> https: guarded by preference if #available(OSX 10.13, *), UserSettings.PromoteHTTPS.value { // https://developer.apple.com/videos/play/wwdc2017/220/ 21:04 let jsonString = """ [{ "trigger" : { "url-filter" : ".*" }, "action" : { "type" : "make-https" } }] """ WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "httpRuleList", encodedContentRuleList: jsonString, completionHandler: {(list, error) in guard let contentRuleList = list else { return } self.webView.configuration.userContentController.add(contentRuleList) }) } } var appDelegate: AppDelegate = NSApp.delegate as! AppDelegate @objc dynamic var observing : Bool = false func setupTrackingAreas(_ establish: Bool) { if let tag = trackingTag { view.removeTrackingRect(tag) trackingTag = nil } if establish { trackingTag = view.addTrackingRect(view.bounds, owner: self, userData: nil, assumeInside: false) } webView.updateTrackingAreas() } override func viewDidLayout() { super.viewDidLayout() // ditch horizonatal scroll when not over if let scrollView = self.webView.enclosingScrollView { if scrollView.hasHorizontalScroller { scrollView.horizontalScroller?.isHidden = true } if scrollView.hasVerticalScroller { scrollView.verticalScroller?.isHidden = true } } setupTrackingAreas(true) } override func viewWillDisappear() { guard let wc = self.view.window?.windowController, !wc.isKind(of: ReleasePanelController.self) else { return } let navDelegate = webView.navigationDelegate as! NSObject // Wind down all observations if observing { webView.removeObserver(navDelegate, forKeyPath: "estimatedProgress") webView.removeObserver(navDelegate, forKeyPath: "title") observing = false } } // MARK: Actions @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool{ switch menuItem.title { case "Developer Extras": guard let state = webView.configuration.preferences.value(forKey: "developerExtrasEnabled") else { return false } menuItem.state = (state as? NSNumber)?.boolValue == true ? .on : .off return true case "Back": return webView.canGoBack case "Forward": return webView.canGoForward default: return true } } @objc @IBAction func backPress(_ sender: AnyObject) { webView.goBack() } @objc @IBAction func forwardPress(_ sender: AnyObject) { webView.goForward() } @objc internal func commandKeyDown(_ notification : Notification) { let commandKeyDown : NSNumber = notification.object as! NSNumber if let window = self.view.window { window.isMovableByWindowBackground = commandKeyDown.boolValue // Swift.print(String(format: "CMND %@", commandKeyDown.boolValue ? "v" : "^")) } } fileprivate func zoomIn() { webView.magnification += 0.1 } fileprivate func zoomOut() { webView.magnification -= 0.1 } fileprivate func resetZoom() { webView.magnification = 1 } @objc @IBAction func developerExtrasEnabledPress(_ sender: NSMenuItem) { self.webView?.configuration.preferences.setValue((sender.state != .on), forKey: "developerExtrasEnabled") } @objc @IBAction func openFilePress(_ sender: AnyObject) { var viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window let open = NSOpenPanel() open.allowsMultipleSelection = true open.canChooseDirectories = false open.resolvesAliases = true open.canChooseFiles = true // Have window, but make it active NSApp.activate(ignoringOtherApps: true) open.worksWhenModal = true open.beginSheetModal(for: window!, completionHandler: { (response: NSApplication.ModalResponse) in if response == NSApplication.ModalResponse.OK { var parent : NSWindow? = window var latest : Document? let urls = open.urls for url in urls { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.webView.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) } } }) } @objc @IBAction func openLocationPress(_ sender: AnyObject) { let viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window var urlString = currentURL if let rawString = NSPasteboard.general.string(forType: NSPasteboard.PasteboardType.string), rawString.isValidURL() { urlString = rawString } appDelegate.didRequestUserUrl(RequestUserStrings ( currentURL: urlString, alertMessageText: "URL to load", alertButton1stText: "Load", alertButton1stInfo: nil, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "Home", alertButton3rdInfo: UserSettings.HomePageURL.value), onWindow: window as? HeliumPanel, title: "Enter URL", acceptHandler: { (urlString: String) in guard let newURL = URL.init(string: urlString) else { return } if viewOptions.contains(.t_view) { _ = self.appDelegate.openURLInNewWindow(newURL, attachTo: window) } else if viewOptions.contains(.w_view) { _ = self.appDelegate.openURLInNewWindow(newURL) } else { self.loadURL(url: newURL) } }) } @objc @IBAction func openSearchPress(_ sender: AnyObject) { let viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window let name = k.searchNames[ UserSettings.Search.value ] let info = k.searchInfos[ UserSettings.Search.value ] appDelegate.didRequestSearch(RequestUserStrings ( currentURL: nil, alertMessageText: "Search", alertButton1stText: name, alertButton1stInfo: info, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "New Window", alertButton3rdInfo: "Results in new window"), onWindow: self.view.window as? HeliumPanel, title: "Web Search", acceptHandler: { (newWindow: Bool, searchURL: URL) in if viewOptions.contains(.t_view) { _ = self.appDelegate.openURLInNewWindow(searchURL, attachTo: window) } else if viewOptions.contains(.w_view) { _ = self.appDelegate.openURLInNewWindow(searchURL) } else { self.loadURL(url: searchURL) } }) } @objc @IBAction fileprivate func reloadPress(_ sender: AnyObject) { requestedReload() } @objc @IBAction fileprivate func clearPress(_ sender: AnyObject) { clear() } @objc @IBAction fileprivate func resetZoomLevel(_ sender: AnyObject) { resetZoom() } @objc @IBAction func userAgentPress(_ sender: AnyObject) { appDelegate.didRequestUserAgent(RequestUserStrings ( currentURL: webView.customUserAgent, alertMessageText: "Custom user agent", alertButton1stText: "Set", alertButton1stInfo: nil, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "Default", alertButton3rdInfo: UserSettings.UserAgent.default), onWindow: NSApp.keyWindow as? HeliumPanel, title: "Custom User Agent", acceptHandler: { (newUserAgent: String) in self.webView.customUserAgent = newUserAgent } ) } @objc @IBAction fileprivate func zoomIn(_ sender: AnyObject) { zoomIn() } @objc @IBAction fileprivate func zoomOut(_ sender: AnyObject) { zoomOut() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: Loading internal var currentURL: String? { return webView.url?.absoluteString } internal func loadURL(text: String) { let text = UrlHelpers.ensureScheme(text) if let url = URL(string: text) { webView.load(URLRequest.init(url: url)) } } internal func loadURL(url: URL) { webView.next(url: url) } @objc internal func loadURL(urlFileURL: Notification) { if let fileURL = urlFileURL.object, let userInfo = urlFileURL.userInfo { if userInfo["hwc"] as? NSWindowController == self.view.window?.windowController { loadURL(url: fileURL as! URL) } else { // load new window with URL loadURL(url: urlFileURL.object as! URL) } } } @objc func loadURL(urlString: Notification) { if let userInfo = urlString.userInfo { if userInfo["hwc"] as? NSWindowController != self.view.window?.windowController { return } } if let string = urlString.object as? String { _ = loadURL(text: string) } } func loadAttributes(dict: Dictionary<String,Any>) { Swift.print("loadAttributes: dict \(dict)") } func loadAttributes(item: PlayItem) { loadAttributes(dict: item.dictionary()) } // TODO: For now just log what we would play once we figure out how to determine when an item finishes so we can start the next @objc func playerDidFinishPlaying(_ note: Notification) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: note.object) print("Video Finished") } fileprivate func requestedReload() { webView.reload() } // MARK: Javascript func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //Swift.print("userContentController") switch message.name { case "newWindowWithUrlDetected": if let url = URL.init(string: message.body as! String) { webView.selectedURL = url //Swift.print("ucc: new -> \(url.absoluteString)") } break case "newSelectionDetected": if let urlString : String = message.body as? String { webView.selectedText = urlString //Swift.print("ucc: str -> \(urlString)") } break case "newUrlDetected": if let url = URL.init(string: message.body as! String) { webView.selectedURL = url //Swift.print("ucc: url -> \(url.absoluteString)") } break default: Swift.print("ucc: unknown \(message.name)") } } // MARK: Webview functions func clear() { // Reload to home page (or default if no URL stored in UserDefaults) guard self.document?.docType == .helium, let url = URL.init(string: UserSettings.HomePageURL.value) else { return } webView.load(URLRequest.init(url: url)) } @objc @IBOutlet var webView: MyWebView! var webSize = CGSize(width: 0,height: 0) @objc @IBOutlet weak var borderView: WebBorderView! @objc @IBOutlet weak var loadingIndicator: NSProgressIndicator! override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let mwv = object as? MyWebView, mwv == self.webView else { return } // We *must* have a key path guard let keyPath = keyPath else { return } switch keyPath { case "estimatedProgress": if let progress = change?[NSKeyValueChangeKey(rawValue: "new")] as? Float { let percent = progress * 100 var title = String(format: "Loading... %.2f%%", percent) if percent == 100, let url = (self.webView.url) { // Initial recording for this url session let notif = Notification(name: Notification.Name(rawValue: "HeliumNewURL"), object: url, userInfo: [k.fini : false, k.view : self.webView as Any]) NotificationCenter.default.post(notif) // once loaded update window title,size with video name,dimension if let toolTip = (mwv.url?.absoluteString) { title = url.isFileURL ? url.lastPathComponent : (url.path != "/" ? url.lastPathComponent : url.host) ?? toolTip self.heliumPanelController?.hoverBar?.superview?.toolTip = toolTip if let track = AVURLAsset(url: url, options: nil).tracks.first { // if it's a video file, get and set window content size to its dimentions if track.mediaType == AVMediaType.video { webSize = track.naturalSize // Try to adjust initial size if possible let os = appDelegate.os switch (os.majorVersion, os.minorVersion, os.patchVersion) { case (10, 10, _), (10, 11, _), (10, 12, _): if let oldSize = mwv.window?.contentView?.bounds.size, oldSize != webSize, var origin = mwv.window?.frame.origin, let theme = self.view.window?.contentView?.superview { var iterator = theme.constraints.makeIterator() Swift.print(String(format:"view:%p webView:%p", mwv.superview!, mwv)) while let constraint = iterator.next() { Swift.print("\(constraint.priority) \(constraint)") } origin.y += (oldSize.height - webSize.height) mwv.window?.setContentSize(webSize) mwv.window?.setFrameOrigin(origin) mwv.bounds.size = webSize } break default: // Issue still to be resolved so leave as-is for now Swift.print("os \(os)") if webSize != webView.fittingSize { webView.bounds.size = webView.fittingSize webSize = webView.bounds.size } } } // Wait for URL to finish let videoPlayer = AVPlayer(url: url) let item = videoPlayer.currentItem NotificationCenter.default.addObserver(self, selector: #selector(WebViewController.playerDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main, using: { (_) in DispatchQueue.main.async { Swift.print("restarting #1") videoPlayer.seek(to: CMTime.zero) videoPlayer.play() } }) NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item, queue: .main, using: { (_) in DispatchQueue.main.async { Swift.print("restarting #2") videoPlayer.seek(to: CMTime.zero) videoPlayer.play() } }) } else { restoreSettings(url.absoluteString) } } else { title = appDelegate.appName } self.view.window?.title = title // Remember for later restoration if let doc = self.document, let hpc = doc.heliumPanelController { self.view.window?.representedURL = url hpc.updateTitleBar(didChange: false) NSApp.addWindowsItem(self.view.window!, title: url.lastPathComponent, filename: false) } } } break case "loading": guard let loading = change?[NSKeyValueChangeKey(rawValue: "new")] as? Bool, loading == loadingIndicator.isHidden else { return } Swift.print("loading: \(loading ? "YES" : "NO")") break; case "title": title = mwv.title break; default: Swift.print("Unknown observing keyPath \(String(describing: keyPath))") } } fileprivate func restoreSettings(_ title: String) { guard let dict = defaults.dictionary(forKey: title), let doc = self.document, let hpc = doc.heliumPanelController else { return } doc.restoreSettings(with: dict) hpc.documentDidLoad() } //Convert a YouTube video url that starts at a certian point to popup/embedded design // (i.e. ...?t=1m2s --> ?start=62) func makeCustomStartTimeURL(_ url: String) -> String { let startTime = "?t=" let idx = url.indexOf(startTime) if idx == -1 { return url } else { let timeIdx = idx.advanced(by: 3) let hmsString = url[timeIdx...].replacingOccurrences(of: "h", with: ":").replacingOccurrences(of: "m", with: ":").replacingOccurrences(of: "s", with: ":") var returnURL = url var final = 0 let hms = hmsString.components(separatedBy: ":") if hms.count > 2, let hrs = Int(hms[2]) { final += 3600 * hrs } if hms.count > 1, let mins = Int(hms[1]) { final += 60 * mins } if hms.count > 0, let secs = Int(hms[0]) { final += secs } returnURL.removeSubrange(returnURL.index(returnURL.startIndex, offsetBy: idx+1) ..< returnURL.endIndex) returnURL = "?start=" returnURL = returnURL + String(final) return returnURL } } //Helper function to return the hash of the video for encoding a popout video that has a start time code. fileprivate func getVideoHash(_ url: String) -> String { let startOfHash = url.indexOf(".be/") let endOfHash = startOfHash.advanced(by: 4) let restOfUrl = url.indexOf("?t") let hash = url[url.index(url.startIndex, offsetBy: endOfHash) ..< (endOfHash == -1 ? url.endIndex : url.index(url.startIndex, offsetBy: restOfUrl))] return String(hash) } /* func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { let alertController = NSAlertController(title: nil, message: message, preferredStyle: .ActionSheet) alertController.addAction(NSAlertAction(title: "Ok", style: .Default, handler: { (action) in completionHandler() })) self.presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { let alertController = AlertController(title: nil, message: message, preferredStyle: .ActionSheet) alertController.addAction(AlertAction(title: "Ok", style: .Default, handler: { (action) in completionHandler(true) })) alertController.addAction(AlertAction(title: "Cancel", style: .Default, handler: { (action) in completionHandler(false) })) self.presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) { let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .ActionSheet) alertController.addTextFieldWithConfigurationHandler { (textField) in textField.text = defaultText } alertController.addAction(AlertAction(title: "Ok", style: .Default, handler: { (action) in if let text = alertController.textFields?.first?.text { completionHandler(text) } else { completionHandler(defaultText) } })) alertController.addAction(AlertAction(title: "Cancel", style: .Default, handler: { (action) in completionHandler(nil) })) self.presentViewController(alertController, animated: true, completion: nil) } */ // MARK: Navigation Delegate // Redirect Hulu and YouTube to pop-out videos func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let viewOptions = appDelegate.getViewOptions var url = navigationAction.request.url! guard navigationAction.buttonNumber < 2 else { Swift.print("newWindow with url:\(String(describing: url))") if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(url, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(url) } decisionHandler(WKNavigationActionPolicy.cancel) return } guard !UserSettings.DisabledMagicURLs.value else { if let selectedURL = (webView as! MyWebView).selectedURL { url = selectedURL } if navigationAction.buttonNumber > 1 { if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(url, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(url) } decisionHandler(WKNavigationActionPolicy.cancel) } else { decisionHandler(WKNavigationActionPolicy.allow) } return } if let newUrl = UrlHelpers.doMagic(url), newUrl != url { decisionHandler(WKNavigationActionPolicy.cancel) if let selectedURL = (webView as! MyWebView).selectedURL { url = selectedURL } if navigationAction.buttonNumber > 1 { if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(newUrl, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(newUrl) } } else { loadURL(url: newUrl) } } else { decisionHandler(WKNavigationActionPolicy.allow) } } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { guard let response = navigationResponse.response as? HTTPURLResponse, let url = navigationResponse.response.url else { decisionHandler(.allow) return } // load cookies if #available(OSX 10.13, *) { if let headerFields = response.allHeaderFields as? [String:String] { Swift.print("\(url.absoluteString) allHeaderFields:\n\(headerFields)") let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url) cookies.forEach({ cookie in webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: nil) }) } } decisionHandler(.allow) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { Swift.print("didStartProvisionalNavigation - 1st") } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { Swift.print("didCommit - 2nd") } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { handleError(error) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { handleError(error) } fileprivate func handleError(_ error: Error) { let message = error.localizedDescription Swift.print("didFail?: \((error as NSError).code): \(message)") if (error as NSError).code >= 400 { NSApp.presentError(error) } else if (error as NSError).code < 0 { if let info = error._userInfo as? [String: Any] { if let url = info["NSErrorFailingURLKey"] as? URL { appDelegate.userAlertMessage(message, info: url.absoluteString) } else if let urlString = info["NSErrorFailingURLStringKey"] as? String { appDelegate.userAlertMessage(message, info: urlString) } } } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) { let doc = self.document let hpc = doc?.heliumPanelController guard let url = webView.url else { return } // Restore setting not done by document controller if let hpc = hpc { hpc.documentDidLoad() } // Finish recording of for this url session let notif = Notification(name: Notification.Name(rawValue: "HeliumNewURL"), object: url, userInfo: [k.fini : true]) NotificationCenter.default.post(notif) Swift.print("webView:didFinish navigation: '\(String(describing: webView.title))' => \(url.absoluteString) - last") /* let html = """ <html> <body> <h1>Hello, Swift!</h1> </body> </html> """ webView.loadHTMLString(html, baseURL: nil)*/ } func webView(_ webView: WKWebView, didFinishLoad navigation: WKNavigation) { guard let title = webView.title, let urlString : String = webView.url?.absoluteString else { return } Swift.print("webView:didFinishLoad: '\(title)' => \(urlString)") } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let serverTrust = challenge.protectionSpace.serverTrust else { return completionHandler(.useCredential, nil) } let exceptions = SecTrustCopyExceptions(serverTrust) SecTrustSetExceptions(serverTrust, exceptions) completionHandler(.useCredential, URLCredential(trust: serverTrust)) } // MARK: UI Delegate func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { _ = appDelegate.openURLInNewWindow(navigationAction.request.url!) return nil } // We really want to use the supplied config, so use custom setup var newWebView : WKWebView? Swift.print("createWebViewWith") if let newURL = navigationAction.request.url { do { let doc = try NSDocumentController.shared.makeDocument(withContentsOf: newURL, ofType: k.Custom) if let hpc = doc.windowControllers.first as? HeliumPanelController, let window = hpc.window { let newView = MyWebView.init(frame: webView.frame, configuration: configuration) let contentView = window.contentView! let wvc = hpc.webViewController hpc.webViewController.webView = newView contentView.addSubview(newView) hpc.webViewController.loadURL(text: newURL.absoluteString) newView.navigationDelegate = wvc newView.uiDelegate = wvc newWebView = hpc.webView wvc.viewDidLoad() // Setups all done, make us visible doc.showWindows() } } catch let error { NSApp.presentError(error) } } return newWebView } func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) { Swift.print("runOpenPanelWith") } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { Swift.print("runJavaScriptAlertPanelWithMessage") } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { Swift.print("runJavaScriptConfirmPanelWithMessage") } func webViewDidClose(_ webView: WKWebView) { Swift.print("webViewDidClose") } // MARK: TabView Delegate func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { if let item = tabViewItem { Swift.print("willSelect: label: \(item.label) ident: \(String(describing: item.identifier))") } } func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { if let item = tabViewItem { Swift.print("didSelect: label: \(item.label) ident: \(String(describing: item.identifier))") } } } class ReleaseViewController : WebViewController { } comment out flipped view tracking // // WebViewController.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // Copyright © 2017 Carlos D. Santiago. All rights reserved. // import Cocoa import WebKit import AVFoundation import Carbon.HIToolbox extension WKWebViewConfiguration { /// Async Factory method to acquire WKWebViewConfigurations packaged with system cookies static func cookiesIncluded(completion: @escaping (WKWebViewConfiguration?) -> Void) { let config = WKWebViewConfiguration() guard let cookies = HTTPCookieStorage.shared.cookies else { completion(config) return } // Use nonPersistent() or default() depending on if you want cookies persisted to disk // and shared between WKWebViews of the same app (default), or not persisted and not shared // across WKWebViews in the same app. let dataStore = WKWebsiteDataStore.nonPersistent() let waitGroup = DispatchGroup() for cookie in cookies { waitGroup.enter() if #available(OSX 10.13, *) { dataStore.httpCookieStore.setCookie(cookie) { waitGroup.leave() } } else { // Fallback on earlier versions } } waitGroup.notify(queue: DispatchQueue.main) { config.websiteDataStore = dataStore completion(config) } } } class WebBorderView : NSView { var isReceivingDrag = false { didSet { needsDisplay = true } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) self.isHidden = !isReceivingDrag // Swift.print("web borderView drawing \(isHidden ? "NO" : "YES")....") if isReceivingDrag { NSColor.selectedKnobColor.set() let path = NSBezierPath(rect:bounds) path.lineWidth = 4 path.stroke() } } } class MyWebView : WKWebView { var appDelegate: AppDelegate = NSApp.delegate as! AppDelegate override class func handlesURLScheme(_ urlScheme: String) -> Bool { Swift.print("handleURLScheme: \(urlScheme)") return true } var selectedText : String? var selectedURL : URL? var chromeType: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "org.chromium.drag-dummy-type") } var finderNode: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "com.apple.finder.node") } var webarchive: NSPasteboard.PasteboardType { return NSPasteboard.PasteboardType.init(rawValue: "com.apple.webarchive") } var acceptableTypes: Set<NSPasteboard.PasteboardType> { return [.URL, .fileURL, .list, .item, .html, .pdf, .png, .rtf, .rtfd, .tiff, finderNode, webarchive] } var filteringOptions = [NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes:NSImage.imageTypes] @objc internal func menuClicked(_ sender: AnyObject) { if let menuItem = sender as? NSMenuItem { Swift.print("Menu \(menuItem.title) clicked") } } override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) { // Pick off javascript items we want to ignore or handle for title in ["Open Link", "Open Link in New Window", "Download Linked File"] { if let item = menu.item(withTitle: title) { if title == "Download Linked File" { menu.removeItem(item) } else if title == "Open Link" { item.action = #selector(MyWebView.openLinkInWindow(_:)) item.target = self } else { item.tag = ViewOptions.w_view.rawValue item.action = #selector(MyWebView.openLinkInNewWindow(_:)) item.target = self } } } publishApplicationMenu(menu); } @objc func openLinkInWindow(_ item: NSMenuItem) { if let urlString = self.selectedText, let url = URL.init(string: urlString) { load(URLRequest.init(url: url)) } else if let url = self.selectedURL { load(URLRequest.init(url: url)) } } @objc func openLinkInNewWindow(_ item: NSMenuItem) { if let urlString = self.selectedText, let url = URL.init(string: urlString) { _ = appDelegate.openURLInNewWindow(url, attachTo: item.representedObject as? NSWindow) } else if let url = self.selectedURL { _ = appDelegate.openURLInNewWindow(url, attachTo: item.representedObject as? NSWindow) } } override var mouseDownCanMoveWindow: Bool { get { if let window = self.window { return window.isMovableByWindowBackground } else { return false } } } var heliumPanelController : HeliumPanelController? { get { guard let hpc : HeliumPanelController = self.window?.windowController as? HeliumPanelController else { return nil } return hpc } } var webViewController : WebViewController? { get { guard let wvc : WebViewController = self.window?.contentViewController as? WebViewController else { return nil } return wvc } } /* override func load(_ request: URLRequest) -> WKNavigation? { Swift.print("we got \(request)") return super.load(request) } */ @objc @IBAction internal func cut(_ sender: Any) { let pb = NSPasteboard.general pb.clearContents() if let urlString = self.url?.absoluteString { pb.setString(urlString, forType: NSPasteboard.PasteboardType.string) (self.uiDelegate as! WebViewController).clear() } } @objc @IBAction internal func copy(_ sender: Any) { let pb = NSPasteboard.general pb.clearContents() if let urlString = self.url?.absoluteString { pb.setString(urlString, forType: NSPasteboard.PasteboardType.string) } } @objc @IBAction internal func paste(_ sender: Any) { let pb = NSPasteboard.general guard let rawString = pb.string(forType: NSPasteboard.PasteboardType.string), rawString.isValidURL() else { return } self.load(URLRequest.init(url: URL.init(string: rawString)!)) } @objc @IBAction internal func delete(_ sender: Any) { self.cancelOperation(sender) Swift.print("cancel") } func html(_ html : String) { self.loadHTMLString(html, baseURL: nil) } func next(url: URL) { let doc = self.heliumPanelController?.document as! Document var nextURL = url // Resolve alias before sandbox bookmarking if let webloc = nextURL.webloc { next(url: webloc) return } if nextURL.isFileURL { if let original = (nextURL as NSURL).resolvedFinderAlias() { nextURL = original } if nextURL.isFileURL, appDelegate.isSandboxed() && !appDelegate.storeBookmark(url: nextURL) { Swift.print("Yoink, unable to sandbox \(nextURL)") return } } // h3w files are playlist extractions, presented as a sheet or window guard nextURL.pathExtension == k.h3w, let dict = NSDictionary(contentsOf: url) else { // keep document in sync with webView url doc.update(to: nextURL) self.load(URLRequest(url: nextURL)) ///self.loadFileURL(nextURL, allowingReadAccessTo: nextURL) return } // We could have 3 keys: <source-name>, k.playlists, k.playitems or promise file of playlists var playlists = [PlayList]() if let names : [String] = dict.value(forKey: k.playlists) as? [String] { for name in names { if let items = dict.value(forKey: name) as? [Dictionary<String,Any>] { let playlist = PlayList.init(name: name, list: [PlayItem]()) for item in items { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } } } else if let items = dict.value(forKey: k.playitems) as? [Dictionary<String,Any>] { let playlist = PlayList.init(name: nextURL.lastPathComponent, list: [PlayItem]()) for item in items { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } else { for (name,list) in dict { let playlist = PlayList.init(name: name as! String, list: [PlayItem]()) for item in (list as? [Dictionary<String,Any>])! { playlist.list.append(PlayItem.init(with: item)) } playlists.append(playlist) } } if let wvc = self.webViewController, wvc.presentedViewControllers?.count == 0 { let storyboard = NSStoryboard(name: "Main", bundle: nil) let pvc = storyboard.instantiateController(withIdentifier: "PlaylistViewController") as! PlaylistViewController pvc.playlists.append(contentsOf: playlists) pvc.webViewController = self.webViewController wvc.presentAsSheet(pvc) } } func text(_ text : String) { if FileManager.default.fileExists(atPath: text) { let url = URL.init(fileURLWithPath: text) next(url: url) return } if let url = URL.init(string: text) { do { if try url.checkResourceIsReachable() { next(url: url) return } } catch let error as NSError { Swift.print("url?: \(error.code):\(error.localizedDescription): \(text)") } } if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) let wvc = self.window?.contentViewController (wvc as! WebViewController).loadAttributes(dict: json as! Dictionary<String, Any>) return } catch let error as NSError { Swift.print("json: \(error.code):\(error.localizedDescription): \(text)") } } let html = String(format: """ <html> <body> <code> %@ </code> </body> </html> """, text); self.loadHTMLString(html, baseURL: nil) } func text(attrributedString text: NSAttributedString) { do { let docAttrs = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html] let data = try text.data(from: NSMakeRange(0, text.length), documentAttributes: docAttrs) if let attrs = String(data: data, encoding: .utf8) { let html = String(format: """ <html> <body> <code> %@ </code> </body> </html> """, attrs); self.loadHTMLString(html, baseURL: nil) } } catch let error as NSError { Swift.print("attributedString -> html: \(error.code):\(error.localizedDescription): \(text)") } } // MARK: Drag and Drop - Before Release func shouldAllowDrag(_ info: NSDraggingInfo) -> Bool { guard let doc = webViewController?.document, doc.docType == .helium else { return false } let pboard = info.draggingPasteboard let items = pboard.pasteboardItems! var canAccept = false let readableClasses = [NSURL.self, NSString.self, NSAttributedString.self, NSPasteboardItem.self, PlayList.self, PlayItem.self] if pboard.canReadObject(forClasses: readableClasses, options: filteringOptions) { canAccept = true } else { for item in items { Swift.print("item: \(item)") } } Swift.print("web shouldAllowDrag -> \(canAccept) \(items.count) item(s)") return canAccept } var borderView: WebBorderView { get { return (uiDelegate as! WebViewController).borderView } } var isReceivingDrag : Bool { get { return borderView.isReceivingDrag } set (value) { borderView.isReceivingDrag = value } } override func draggingEntered(_ info: NSDraggingInfo) -> NSDragOperation { let pboard = info.draggingPasteboard let items = pboard.pasteboardItems! let allow = shouldAllowDrag(info) if uiDelegate != nil { isReceivingDrag = allow } let dragOperation = allow ? .copy : NSDragOperation() Swift.print("web draggingEntered -> \(dragOperation) \(items.count) item(s)") return dragOperation } override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { let allow = shouldAllowDrag(sender) sender.animatesToDestination = true Swift.print("web prepareForDragOperation -> \(allow)") return allow } override func draggingExited(_ sender: NSDraggingInfo?) { Swift.print("web draggingExited") if uiDelegate != nil { isReceivingDrag = false } } var lastDragSequence : Int = 0 override func draggingUpdated(_ info: NSDraggingInfo) -> NSDragOperation { appDelegate.newViewOptions = appDelegate.getViewOptions let sequence = info.draggingSequenceNumber if sequence != lastDragSequence { Swift.print("web draggingUpdated -> .copy") lastDragSequence = sequence } return .copy } // MARK: Drag and Drop - After Release override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { var viewOptions = appDelegate.newViewOptions let options : [NSPasteboard.ReadingOptionKey: Any] = [NSPasteboard.ReadingOptionKey.urlReadingFileURLsOnly : true, NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes : [ kUTTypeImage, kUTTypeVideo, kUTTypeMovie], NSPasteboard.ReadingOptionKey(rawValue: PlayList.className()) : true, NSPasteboard.ReadingOptionKey(rawValue: PlayItem.className()) : true] let pboard = sender.draggingPasteboard let items = pboard.pasteboardItems var parent : NSWindow? = self.window var latest : Document? var handled = 0 for item in items! { if handled == items!.count { break } if let urlString = item.string(forType: NSPasteboard.PasteboardType(rawValue: kUTTypeURL as String)) { self.next(url: URL(string: urlString)!) handled += 1 continue } for type in pboard.types! { Swift.print("web type: \(type)") switch type { case .files: if let files = pboard.propertyList(forType: type) { Swift.print("files \(files)") } break case .URL, .fileURL: if let urlString = item.string(forType: type), let url = URL.init(string: urlString) { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } else if let data = item.data(forType: type), let url = NSKeyedUnarchiver.unarchiveObject(with: data) { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url as! URL , attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url as! URL) } else { self.next(url: url as! URL) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } else if let urls: Array<AnyObject> = pboard.readObjects(forClasses: [NSURL.classForCoder()], options: options) as Array<AnyObject>? { for url in urls as! [URL] { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url , attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } } break case .list: if let playlists: Array<AnyObject> = pboard.readObjects(forClasses: [PlayList.classForCoder()], options: options) as Array<AnyObject>? { var parent : NSWindow? = self.window var latest : Document? for playlist in playlists { for playitem in playlist.list { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link) } else { self.next(url: playitem.link) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) } handled += 1 } } break case .item: if let playitems: Array<AnyObject> = pboard.readObjects(forClasses: [PlayItem.classForCoder()], options: options) as Array<AnyObject>? { var parent : NSWindow? = self.window var latest : Document? for playitem in playitems { Swift.print("item: \(playitem)") if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(playitem.link) } else { self.next(url: playitem.link) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) handled += 1 } } break case .data: if let data = item.data(forType: type), let item = NSKeyedUnarchiver.unarchiveObject(with: data) { if let playlist = item as? PlayList { Swift.print("list: \(playlist)") handled += 1 } else if let playitem = item as? PlayItem { Swift.print("item: \(playitem)") handled += 1 } else { Swift.print("data: \(data)") } } break case .rtf, .rtfd, .tiff: if let data = item.data(forType: type), let text = NSAttributedString(rtf: data, documentAttributes: nil) { self.text(text.string) handled += 1 } break case .string, .tabularText: if let text = item.string(forType: type) { self.text(text) handled += 1 } break case webarchive: if let data = item.data(forType: type) { let html = String(decoding: data, as: UTF8.self) self.html(html) handled += 1 } if let text = item.string(forType: type) { Swift.print("\(type) text \(String(describing: text))") self.text(text) handled += 1 } if let prop = item.propertyList(forType: type) { if let html = String.init(data: prop as! Data, encoding: .utf8) { self.html(html) handled += 1 } else { Swift.print("\(type) prop \(String(describing: prop))") } } break case chromeType: if let data = item.data(forType: type) { let html = String(decoding: data, as: UTF8.self) if html.count > 0 { self.html(html) handled += 1 } } if let text = item.string(forType: type) { Swift.print("\(type) text \(String(describing: text))") if text.count > 0 { self.text(text) handled += 1 } } if let prop = item.propertyList(forType: type) { if let html = String.init(data: prop as! Data, encoding: .utf8) { self.html(html) handled += 1 } else { Swift.print("\(type) prop \(String(describing: prop))") } } break default: Swift.print("unkn: \(type)") if let data = item.data(forType: type) { Swift.print("data: \(data.count) bytes") //self.load(data, mimeType: <#T##String#>, characterEncodingName: UTF8, baseURL: <#T##URL#>) } } if handled == items?.count { break } } } Swift.print("web performDragOperation -> \(handled == items?.count ? "true" : "false")") return handled == items?.count } // MARK: Context Menu // // Intercepted actions; capture state needed for avToggle() var playPressMenuItem = NSMenuItem() @objc @IBAction func playActionPress(_ sender: NSMenuItem) { // Swift.print("\(playPressMenuItem.title) -> target:\(String(describing: playPressMenuItem.target)) action:\(String(describing: playPressMenuItem.action)) tag:\(playPressMenuItem.tag)") _ = playPressMenuItem.target?.perform(playPressMenuItem.action, with: playPressMenuItem.representedObject) // this releases original menu item sender.representedObject = self let notif = Notification(name: Notification.Name(rawValue: "HeliumItemAction"), object: sender) NotificationCenter.default.post(notif) } var mutePressMenuItem = NSMenuItem() @objc @IBAction func muteActionPress(_ sender: NSMenuItem) { // Swift.print("\(mutePressMenuItem.title) -> target:\(String(describing: mutePressMenuItem.target)) action:\(String(describing: mutePressMenuItem.action)) tag:\(mutePressMenuItem.tag)") _ = mutePressMenuItem.target?.perform(mutePressMenuItem.action, with: mutePressMenuItem.representedObject) // this releases original menu item sender.representedObject = self let notif = Notification(name: Notification.Name(rawValue: "HeliumItemAction"), object: sender) NotificationCenter.default.post(notif) } // // Actions used by contextual menu, or status item, or our app menu func publishApplicationMenu(_ menu: NSMenu) { let wvc = self.window?.contentViewController as! WebViewController let hpc = self.window?.windowController as! HeliumPanelController let settings = (hpc.document as! Document).settings let autoHideTitle = hpc.autoHideTitlePreference let translucency = hpc.translucencyPreference // Remove item(s) we cannot support for title in ["Enter Picture in Picture", "Download Video"] { if let item = menu.item(withTitle: title) { menu.removeItem(item) } } // Alter item(s) we want to support for title in ["Enter Full Screen", "Open Video in New Window"] { if let item = menu.item(withTitle: title) { // Swift.print("old: \(title) -> target:\(String(describing: item.target)) action:\(String(describing: item.action)) tag:\(item.tag)") if item.title.hasSuffix("Enter Full Screen") { item.target = appDelegate item.action = #selector(appDelegate.toggleFullScreen(_:)) item.state = appDelegate.fullScreen != nil ? .on : .off } else if self.url != nil { item.representedObject = self.url item.target = appDelegate item.action = #selector(appDelegate.openVideoInNewWindowPress(_:)) } else { item.isEnabled = false } // Swift.print("new: \(title) -> target:\(String(describing: item.target)) action:\(String(describing: item.action)) tag:\(item.tag)") } } // Intercept these actions so we can record them for later // NOTE: cache original menu item so it does not disappear for title in ["Play", "Pause", "Mute"] { if let item = menu.item(withTitle: title) { if item.title == "Mute" { mutePressMenuItem.action = item.action mutePressMenuItem.target = item.target mutePressMenuItem.title = item.title mutePressMenuItem.state = item.state mutePressMenuItem.tag = item.tag mutePressMenuItem.representedObject = item item.action = #selector(self.muteActionPress(_:)) item.target = self } else { playPressMenuItem.action = item.action playPressMenuItem.target = item.target playPressMenuItem.title = item.title playPressMenuItem.state = item.state playPressMenuItem.tag = item.tag playPressMenuItem.representedObject = item item.action = #selector(self.playActionPress(_:)) item.target = self } // let state = item.state == .on ? "yes" : "no" // Swift.print("target: \(title) -> \(String(describing: item.action)) state: \(state) tag:\(item.tag)") } } var item: NSMenuItem item = NSMenuItem(title: "Cut", action: #selector(MyWebView.cut(_:)), keyEquivalent: "") menu.addItem(item) item = NSMenuItem(title: "Copy", action: #selector(MyWebView.copy(_:)), keyEquivalent: "") menu.addItem(item) item = NSMenuItem(title: "Paste", action: #selector(MyWebView.paste(_:)), keyEquivalent: "") menu.addItem(item) menu.addItem(NSMenuItem.separator()) item = NSMenuItem(title: "New Window", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.target = appDelegate item.tag = 1 menu.addItem(item) item = NSMenuItem(title: "New Tab", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.target = appDelegate item.isAlternate = true item.tag = 3 menu.addItem(item) item = NSMenuItem(title: "Open", action: #selector(menuClicked(_:)), keyEquivalent: "") menu.addItem(item) let subOpen = NSMenu() item.submenu = subOpen item = NSMenuItem(title: "File…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.target = wvc subOpen.addItem(item) item = NSMenuItem(title: "File in new window…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.shift item.isAlternate = true item.target = wvc item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "File in new tab…", action: #selector(WebViewController.openFilePress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.isAlternate = true item.target = wvc item.tag = 3 subOpen.addItem(item) item = NSMenuItem(title: "URL…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.target = wvc subOpen.addItem(item) item = NSMenuItem(title: "URL in new window…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.shift item.isAlternate = true item.target = wvc item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "URL in new tab…", action: #selector(WebViewController.openLocationPress(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.isAlternate = true item.target = wvc item.tag = 3 subOpen.addItem(item) item = NSMenuItem(title: "New Window", action: #selector(appDelegate.newDocument(_:)), keyEquivalent: "") item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.target = appDelegate item.isAlternate = true item.tag = 1 subOpen.addItem(item) item = NSMenuItem(title: "Playlists", action: #selector(AppDelegate.presentPlaylistSheet(_:)), keyEquivalent: "") item.representedObject = self.window item.target = appDelegate menu.addItem(item) item = NSMenuItem(title: "Appearance", action: #selector(menuClicked(_:)), keyEquivalent: "") menu.addItem(item) let subPref = NSMenu() item.submenu = subPref item = NSMenuItem(title: "Auto-hide Title Bar", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subAuto = NSMenu() item.submenu = subAuto item = NSMenuItem(title: "Never", action: #selector(hpc.autoHideTitlePress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.AutoHideTitlePreference.never.rawValue item.state = autoHideTitle == .never ? .on : .off item.target = hpc subAuto.addItem(item) item = NSMenuItem(title: "Outside", action: #selector(hpc.autoHideTitlePress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.AutoHideTitlePreference.outside.rawValue item.state = autoHideTitle == .outside ? .on : .off item.target = hpc subAuto.addItem(item) item = NSMenuItem(title: "Float Above", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subFloat = NSMenu() item.submenu = subFloat item = NSMenuItem(title: "All Spaces Disabled", action: #selector(hpc.floatOverAllSpacesPress), keyEquivalent: "") item.state = settings.floatAboveAllPreference.value.contains(.disabled) ? .on : .off item.target = hpc subFloat.addItem(item) item = NSMenuItem(title: "Full Screen", action: #selector(hpc.floatOverFullScreenAppsPress(_:)), keyEquivalent: "") item.state = settings.floatAboveAllPreference.value.contains(.screen) ? .on : .off item.target = hpc subFloat.addItem(item) item = NSMenuItem(title: "User Agent", action: #selector(wvc.userAgentPress(_:)), keyEquivalent: "") item.target = wvc subPref.addItem(item) item = NSMenuItem(title: "Translucency", action: #selector(menuClicked(_:)), keyEquivalent: "") subPref.addItem(item) let subTranslucency = NSMenu() item.submenu = subTranslucency item = NSMenuItem(title: "Opacity", action: #selector(menuClicked(_:)), keyEquivalent: "") let opacity = settings.opacityPercentage.value subTranslucency.addItem(item) let subOpacity = NSMenu() item.submenu = subOpacity item = NSMenuItem(title: "10%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (10 == opacity ? .on : .off) item.target = hpc item.tag = 10 subOpacity.addItem(item) item = NSMenuItem(title: "20%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.isEnabled = translucency.rawValue > 0 item.state = (20 == opacity ? .on : .off) item.target = hpc item.tag = 20 subOpacity.addItem(item) item = NSMenuItem(title: "30%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (30 == opacity ? .on : .off) item.target = hpc item.tag = 30 subOpacity.addItem(item) item = NSMenuItem(title: "40%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (40 == opacity ? .on : .off) item.target = hpc item.tag = 40 subOpacity.addItem(item) item = NSMenuItem(title: "50%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (50 == opacity ? .on : .off) item.target = hpc item.tag = 50 subOpacity.addItem(item) item = NSMenuItem(title: "60%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (60 == opacity ? .on : .off) item.target = hpc item.tag = 60 subOpacity.addItem(item) item = NSMenuItem(title: "70%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (70 == opacity ? .on : .off) item.target = hpc item.tag = 70 subOpacity.addItem(item) item = NSMenuItem(title: "80%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (80 == opacity ? .on : .off) item.target = hpc item.tag = 80 subOpacity.addItem(item) item = NSMenuItem(title: "90%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (90 == opacity ? .on : .off) item.target = hpc item.tag = 90 subOpacity.addItem(item) item = NSMenuItem(title: "100%", action: #selector(hpc.percentagePress(_:)), keyEquivalent: "") item.state = (100 == opacity ? .on : .off) item.target = hpc item.tag = 100 subOpacity.addItem(item) item = NSMenuItem(title: "Never", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.never.rawValue item.state = translucency == .never ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Always", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.always.rawValue item.state = translucency == .always ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Mouse Over", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.mouseOver.rawValue item.state = translucency == .mouseOver ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Mouse Outside", action: #selector(hpc.translucencyPress(_:)), keyEquivalent: "") item.tag = HeliumPanelController.TranslucencyPreference.mouseOutside.rawValue item.state = translucency == .mouseOutside ? .on : .off item.target = hpc subTranslucency.addItem(item) item = NSMenuItem(title: "Save", action: #selector(hpc.saveDocument(_:)), keyEquivalent: "") item.representedObject = self.window item.target = hpc menu.addItem(item) item = NSMenuItem(title: "Search…", action: #selector(WebViewController.openSearchPress(_:)), keyEquivalent: "") item.representedObject = self.window item.target = wvc menu.addItem(item) item = NSMenuItem(title: "Close", action: #selector(HeliumPanel.performClose(_:)), keyEquivalent: "") item.target = hpc.window menu.addItem(item) menu.addItem(NSMenuItem.separator()) item = NSMenuItem(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "") item.target = NSApp menu.addItem(item) } @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool{ switch menuItem.title { default: return true } } } extension NSView { func fit(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true } func center(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true self.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true } func vCenter(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true } func top(_ parentView: NSView) { self.translatesAutoresizingMaskIntoConstraints = false self.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } } class WebViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, NSMenuDelegate, NSTabViewDelegate, WKHTTPCookieStoreObserver { @available(OSX 10.13, *) public func cookiesDidChange(in cookieStore: WKHTTPCookieStore) { DispatchQueue.main.async { cookieStore.getAllCookies { cookies in // Process cookies } } } var defaults = UserDefaults.standard var document : Document? { get { if let document : Document = self.view.window?.windowController?.document as? Document { return document } return nil } } var heliumPanelController : HeliumPanelController? { get { guard let hpc : HeliumPanelController = self.view.window?.windowController as? HeliumPanelController else { return nil } return hpc } } var trackingTag: NSView.TrackingRectTag? { get { return (self.webView.window?.windowController as? HeliumPanelController)?.viewTrackingTag } set (value) { (self.webView.window?.windowController as? HeliumPanelController)?.viewTrackingTag = value } } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() webView.becomeFirstResponder() NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.loadURL(urlFileURL:)), name: NSNotification.Name(rawValue: "HeliumLoadURL"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.loadURL(urlString:)), name: NSNotification.Name(rawValue: "HeliumLoadURLString"), object: nil)/* NotificationCenter.default.addObserver( self, selector: #selector(wkFlippedView(_:)), name: NSNotification.Name(rawValue: "WKFlippedView"), object: nil) // We want to be notified when a player is added let originalDidAddSubviewMethod = class_getInstanceMethod(NSView.self, #selector(NSView.didAddSubview(_:))) let originalDidAddSubviewImplementation = method_getImplementation(originalDidAddSubviewMethod!) typealias DidAddSubviewCFunction = @convention(c) (AnyObject, Selector, NSView) -> Void let castedOriginalDidAddSubviewImplementation = unsafeBitCast(originalDidAddSubviewImplementation, to: DidAddSubviewCFunction.self) let newDidAddSubviewImplementationBlock: @convention(block) (AnyObject?, NSView) -> Void = { (view: AnyObject!, subview: NSView) -> Void in castedOriginalDidAddSubviewImplementation(view, Selector(("didAddsubview:")), subview) // Swift.print("view: \(subview.className)") if subview.className == "WKFlippedView" { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WKFlippedView"), object: subview) } } let newDidAddSubviewImplementation = imp_implementationWithBlock(unsafeBitCast(newDidAddSubviewImplementationBlock, to: AnyObject.self)) method_setImplementation(originalDidAddSubviewMethod!, newDidAddSubviewImplementation) } @objc func wkFlippedView(_ note: NSNotification) { print("A Player \(String(describing: note.object)) will be opened now") guard let view = note.object as? NSView, let scrollView = view.enclosingScrollView else { return } if scrollView.hasHorizontalScroller { scrollView.horizontalScroller?.isHidden = true } if scrollView.hasVerticalScroller { scrollView.verticalScroller?.isHidden = true } } func scrollView(_ note: NSNotification) { print("Scroll View \(String(describing: note.object)) will be opened now") if let scrollView : NSScrollView = note.object as? NSScrollView { scrollView.autohidesScrollers = true }*/ } override func viewDidAppear() { guard let doc = self.document, doc.docType == .helium else { return } // https://stackoverflow.com/questions/32056874/programmatically-wkwebview-inside-an-uiview-with-auto-layout // the autolayout is complete only when the view has appeared. if self.webView != nil { setupWebView() } // Final panel updates, called by view, when document is available if let hpc = self.heliumPanelController { hpc.documentDidLoad() } // load developer panel if asked - initially no self.webView?.configuration.preferences.setValue(UserSettings.DeveloperExtrasEnabled.value, forKey: "developerExtrasEnabled") } fileprivate func setupWebView() { webView.autoresizingMask = [NSView.AutoresizingMask.height, NSView.AutoresizingMask.width] if webView.constraints.count == 0 { webView.fit(webView.superview!) } // Allow plug-ins such as silverlight webView.configuration.preferences.plugInsEnabled = true // Custom user agent string for Netflix HTML5 support webView.customUserAgent = UserSettings.UserAgent.value // Allow zooming webView.allowsMagnification = true // Alow back and forth webView.allowsBackForwardNavigationGestures = true // Allow look ahead views webView.allowsLinkPreview = true // ditch loading indicator background loadingIndicator.appearance = NSAppearance.init(named: NSAppearance.Name.aqua) // Fetch, synchronize and observe data store for cookie changes if #available(OSX 10.13, *) { let websiteDataStore = WKWebsiteDataStore.nonPersistent() let configuration = webView.configuration configuration.websiteDataStore = websiteDataStore configuration.processPool = WKProcessPool() let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]() cookies.forEach({ configuration.websiteDataStore.httpCookieStore.setCookie($0, completionHandler: nil) }) WKWebsiteDataStore.default().httpCookieStore.add(self) } // Listen for load progress webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) observing = true // Watch command key changes NotificationCenter.default.addObserver( self, selector: #selector(WebViewController.commandKeyDown(_:)), name: NSNotification.Name(rawValue: "commandKeyDown"), object: nil) // Intercept drags webView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0)}) webView.registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL]) webView.registerForDraggedTypes(Array(webView.acceptableTypes)) // Watch javascript selection messages unless already done let controller = webView.configuration.userContentController if controller.userScripts.count > 0 { return } controller.add(self, name: "newWindowWithUrlDetected") controller.add(self, name: "newSelectionDetected") controller.add(self, name: "newUrlDetected") let js = NSString.string(fromAsset: "Helium-js") let script = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true) controller.addUserScript(script) // make http: -> https: guarded by preference if #available(OSX 10.13, *), UserSettings.PromoteHTTPS.value { // https://developer.apple.com/videos/play/wwdc2017/220/ 21:04 let jsonString = """ [{ "trigger" : { "url-filter" : ".*" }, "action" : { "type" : "make-https" } }] """ WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "httpRuleList", encodedContentRuleList: jsonString, completionHandler: {(list, error) in guard let contentRuleList = list else { return } self.webView.configuration.userContentController.add(contentRuleList) }) } } var appDelegate: AppDelegate = NSApp.delegate as! AppDelegate @objc dynamic var observing : Bool = false func setupTrackingAreas(_ establish: Bool) { if let tag = trackingTag { view.removeTrackingRect(tag) trackingTag = nil } if establish { trackingTag = view.addTrackingRect(view.bounds, owner: self, userData: nil, assumeInside: false) } webView.updateTrackingAreas() } override func viewDidLayout() { super.viewDidLayout() // ditch horizonatal scroll when not over if let scrollView = self.webView.enclosingScrollView { if scrollView.hasHorizontalScroller { scrollView.horizontalScroller?.isHidden = true } if scrollView.hasVerticalScroller { scrollView.verticalScroller?.isHidden = true } } setupTrackingAreas(true) } override func viewWillDisappear() { guard let wc = self.view.window?.windowController, !wc.isKind(of: ReleasePanelController.self) else { return } let navDelegate = webView.navigationDelegate as! NSObject // Wind down all observations if observing { webView.removeObserver(navDelegate, forKeyPath: "estimatedProgress") webView.removeObserver(navDelegate, forKeyPath: "title") observing = false } } // MARK: Actions @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool{ switch menuItem.title { case "Developer Extras": guard let state = webView.configuration.preferences.value(forKey: "developerExtrasEnabled") else { return false } menuItem.state = (state as? NSNumber)?.boolValue == true ? .on : .off return true case "Back": return webView.canGoBack case "Forward": return webView.canGoForward default: return true } } @objc @IBAction func backPress(_ sender: AnyObject) { webView.goBack() } @objc @IBAction func forwardPress(_ sender: AnyObject) { webView.goForward() } @objc internal func commandKeyDown(_ notification : Notification) { let commandKeyDown : NSNumber = notification.object as! NSNumber if let window = self.view.window { window.isMovableByWindowBackground = commandKeyDown.boolValue // Swift.print(String(format: "CMND %@", commandKeyDown.boolValue ? "v" : "^")) } } fileprivate func zoomIn() { webView.magnification += 0.1 } fileprivate func zoomOut() { webView.magnification -= 0.1 } fileprivate func resetZoom() { webView.magnification = 1 } @objc @IBAction func developerExtrasEnabledPress(_ sender: NSMenuItem) { self.webView?.configuration.preferences.setValue((sender.state != .on), forKey: "developerExtrasEnabled") } @objc @IBAction func openFilePress(_ sender: AnyObject) { var viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window let open = NSOpenPanel() open.allowsMultipleSelection = true open.canChooseDirectories = false open.resolvesAliases = true open.canChooseFiles = true // Have window, but make it active NSApp.activate(ignoringOtherApps: true) open.worksWhenModal = true open.beginSheetModal(for: window!, completionHandler: { (response: NSApplication.ModalResponse) in if response == NSApplication.ModalResponse.OK { var parent : NSWindow? = window var latest : Document? let urls = open.urls for url in urls { if viewOptions.contains(.t_view) { latest = self.appDelegate.openURLInNewWindow(url, attachTo: parent) } else if viewOptions.contains(.w_view) { latest = self.appDelegate.openURLInNewWindow(url) } else { self.webView.next(url: url) } // Multiple files implies new windows if latest != nil { parent = latest?.windowControllers.first?.window } viewOptions.insert(.w_view) } } }) } @objc @IBAction func openLocationPress(_ sender: AnyObject) { let viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window var urlString = currentURL if let rawString = NSPasteboard.general.string(forType: NSPasteboard.PasteboardType.string), rawString.isValidURL() { urlString = rawString } appDelegate.didRequestUserUrl(RequestUserStrings ( currentURL: urlString, alertMessageText: "URL to load", alertButton1stText: "Load", alertButton1stInfo: nil, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "Home", alertButton3rdInfo: UserSettings.HomePageURL.value), onWindow: window as? HeliumPanel, title: "Enter URL", acceptHandler: { (urlString: String) in guard let newURL = URL.init(string: urlString) else { return } if viewOptions.contains(.t_view) { _ = self.appDelegate.openURLInNewWindow(newURL, attachTo: window) } else if viewOptions.contains(.w_view) { _ = self.appDelegate.openURLInNewWindow(newURL) } else { self.loadURL(url: newURL) } }) } @objc @IBAction func openSearchPress(_ sender: AnyObject) { let viewOptions = ViewOptions(rawValue: sender.tag) let window = self.view.window let name = k.searchNames[ UserSettings.Search.value ] let info = k.searchInfos[ UserSettings.Search.value ] appDelegate.didRequestSearch(RequestUserStrings ( currentURL: nil, alertMessageText: "Search", alertButton1stText: name, alertButton1stInfo: info, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "New Window", alertButton3rdInfo: "Results in new window"), onWindow: self.view.window as? HeliumPanel, title: "Web Search", acceptHandler: { (newWindow: Bool, searchURL: URL) in if viewOptions.contains(.t_view) { _ = self.appDelegate.openURLInNewWindow(searchURL, attachTo: window) } else if viewOptions.contains(.w_view) { _ = self.appDelegate.openURLInNewWindow(searchURL) } else { self.loadURL(url: searchURL) } }) } @objc @IBAction fileprivate func reloadPress(_ sender: AnyObject) { requestedReload() } @objc @IBAction fileprivate func clearPress(_ sender: AnyObject) { clear() } @objc @IBAction fileprivate func resetZoomLevel(_ sender: AnyObject) { resetZoom() } @objc @IBAction func userAgentPress(_ sender: AnyObject) { appDelegate.didRequestUserAgent(RequestUserStrings ( currentURL: webView.customUserAgent, alertMessageText: "Custom user agent", alertButton1stText: "Set", alertButton1stInfo: nil, alertButton2ndText: "Cancel", alertButton2ndInfo: nil, alertButton3rdText: "Default", alertButton3rdInfo: UserSettings.UserAgent.default), onWindow: NSApp.keyWindow as? HeliumPanel, title: "Custom User Agent", acceptHandler: { (newUserAgent: String) in self.webView.customUserAgent = newUserAgent } ) } @objc @IBAction fileprivate func zoomIn(_ sender: AnyObject) { zoomIn() } @objc @IBAction fileprivate func zoomOut(_ sender: AnyObject) { zoomOut() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: Loading internal var currentURL: String? { return webView.url?.absoluteString } internal func loadURL(text: String) { let text = UrlHelpers.ensureScheme(text) if let url = URL(string: text) { webView.load(URLRequest.init(url: url)) } } internal func loadURL(url: URL) { webView.next(url: url) } @objc internal func loadURL(urlFileURL: Notification) { if let fileURL = urlFileURL.object, let userInfo = urlFileURL.userInfo { if userInfo["hwc"] as? NSWindowController == self.view.window?.windowController { loadURL(url: fileURL as! URL) } else { // load new window with URL loadURL(url: urlFileURL.object as! URL) } } } @objc func loadURL(urlString: Notification) { if let userInfo = urlString.userInfo { if userInfo["hwc"] as? NSWindowController != self.view.window?.windowController { return } } if let string = urlString.object as? String { _ = loadURL(text: string) } } func loadAttributes(dict: Dictionary<String,Any>) { Swift.print("loadAttributes: dict \(dict)") } func loadAttributes(item: PlayItem) { loadAttributes(dict: item.dictionary()) } // TODO: For now just log what we would play once we figure out how to determine when an item finishes so we can start the next @objc func playerDidFinishPlaying(_ note: Notification) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: note.object) print("Video Finished") } fileprivate func requestedReload() { webView.reload() } // MARK: Javascript func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //Swift.print("userContentController") switch message.name { case "newWindowWithUrlDetected": if let url = URL.init(string: message.body as! String) { webView.selectedURL = url //Swift.print("ucc: new -> \(url.absoluteString)") } break case "newSelectionDetected": if let urlString : String = message.body as? String { webView.selectedText = urlString //Swift.print("ucc: str -> \(urlString)") } break case "newUrlDetected": if let url = URL.init(string: message.body as! String) { webView.selectedURL = url //Swift.print("ucc: url -> \(url.absoluteString)") } break default: Swift.print("ucc: unknown \(message.name)") } } // MARK: Webview functions func clear() { // Reload to home page (or default if no URL stored in UserDefaults) guard self.document?.docType == .helium, let url = URL.init(string: UserSettings.HomePageURL.value) else { return } webView.load(URLRequest.init(url: url)) } @objc @IBOutlet var webView: MyWebView! var webSize = CGSize(width: 0,height: 0) @objc @IBOutlet weak var borderView: WebBorderView! @objc @IBOutlet weak var loadingIndicator: NSProgressIndicator! override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let mwv = object as? MyWebView, mwv == self.webView else { return } // We *must* have a key path guard let keyPath = keyPath else { return } switch keyPath { case "estimatedProgress": if let progress = change?[NSKeyValueChangeKey(rawValue: "new")] as? Float { let percent = progress * 100 var title = String(format: "Loading... %.2f%%", percent) if percent == 100, let url = (self.webView.url) { // Initial recording for this url session let notif = Notification(name: Notification.Name(rawValue: "HeliumNewURL"), object: url, userInfo: [k.fini : false, k.view : self.webView as Any]) NotificationCenter.default.post(notif) // once loaded update window title,size with video name,dimension if let toolTip = (mwv.url?.absoluteString) { title = url.isFileURL ? url.lastPathComponent : (url.path != "/" ? url.lastPathComponent : url.host) ?? toolTip self.heliumPanelController?.hoverBar?.superview?.toolTip = toolTip if let track = AVURLAsset(url: url, options: nil).tracks.first { // if it's a video file, get and set window content size to its dimentions if track.mediaType == AVMediaType.video { webSize = track.naturalSize // Try to adjust initial size if possible let os = appDelegate.os switch (os.majorVersion, os.minorVersion, os.patchVersion) { case (10, 10, _), (10, 11, _), (10, 12, _): if let oldSize = mwv.window?.contentView?.bounds.size, oldSize != webSize, var origin = mwv.window?.frame.origin, let theme = self.view.window?.contentView?.superview { var iterator = theme.constraints.makeIterator() Swift.print(String(format:"view:%p webView:%p", mwv.superview!, mwv)) while let constraint = iterator.next() { Swift.print("\(constraint.priority) \(constraint)") } origin.y += (oldSize.height - webSize.height) mwv.window?.setContentSize(webSize) mwv.window?.setFrameOrigin(origin) mwv.bounds.size = webSize } break default: // Issue still to be resolved so leave as-is for now Swift.print("os \(os)") if webSize != webView.fittingSize { webView.bounds.size = webView.fittingSize webSize = webView.bounds.size } } } // Wait for URL to finish let videoPlayer = AVPlayer(url: url) let item = videoPlayer.currentItem NotificationCenter.default.addObserver(self, selector: #selector(WebViewController.playerDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main, using: { (_) in DispatchQueue.main.async { Swift.print("restarting #1") videoPlayer.seek(to: CMTime.zero) videoPlayer.play() } }) NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item, queue: .main, using: { (_) in DispatchQueue.main.async { Swift.print("restarting #2") videoPlayer.seek(to: CMTime.zero) videoPlayer.play() } }) } else { restoreSettings(url.absoluteString) } } else { title = appDelegate.appName } self.view.window?.title = title // Remember for later restoration if let doc = self.document, let hpc = doc.heliumPanelController { self.view.window?.representedURL = url hpc.updateTitleBar(didChange: false) NSApp.addWindowsItem(self.view.window!, title: url.lastPathComponent, filename: false) } } } break case "loading": guard let loading = change?[NSKeyValueChangeKey(rawValue: "new")] as? Bool, loading == loadingIndicator.isHidden else { return } Swift.print("loading: \(loading ? "YES" : "NO")") break; case "title": title = mwv.title break; default: Swift.print("Unknown observing keyPath \(String(describing: keyPath))") } } fileprivate func restoreSettings(_ title: String) { guard let dict = defaults.dictionary(forKey: title), let doc = self.document, let hpc = doc.heliumPanelController else { return } doc.restoreSettings(with: dict) hpc.documentDidLoad() } //Convert a YouTube video url that starts at a certian point to popup/embedded design // (i.e. ...?t=1m2s --> ?start=62) func makeCustomStartTimeURL(_ url: String) -> String { let startTime = "?t=" let idx = url.indexOf(startTime) if idx == -1 { return url } else { let timeIdx = idx.advanced(by: 3) let hmsString = url[timeIdx...].replacingOccurrences(of: "h", with: ":").replacingOccurrences(of: "m", with: ":").replacingOccurrences(of: "s", with: ":") var returnURL = url var final = 0 let hms = hmsString.components(separatedBy: ":") if hms.count > 2, let hrs = Int(hms[2]) { final += 3600 * hrs } if hms.count > 1, let mins = Int(hms[1]) { final += 60 * mins } if hms.count > 0, let secs = Int(hms[0]) { final += secs } returnURL.removeSubrange(returnURL.index(returnURL.startIndex, offsetBy: idx+1) ..< returnURL.endIndex) returnURL = "?start=" returnURL = returnURL + String(final) return returnURL } } //Helper function to return the hash of the video for encoding a popout video that has a start time code. fileprivate func getVideoHash(_ url: String) -> String { let startOfHash = url.indexOf(".be/") let endOfHash = startOfHash.advanced(by: 4) let restOfUrl = url.indexOf("?t") let hash = url[url.index(url.startIndex, offsetBy: endOfHash) ..< (endOfHash == -1 ? url.endIndex : url.index(url.startIndex, offsetBy: restOfUrl))] return String(hash) } /* func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { let alertController = NSAlertController(title: nil, message: message, preferredStyle: .ActionSheet) alertController.addAction(NSAlertAction(title: "Ok", style: .Default, handler: { (action) in completionHandler() })) self.presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { let alertController = AlertController(title: nil, message: message, preferredStyle: .ActionSheet) alertController.addAction(AlertAction(title: "Ok", style: .Default, handler: { (action) in completionHandler(true) })) alertController.addAction(AlertAction(title: "Cancel", style: .Default, handler: { (action) in completionHandler(false) })) self.presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) { let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .ActionSheet) alertController.addTextFieldWithConfigurationHandler { (textField) in textField.text = defaultText } alertController.addAction(AlertAction(title: "Ok", style: .Default, handler: { (action) in if let text = alertController.textFields?.first?.text { completionHandler(text) } else { completionHandler(defaultText) } })) alertController.addAction(AlertAction(title: "Cancel", style: .Default, handler: { (action) in completionHandler(nil) })) self.presentViewController(alertController, animated: true, completion: nil) } */ // MARK: Navigation Delegate // Redirect Hulu and YouTube to pop-out videos func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let viewOptions = appDelegate.getViewOptions var url = navigationAction.request.url! guard navigationAction.buttonNumber < 2 else { Swift.print("newWindow with url:\(String(describing: url))") if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(url, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(url) } decisionHandler(WKNavigationActionPolicy.cancel) return } guard !UserSettings.DisabledMagicURLs.value else { if let selectedURL = (webView as! MyWebView).selectedURL { url = selectedURL } if navigationAction.buttonNumber > 1 { if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(url, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(url) } decisionHandler(WKNavigationActionPolicy.cancel) } else { decisionHandler(WKNavigationActionPolicy.allow) } return } if let newUrl = UrlHelpers.doMagic(url), newUrl != url { decisionHandler(WKNavigationActionPolicy.cancel) if let selectedURL = (webView as! MyWebView).selectedURL { url = selectedURL } if navigationAction.buttonNumber > 1 { if viewOptions.contains(.t_view) { _ = appDelegate.openURLInNewWindow(newUrl, attachTo: webView.window ) } else { _ = appDelegate.openURLInNewWindow(newUrl) } } else { loadURL(url: newUrl) } } else { decisionHandler(WKNavigationActionPolicy.allow) } } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { guard let response = navigationResponse.response as? HTTPURLResponse, let url = navigationResponse.response.url else { decisionHandler(.allow) return } // load cookies if #available(OSX 10.13, *) { if let headerFields = response.allHeaderFields as? [String:String] { Swift.print("\(url.absoluteString) allHeaderFields:\n\(headerFields)") let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url) cookies.forEach({ cookie in webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: nil) }) } } decisionHandler(.allow) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { Swift.print("didStartProvisionalNavigation - 1st") } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { Swift.print("didCommit - 2nd") } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { handleError(error) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { handleError(error) } fileprivate func handleError(_ error: Error) { let message = error.localizedDescription Swift.print("didFail?: \((error as NSError).code): \(message)") if (error as NSError).code >= 400 { NSApp.presentError(error) } else if (error as NSError).code < 0 { if let info = error._userInfo as? [String: Any] { if let url = info["NSErrorFailingURLKey"] as? URL { appDelegate.userAlertMessage(message, info: url.absoluteString) } else if let urlString = info["NSErrorFailingURLStringKey"] as? String { appDelegate.userAlertMessage(message, info: urlString) } } } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) { let doc = self.document let hpc = doc?.heliumPanelController guard let url = webView.url else { return } // Restore setting not done by document controller if let hpc = hpc { hpc.documentDidLoad() } // Finish recording of for this url session let notif = Notification(name: Notification.Name(rawValue: "HeliumNewURL"), object: url, userInfo: [k.fini : true]) NotificationCenter.default.post(notif) Swift.print("webView:didFinish navigation: '\(String(describing: webView.title))' => \(url.absoluteString) - last") /* let html = """ <html> <body> <h1>Hello, Swift!</h1> </body> </html> """ webView.loadHTMLString(html, baseURL: nil)*/ } func webView(_ webView: WKWebView, didFinishLoad navigation: WKNavigation) { guard let title = webView.title, let urlString : String = webView.url?.absoluteString else { return } Swift.print("webView:didFinishLoad: '\(title)' => \(urlString)") } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let serverTrust = challenge.protectionSpace.serverTrust else { return completionHandler(.useCredential, nil) } let exceptions = SecTrustCopyExceptions(serverTrust) SecTrustSetExceptions(serverTrust, exceptions) completionHandler(.useCredential, URLCredential(trust: serverTrust)) } // MARK: UI Delegate func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { _ = appDelegate.openURLInNewWindow(navigationAction.request.url!) return nil } // We really want to use the supplied config, so use custom setup var newWebView : WKWebView? Swift.print("createWebViewWith") if let newURL = navigationAction.request.url { do { let doc = try NSDocumentController.shared.makeDocument(withContentsOf: newURL, ofType: k.Custom) if let hpc = doc.windowControllers.first as? HeliumPanelController, let window = hpc.window { let newView = MyWebView.init(frame: webView.frame, configuration: configuration) let contentView = window.contentView! let wvc = hpc.webViewController hpc.webViewController.webView = newView contentView.addSubview(newView) hpc.webViewController.loadURL(text: newURL.absoluteString) newView.navigationDelegate = wvc newView.uiDelegate = wvc newWebView = hpc.webView wvc.viewDidLoad() // Setups all done, make us visible doc.showWindows() } } catch let error { NSApp.presentError(error) } } return newWebView } func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) { Swift.print("runOpenPanelWith") } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { Swift.print("runJavaScriptAlertPanelWithMessage") } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { Swift.print("runJavaScriptConfirmPanelWithMessage") } func webViewDidClose(_ webView: WKWebView) { Swift.print("webViewDidClose") } // MARK: TabView Delegate func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { if let item = tabViewItem { Swift.print("willSelect: label: \(item.label) ident: \(String(describing: item.identifier))") } } func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { if let item = tabViewItem { Swift.print("didSelect: label: \(item.label) ident: \(String(describing: item.identifier))") } } } class ReleaseViewController : WebViewController { }
// // ViewController.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // import Cocoa import WebKit class WebViewController: NSViewController, WKNavigationDelegate { var trackingTag: NSTrackingRectTag? // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WebViewController.loadURLObject(_:)), name: "HeliumLoadURL", object: nil) // Layout webview view.addSubview(webView) webView.frame = view.bounds webView.autoresizingMask = [NSAutoresizingMaskOptions.ViewHeightSizable, NSAutoresizingMaskOptions.ViewWidthSizable] // Allow plug-ins such as silverlight webView.configuration.preferences.plugInsEnabled = true // Custom user agent string for Netflix HTML5 support webView._customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17" // Setup magic URLs webView.navigationDelegate = self // Allow zooming webView.allowsMagnification = true // Alow back and forth webView.allowsBackForwardNavigationGestures = true // Listen for load progress webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil) clear() } override func viewDidLayout() { super.viewDidLayout() if let tag = trackingTag { view.removeTrackingRect(tag) } trackingTag = view.addTrackingRect(view.bounds, owner: self, userData: nil, assumeInside: false) } // MARK: Actions override func validateMenuItem(menuItem: NSMenuItem) -> Bool{ switch menuItem.title { case "Back": return webView.canGoBack case "Forward": return webView.canGoForward default: return true } } @IBAction func backPress(sender: AnyObject) { webView.goBack() } @IBAction func forwardPress(sender: AnyObject) { webView.goForward() } private func zoomIn() { webView.magnification += 0.1 } private func zoomOut() { webView.magnification -= 0.1 } private func resetZoom() { webView.magnification = 1 } @IBAction private func reloadPress(sender: AnyObject) { requestedReload() } @IBAction private func clearPress(sender: AnyObject) { clear() } @IBAction private func resetZoomLevel(sender: AnyObject) { resetZoom() } @IBAction private func zoomIn(sender: AnyObject) { zoomIn() } @IBAction private func zoomOut(sender: AnyObject) { zoomOut() } internal func loadAlmostURL(text: String) { var text = text if !(text.lowercaseString.hasPrefix("http://") || text.lowercaseString.hasPrefix("https://")) { text = "http://" + text } if let url = NSURL(string: text) { loadURL(url) } } // MARK: Loading internal func loadURL(url:NSURL) { webView.loadRequest(NSURLRequest(URL: url)) } func loadURLObject(urlObject : NSNotification) { if let url = urlObject.object as? NSURL { loadAlmostURL(url.absoluteString); } } private func requestedReload() { webView.reload() } // MARK: Webview functions func clear() { // Reload to home page (or default if no URL stored in UserDefaults) if let homePage = NSUserDefaults.standardUserDefaults().stringForKey(UserSetting.HomePageURL.userDefaultsKey) { loadAlmostURL(homePage) } else{ loadURL(NSURL(string: "https://cdn.rawgit.com/JadenGeller/Helium/master/helium_start.html")!) } } var webView = WKWebView() var shouldRedirect: Bool { get { return !NSUserDefaults.standardUserDefaults().boolForKey(UserSetting.DisabledMagicURLs.userDefaultsKey) } } // Redirect Hulu and YouTube to pop-out videos func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if shouldRedirect, let url = navigationAction.request.URL { let urlString = url.absoluteString var modified = urlString modified = modified.replacePrefix("https://www.youtube.com/watch?v=", replacement: modified.containsString("list") ? "https://www.youtube.com/embed/?v=" : "https://www.youtube.com/embed/") modified = modified.replacePrefix("https://vimeo.com/", replacement: "http://player.vimeo.com/video/") modified = modified.replacePrefix("http://v.youku.com/v_show/id_", replacement: "http://player.youku.com/embed/") modified = modified.replacePrefix("https://www.twitch.tv/", replacement: "https://player.twitch.tv?html5&channel=") modified = modified.replacePrefix("http://www.dailymotion.com/video/", replacement: "http://www.dailymotion.com/embed/video/") modified = modified.replacePrefix("http://dai.ly/", replacement: "http://www.dailymotion.com/embed/video/") if modified.containsString("https://youtu.be") { modified = "https://www.youtube.com/embed/" + getVideoHash(urlString) if urlString.containsString("?t=") { modified += makeCustomStartTimeURL(urlString) } } if urlString != modified { decisionHandler(WKNavigationActionPolicy.Cancel) loadURL(NSURL(string: modified)!) return } } decisionHandler(WKNavigationActionPolicy.Allow) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation) { if let pageTitle = webView.title { var title = pageTitle; if title.isEmpty { title = "Helium" } let notif = NSNotification(name: "HeliumUpdateTitle", object: title); NSNotificationCenter.defaultCenter().postNotification(notif) } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if object as! NSObject == webView && keyPath == "estimatedProgress" { if let progress = change?["new"] as? Float { let percent = progress * 100 var title = NSString(format: "Loading... %.2f%%", percent) if percent == 100 { title = "Helium" } let notif = NSNotification(name: "HeliumUpdateTitle", object: title); NSNotificationCenter.defaultCenter().postNotification(notif) } } } //Convert a YouTube video url that starts at a certian point to popup/embedded design // (i.e. ...?t=1m2s --> ?start=62) private func makeCustomStartTimeURL(url: String) -> String { let startTime = "?t=" let idx = url.indexOf(startTime) if idx == -1 { return url } else { var returnURL = url let timing = url.substringFromIndex(url.startIndex.advancedBy(idx+3)) let hoursDigits = timing.indexOf("h") var minutesDigits = timing.indexOf("m") let secondsDigits = timing.indexOf("s") returnURL.removeRange(returnURL.startIndex.advancedBy(idx+1) ..< returnURL.endIndex) returnURL = "?start=" //If there are no h/m/s params and only seconds (i.e. ...?t=89) if (hoursDigits == -1 && minutesDigits == -1 && secondsDigits == -1) { let onlySeconds = url.substringFromIndex(url.startIndex.advancedBy(idx+3)) returnURL = returnURL + onlySeconds return returnURL } //Do check to see if there is an hours parameter. var hours = 0 if (hoursDigits != -1) { hours = Int(timing.substringToIndex(timing.startIndex.advancedBy(hoursDigits)))! } //Do check to see if there is a minutes parameter. var minutes = 0 if (minutesDigits != -1) { minutes = Int(timing.substringWithRange(timing.startIndex.advancedBy(hoursDigits+1) ..< timing.startIndex.advancedBy(minutesDigits)))! } if minutesDigits == -1 { minutesDigits = hoursDigits } //Do check to see if there is a seconds parameter. var seconds = 0 if (secondsDigits != -1) { seconds = Int(timing.substringWithRange(timing.startIndex.advancedBy(minutesDigits+1) ..< timing.startIndex.advancedBy(secondsDigits)))! } //Combine all to make seconds. let secondsFinal = 3600*hours + 60*minutes + seconds returnURL = returnURL + String(secondsFinal) return returnURL } } //Helper function to return the hash of the video for encoding a popout video that has a start time code. private func getVideoHash(url: String) -> String { let startOfHash = url.indexOf(".be/") let endOfHash = url.indexOf("?t") let hash = url.substringWithRange(url.startIndex.advancedBy(startOfHash+4) ..< (endOfHash == -1 ? url.endIndex : url.startIndex.advancedBy(endOfHash))) return hash } } added user controlled auto title hiding when enter, exiting // // WebViewController.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // import Cocoa import WebKit import AVFoundation class WebViewController: NSViewController, WKNavigationDelegate { var trackingTag: NSTrackingRectTag? // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WebViewController.loadURLObject(_:)), name: "HeliumLoadURL", object: nil) // Layout webview view.addSubview(webView) webView.frame = view.bounds webView.autoresizingMask = [NSAutoresizingMaskOptions.ViewHeightSizable, NSAutoresizingMaskOptions.ViewWidthSizable] // Allow plug-ins such as silverlight webView.configuration.preferences.plugInsEnabled = true // Custom user agent string for Netflix HTML5 support webView._customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17" // Setup magic URLs webView.navigationDelegate = self // Allow zooming webView.allowsMagnification = true // Alow back and forth webView.allowsBackForwardNavigationGestures = true // Listen for load progress webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil) // Listen for auto hide title changes NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "autoHideTitle", options: NSKeyValueObservingOptions.New, context: nil) clear() } var lastStyle : Int = 0 var lastTitle = "Helium" var autoHideTitle : Bool = NSUserDefaults.standardUserDefaults().boolForKey("autoHideTitle") override func mouseExited(theEvent: NSEvent) { if autoHideTitle { if lastStyle == 0 { lastStyle = (self.view.window?.styleMask)! } self.view.window!.titleVisibility = NSWindowTitleVisibility.Hidden; self.view.window?.styleMask = NSBorderlessWindowMask } } override func mouseEntered(theEvent: NSEvent) { if autoHideTitle { if lastStyle == 0 { lastStyle = (self.view.window?.styleMask)! } self.view.window!.titleVisibility = NSWindowTitleVisibility.Visible; self.view.window?.styleMask = lastStyle let notif = NSNotification(name: "HeliumUpdateTitle", object: lastTitle); NSNotificationCenter.defaultCenter().postNotification(notif) } } override func viewDidLayout() { super.viewDidLayout() if let tag = trackingTag { view.removeTrackingRect(tag) } trackingTag = view.addTrackingRect(view.bounds, owner: self, userData: nil, assumeInside: false) } // MARK: Actions override func validateMenuItem(menuItem: NSMenuItem) -> Bool{ switch menuItem.title { case "Back": return webView.canGoBack case "Forward": return webView.canGoForward default: return true } } @IBAction func backPress(sender: AnyObject) { webView.goBack() } @IBAction func forwardPress(sender: AnyObject) { webView.goForward() } private func zoomIn() { if !fileReferencedURL { webView.magnification += 0.1 } } private func zoomOut() { if !fileReferencedURL { webView.magnification -= 0.1 } } private func resetZoom() { if !fileReferencedURL { webView.magnification = 1 } } @IBAction private func reloadPress(sender: AnyObject) { requestedReload() } @IBAction private func clearPress(sender: AnyObject) { clear() } @IBAction private func resetZoomLevel(sender: AnyObject) { resetZoom() } @IBAction private func zoomIn(sender: AnyObject) { zoomIn() } @IBAction private func zoomOut(sender: AnyObject) { zoomOut() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } internal func loadAlmostURL( text_in: String) { var text = text_in if !(text.lowercaseString.hasPrefix("http://") || text.lowercaseString.hasPrefix("https://")) { text = "http://" + text } if let url = NSURL(string: text) { loadURL(url) } } // MARK: Loading internal func loadURL(url:NSURL) { webView.loadRequest(NSURLRequest(URL: url)) } func loadURLObject(urlObject : NSNotification) { if let url = urlObject.object as? NSURL { loadAlmostURL(url.absoluteString); } } private func requestedReload() { webView.reload() } // MARK: Webview functions func clear() { // Reload to home page (or default if no URL stored in UserDefaults) if let homePage = NSUserDefaults.standardUserDefaults().stringForKey(UserSetting.HomePageURL.userDefaultsKey) { loadAlmostURL(homePage) } else{ loadURL(NSURL(string: "https://cdn.rawgit.com/JadenGeller/Helium/master/helium_start.html")!) } } var webView = WKWebView() var shouldRedirect: Bool { get { return !NSUserDefaults.standardUserDefaults().boolForKey(UserSetting.DisabledMagicURLs.userDefaultsKey) } } // Redirect Hulu and YouTube to pop-out videos func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if shouldRedirect, let url = navigationAction.request.URL { let urlString = url.absoluteString var modified = urlString modified = modified.replacePrefix("https://www.youtube.com/watch?v=", replacement: modified.containsString("list") ? "https://www.youtube.com/embed/?v=" : "https://www.youtube.com/embed/") modified = modified.replacePrefix("https://vimeo.com/", replacement: "http://player.vimeo.com/video/") modified = modified.replacePrefix("http://v.youku.com/v_show/id_", replacement: "http://player.youku.com/embed/") modified = modified.replacePrefix("https://www.twitch.tv/", replacement: "https://player.twitch.tv?html5&channel=") modified = modified.replacePrefix("http://www.dailymotion.com/video/", replacement: "http://www.dailymotion.com/embed/video/") modified = modified.replacePrefix("http://dai.ly/", replacement: "http://www.dailymotion.com/embed/video/") if modified.containsString("https://youtu.be") { modified = "https://www.youtube.com/embed/" + getVideoHash(urlString) if urlString.containsString("?t=") { modified += makeCustomStartTimeURL(urlString) } } if urlString != modified { decisionHandler(WKNavigationActionPolicy.Cancel) loadURL(NSURL(string: modified)!) return } } decisionHandler(WKNavigationActionPolicy.Allow) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation) { if let pageTitle = webView.title { var title = pageTitle; if title.isEmpty { title = "Helium" } let notif = NSNotification(name: "HeliumUpdateTitle", object: title); NSNotificationCenter.defaultCenter().postNotification(notif) lastTitle = title } } var fileReferencedURL = false override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if object as! NSObject == webView && keyPath == "estimatedProgress" { if let progress = change?["new"] as? Float { let percent = progress * 100 var title = NSString(format: "Loading... %.2f%%", percent) if percent == 100 { // once loaded update window title,size with video name,dimension if ((self.webView.URL?.absoluteString) == nil) { title = "Helium" } else { let url = (self.webView.URL) if ((url?.isFileReferenceURL()) != nil) { title = url!.lastPathComponent! fileReferencedURL = true // if it's a video file, get and set window content size to its dimentions let track0 = AVURLAsset(URL:url!, options:nil).tracks[0] if track0.mediaType == AVMediaTypeVideo { webView.window?.setContentSize(track0.naturalSize) } } else { title = (url?.absoluteString)! fileReferencedURL = false } } lastTitle = title as String } let notif = NSNotification(name: "HeliumUpdateTitle", object: title); NSNotificationCenter.defaultCenter().postNotification(notif) } } if (keyPath == "autoHideTitle") { autoHideTitle = NSUserDefaults.standardUserDefaults().boolForKey("autoHideTitle") if autoHideTitle { if lastStyle == 0 { lastStyle = (self.view.window?.styleMask)! } self.view.window!.titleVisibility = NSWindowTitleVisibility.Hidden; self.view.window?.styleMask = NSBorderlessWindowMask } else { if lastStyle == 0 { lastStyle = (self.view.window?.styleMask)! } self.view.window!.titleVisibility = NSWindowTitleVisibility.Visible; self.view.window?.styleMask = lastStyle } let notif = NSNotification(name: "HeliumUpdateTitle", object: lastTitle); NSNotificationCenter.defaultCenter().postNotification(notif) } } //Convert a YouTube video url that starts at a certian point to popup/embedded design // (i.e. ...?t=1m2s --> ?start=62) private func makeCustomStartTimeURL(url: String) -> String { let startTime = "?t=" let idx = url.indexOf(startTime) if idx == -1 { return url } else { var returnURL = url let timing = url.substringFromIndex(url.startIndex.advancedBy(idx+3)) let hoursDigits = timing.indexOf("h") var minutesDigits = timing.indexOf("m") let secondsDigits = timing.indexOf("s") returnURL.removeRange(returnURL.startIndex.advancedBy(idx+1) ..< returnURL.endIndex) returnURL = "?start=" //If there are no h/m/s params and only seconds (i.e. ...?t=89) if (hoursDigits == -1 && minutesDigits == -1 && secondsDigits == -1) { let onlySeconds = url.substringFromIndex(url.startIndex.advancedBy(idx+3)) returnURL = returnURL + onlySeconds return returnURL } //Do check to see if there is an hours parameter. var hours = 0 if (hoursDigits != -1) { hours = Int(timing.substringToIndex(timing.startIndex.advancedBy(hoursDigits)))! } //Do check to see if there is a minutes parameter. var minutes = 0 if (minutesDigits != -1) { minutes = Int(timing.substringWithRange(timing.startIndex.advancedBy(hoursDigits+1) ..< timing.startIndex.advancedBy(minutesDigits)))! } if minutesDigits == -1 { minutesDigits = hoursDigits } //Do check to see if there is a seconds parameter. var seconds = 0 if (secondsDigits != -1) { seconds = Int(timing.substringWithRange(timing.startIndex.advancedBy(minutesDigits+1) ..< timing.startIndex.advancedBy(secondsDigits)))! } //Combine all to make seconds. let secondsFinal = 3600*hours + 60*minutes + seconds returnURL = returnURL + String(secondsFinal) return returnURL } } //Helper function to return the hash of the video for encoding a popout video that has a start time code. private func getVideoHash(url: String) -> String { let startOfHash = url.indexOf(".be/") let endOfHash = url.indexOf("?t") let hash = url.substringWithRange(url.startIndex.advancedBy(startOfHash+4) ..< (endOfHash == -1 ? url.endIndex : url.startIndex.advancedBy(endOfHash))) return hash } }
import UIKit import SwifteriOS import EventBox class TimelineViewController: UIViewController, UIScrollViewDelegate { // MARK: Properties @IBOutlet weak var scrollWrapperView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var streamingStatusLabel: UILabel! @IBOutlet weak var streamingView: UIView! @IBOutlet weak var streamingButton: StreamingButton! @IBOutlet weak var tabWraperView: UIView! @IBOutlet weak var tabCurrentMaskLeftConstraint: NSLayoutConstraint! var settingsViewController: SettingsViewController! var tableViewControllers = [TimelineTableViewController]() var tabButtons = [MenuButton]() var setupView = false var userID = "" var currentPage = 0 struct Static { private static let connectionQueue = NSOperationQueue().serial() } override var nibName: String { return "TimelineViewController" } // MARK: - View Life Cycle override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !setupView { setupView = true configureView() // ViewDidDisappear is performed When you view the ProfileViewController. configureEvent() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } deinit { EventBox.off(self) } // MARK: - Configuration func configureView() { settingsViewController = SettingsViewController() ViewTools.addSubviewWithEqual(self.view, view: settingsViewController.view) if let account = AccountSettingsStore.get() { userID = account.account().userID ImageLoaderClient.displayTitleIcon(account.account().profileImageURL, imageView: iconImageView) } var size = scrollWrapperView.frame.size let contentView = UIView(frame: CGRectMake(0, 0, size.width * 3, size.height)) for i in 0 ... 1 { let vc: TimelineTableViewController = i == 0 ? HomeTimelineTableViewController() : NotificationsViewController() vc.view.frame = CGRectMake(0, 0, size.width, size.height) let view = UIView(frame: CGRectMake(size.width * CGFloat(i), 0, size.width, size.height)) view.addSubview(vc.view) contentView.addSubview(view) tableViewControllers.append(vc) if let button = MenuButton.buttonWithType(UIButtonType.System) as? MenuButton { button.tag = i button.titleLabel?.font = UIFont(name: "fontello", size: 20.0) button.frame = CGRectMake(58 * CGFloat(i), 0, 58, 58) button.contentEdgeInsets = UIEdgeInsetsMake(15, 20, 15, 20) button.setTitle(i == 0 ? "家" : "@", forState: UIControlState.Normal) button.sizeToFit() button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tabButton:")) var longPress = UILongPressGestureRecognizer(target: self, action: "refresh:") longPress.minimumPressDuration = 2.0; button.addGestureRecognizer(longPress) tabWraperView.addSubview(button) tabButtons.append(button) } } scrollView.addSubview(contentView) scrollView.contentSize = contentView.frame.size scrollView.pagingEnabled = true scrollView.delegate = self streamingView.userInteractionEnabled = true var gesture = UITapGestureRecognizer(target: self, action: "streamingSwitch:") gesture.numberOfTapsRequired = 1 streamingView.addGestureRecognizer(gesture) } func configureEvent() { EventBox.onMainThread(self, name: TwitterAuthorizeNotification, handler: { _ in self.reset() }) EventBox.onMainThread(self, name: EventAccountChanged, handler: { _ in self.reset() }) EventBox.onMainThread(self, name: Twitter.Event.CreateStatus.rawValue, sender: nil) { n in let status = n.object as! TwitterStatus var page = 0 for tableViewController in self.tableViewControllers { switch tableViewController { case let vc as StatusTableViewController: if vc.accept(status) { vc.renderData([status], mode: .TOP, handler: {}) if self.currentPage != page || !vc.isTop { self.tabButtons[page].selected = true } } default: break } page++ } } EventBox.onMainThread(self, name: Twitter.Event.StreamingStatusChanged.rawValue) { _ in switch Twitter.connectionStatus { case .CONNECTED: self.streamingStatusLabel.text = "connected" self.streamingButton.enabled = true self.streamingButton.selected = true case .CONNECTING: self.streamingStatusLabel.text = "connecting..." self.streamingButton.enabled = true self.streamingButton.selected = false case .DISCONNECTED: self.streamingStatusLabel.text = "disconnected" if Twitter.enableStreaming { self.streamingButton.enabled = false self.streamingButton.selected = false } else { self.streamingButton.enabled = true self.streamingButton.selected = false } case .DISCONNECTING: self.streamingStatusLabel.text = "disconnecting..." self.streamingButton.enabled = true self.streamingButton.selected = false } } EventBox.onMainThread(self, name: "timelineScrollToTop", handler: { _ in self.tabButtons[self.currentPage].selected = false }) } func toggleStreaming() { } func reset() { if let account = AccountSettingsStore.get() { ImageLoaderClient.displayTitleIcon(account.account().profileImageURL, imageView: self.iconImageView) // other account if userID != account.account().userID { userID = account.account().userID for tableViewController in self.tableViewControllers { switch tableViewController { case let vc as StatusTableViewController: vc.refresh() default: break } } } } self.settingsViewController.hide() } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { let page = Int((scrollView.contentOffset.x + (scrollWrapperView.frame.size.width / 2)) / scrollWrapperView.frame.size.width) if currentPage != page { currentPage = page self.highlightUpdate(page) } } // MARK: - Actions func highlightUpdate(page: Int) { tabCurrentMaskLeftConstraint.constant = CGFloat(page * 58) } func refresh(sender: UILongPressGestureRecognizer) { if (sender.state != .Began) { return } tableViewControllers[currentPage].refresh() } func streamingSwitch(sender: UIView) { StreamingAlert.show(sender) } func tabButton(sender: UITapGestureRecognizer) { if let page = sender.view?.tag { if currentPage == page { tableViewControllers[page].scrollToTop() tabButtons[page].selected = false } else { UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width * CGFloat(page), 0) }, completion: { (flag) -> Void in self.currentPage = page self.highlightUpdate(page) }) } } } @IBAction func showEditor(sender: UIButton) { EditorViewController.show() } @IBAction func showSettings(sender: UIButton) { settingsViewController.show() } } Don't need tinyColor for the MenuButton. import UIKit import SwifteriOS import EventBox class TimelineViewController: UIViewController, UIScrollViewDelegate { // MARK: Properties @IBOutlet weak var scrollWrapperView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var streamingStatusLabel: UILabel! @IBOutlet weak var streamingView: UIView! @IBOutlet weak var streamingButton: StreamingButton! @IBOutlet weak var tabWraperView: UIView! @IBOutlet weak var tabCurrentMaskLeftConstraint: NSLayoutConstraint! var settingsViewController: SettingsViewController! var tableViewControllers = [TimelineTableViewController]() var tabButtons = [MenuButton]() var setupView = false var userID = "" var currentPage = 0 struct Static { private static let connectionQueue = NSOperationQueue().serial() } override var nibName: String { return "TimelineViewController" } // MARK: - View Life Cycle override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !setupView { setupView = true configureView() // ViewDidDisappear is performed When you view the ProfileViewController. configureEvent() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } deinit { EventBox.off(self) } // MARK: - Configuration func configureView() { settingsViewController = SettingsViewController() ViewTools.addSubviewWithEqual(self.view, view: settingsViewController.view) if let account = AccountSettingsStore.get() { userID = account.account().userID ImageLoaderClient.displayTitleIcon(account.account().profileImageURL, imageView: iconImageView) } var size = scrollWrapperView.frame.size let contentView = UIView(frame: CGRectMake(0, 0, size.width * 3, size.height)) for i in 0 ... 1 { let vc: TimelineTableViewController = i == 0 ? HomeTimelineTableViewController() : NotificationsViewController() vc.view.frame = CGRectMake(0, 0, size.width, size.height) let view = UIView(frame: CGRectMake(size.width * CGFloat(i), 0, size.width, size.height)) view.addSubview(vc.view) contentView.addSubview(view) tableViewControllers.append(vc) if let button = MenuButton.buttonWithType(UIButtonType.System) as? MenuButton { button.tag = i button.tintColor = UIColor.clearColor() button.titleLabel?.font = UIFont(name: "fontello", size: 20.0) button.frame = CGRectMake(58 * CGFloat(i), 0, 58, 58) button.contentEdgeInsets = UIEdgeInsetsMake(15, 20, 15, 20) button.setTitle(i == 0 ? "家" : "@", forState: UIControlState.Normal) button.sizeToFit() button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tabButton:")) var longPress = UILongPressGestureRecognizer(target: self, action: "refresh:") longPress.minimumPressDuration = 2.0; button.addGestureRecognizer(longPress) tabWraperView.addSubview(button) tabButtons.append(button) } } scrollView.addSubview(contentView) scrollView.contentSize = contentView.frame.size scrollView.pagingEnabled = true scrollView.delegate = self streamingView.userInteractionEnabled = true var gesture = UITapGestureRecognizer(target: self, action: "streamingSwitch:") gesture.numberOfTapsRequired = 1 streamingView.addGestureRecognizer(gesture) } func configureEvent() { EventBox.onMainThread(self, name: TwitterAuthorizeNotification, handler: { _ in self.reset() }) EventBox.onMainThread(self, name: EventAccountChanged, handler: { _ in self.reset() }) EventBox.onMainThread(self, name: Twitter.Event.CreateStatus.rawValue, sender: nil) { n in let status = n.object as! TwitterStatus var page = 0 for tableViewController in self.tableViewControllers { switch tableViewController { case let vc as StatusTableViewController: if vc.accept(status) { vc.renderData([status], mode: .TOP, handler: {}) if self.currentPage != page || !vc.isTop { self.tabButtons[page].selected = true } } default: break } page++ } } EventBox.onMainThread(self, name: Twitter.Event.StreamingStatusChanged.rawValue) { _ in switch Twitter.connectionStatus { case .CONNECTED: self.streamingStatusLabel.text = "connected" self.streamingButton.enabled = true self.streamingButton.selected = true case .CONNECTING: self.streamingStatusLabel.text = "connecting..." self.streamingButton.enabled = true self.streamingButton.selected = false case .DISCONNECTED: self.streamingStatusLabel.text = "disconnected" if Twitter.enableStreaming { self.streamingButton.enabled = false self.streamingButton.selected = false } else { self.streamingButton.enabled = true self.streamingButton.selected = false } case .DISCONNECTING: self.streamingStatusLabel.text = "disconnecting..." self.streamingButton.enabled = true self.streamingButton.selected = false } } EventBox.onMainThread(self, name: "timelineScrollToTop", handler: { _ in self.tabButtons[self.currentPage].selected = false }) } func toggleStreaming() { } func reset() { if let account = AccountSettingsStore.get() { ImageLoaderClient.displayTitleIcon(account.account().profileImageURL, imageView: self.iconImageView) // other account if userID != account.account().userID { userID = account.account().userID for tableViewController in self.tableViewControllers { switch tableViewController { case let vc as StatusTableViewController: vc.refresh() default: break } } } } self.settingsViewController.hide() } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { let page = Int((scrollView.contentOffset.x + (scrollWrapperView.frame.size.width / 2)) / scrollWrapperView.frame.size.width) if currentPage != page { currentPage = page self.highlightUpdate(page) } } // MARK: - Actions func highlightUpdate(page: Int) { tabCurrentMaskLeftConstraint.constant = CGFloat(page * 58) if tableViewControllers[currentPage].isTop { tabButtons[currentPage].selected = false } } func refresh(sender: UILongPressGestureRecognizer) { if (sender.state != .Began) { return } tableViewControllers[currentPage].refresh() } func streamingSwitch(sender: UIView) { StreamingAlert.show(sender) } func tabButton(sender: UITapGestureRecognizer) { if let page = sender.view?.tag { if currentPage == page { tableViewControllers[page].scrollToTop() tabButtons[page].selected = false } else { UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width * CGFloat(page), 0) }, completion: { (flag) -> Void in self.currentPage = page self.highlightUpdate(page) }) } } } @IBAction func showEditor(sender: UIButton) { EditorViewController.show() } @IBAction func showSettings(sender: UIButton) { settingsViewController.show() } }
// // KeyboardViewController.swift // Keyboard // // Created by Alexei Baboulevitch on 6/9/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit let metrics: [String:Double] = [ "topBanner": 30 ] func metric(name: String) -> CGFloat { return CGFloat(metrics[name]!) } class KeyboardViewController: UIInputViewController { let backspaceDelay: NSTimeInterval = 0.5 let backspaceRepeat: NSTimeInterval = 0.05 var keyboard: Keyboard var forwardingView: ForwardingView var layout: KeyboardLayout! var heightConstraint: NSLayoutConstraint? var currentMode: Int { didSet { setMode(currentMode) } } var backspaceActive: Bool { get { return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil) } } var backspaceDelayTimer: NSTimer? var backspaceRepeatTimer: NSTimer? enum ShiftState { case Disabled case Enabled case Locked func uppercase() -> Bool { switch self { case Disabled: return false case Enabled: return true case Locked: return true } } } var shiftState: ShiftState { didSet { switch shiftState { case .Disabled: self.updateKeyCaps(true) case .Enabled: self.updateKeyCaps(false) case .Locked: self.updateKeyCaps(false) } } } var keyboardHeight: CGFloat { get { if let constraint = self.heightConstraint { return constraint.constant } else { return 0 } } set { self.setHeight(newValue) } } // TODO: why does the app crash if this isn't here? convenience override init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.keyboard = defaultKeyboard() self.forwardingView = ForwardingView(frame: CGRectZero) self.shiftState = .Disabled self.currentMode = 0 super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.layout = KeyboardLayout(model: self.keyboard, superview: self.forwardingView, topBanner: 0) self.view.addSubview(self.forwardingView) self.view.setNeedsUpdateConstraints() } required init(coder: NSCoder) { fatalError("NSCoding not supported") } /* BUG NOTE For some strange reason, a layout pass of the entire keyboard is triggered whenever a popup shows up, if one of the following is done: a) The forwarding view uses an autoresizing mask. b) The forwarding view has constraints set anywhere other than init. On the other hand, setting (non-autoresizing) constraints or just setting the frame in layoutSubviews works perfectly fine. I don't really know what to make of this. Am I doing Autolayout wrong, is it a bug, or is it expected behavior? Perhaps this has to do with the fact that the view's frame is only ever explicitly modified when set directly in layoutSubviews, and not implicitly modified by various Autolayout constraints (even though it should really not be changing). */ var constraintsAdded: Bool = false func setupConstraints() { if !constraintsAdded { self.layout.initialize() self.setupKeys() self.constraintsAdded = true self.setMode(0) } } override func updateViewConstraints() { super.updateViewConstraints() // // suppresses constraint unsatisfiability on initial zero rect; mostly an issue of log spam // // TODO: there's probably a more sensible/correct way to do this // if CGRectIsEmpty(self.view.bounds) { // NSLayoutConstraint.deactivateConstraints(self.layout.allConstraintObjects) // } // else { // NSLayoutConstraint.activateConstraints(self.layout.allConstraintObjects) // } self.setupConstraints() } override func viewDidLayoutSubviews() { self.forwardingView.frame = self.view.bounds } override func viewDidAppear(animated: Bool) { self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation) self.layout.topBanner = metric("topBanner") } // TODO: the new size "snaps" into place on rotation, which I believe is related to performance override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation) } func heightForOrientation(orientation: UIInterfaceOrientation) -> CGFloat { let canonicalPortraitHeight = CGFloat(216) //TODO: different size for 6+ let canonicalLandscapeHeight = CGFloat(162) return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + metric("topBanner") : canonicalLandscapeHeight + metric("topBanner")) } /* BUG NOTE None of the UIContentContainer methods are called for this controller. */ //override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) //} func setupKeys() { for page in keyboard.pages { for rowKeys in page.rows { // TODO: quick hack for key in rowKeys { var keyView = self.layout.viewForKey(key)! // TODO: check let showOptions: UIControlEvents = .TouchDown | .TouchDragInside | .TouchDragEnter let hideOptions: UIControlEvents = .TouchUpInside | .TouchUpOutside | .TouchDragOutside switch key.type { case Key.KeyType.KeyboardChange: keyView.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside) case Key.KeyType.Backspace: let cancelEvents: UIControlEvents = UIControlEvents.TouchUpInside|UIControlEvents.TouchUpInside|UIControlEvents.TouchDragExit|UIControlEvents.TouchUpOutside|UIControlEvents.TouchCancel|UIControlEvents.TouchDragOutside keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown) keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents) case Key.KeyType.Shift: keyView.addTarget(self, action: Selector("shiftDown:"), forControlEvents: .TouchUpInside) keyView.addTarget(self, action: Selector("shiftDoubleTapped:"), forControlEvents: .TouchDownRepeat) case Key.KeyType.ModeChange: keyView.addTarget(self, action: Selector("modeChangeTapped"), forControlEvents: .TouchUpInside) default: break } if key.hasOutput { keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside) // keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown) } if key.type == Key.KeyType.Character || key.type == Key.KeyType.Period { keyView.addTarget(keyView, action: Selector("showPopup"), forControlEvents: showOptions) keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: hideOptions) } } } } } func takeScreenshotDelay() { var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false) } func takeScreenshot() { if !CGRectIsEmpty(self.view.bounds) { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) var rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) var context = UIGraphicsGetCurrentContext() self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) var capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") var imagePath = "/Users/archagon/Documents/Programming/OSX/TransliteratingKeyboard/\(name).png" UIImagePNGRepresentation(capturedImage).writeToFile(imagePath, atomically: true) self.view.backgroundColor = oldViewColor } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } // override func textWillChange(textInput: UITextInput) { // // The app is about to change the document's contents. Perform any preparation here. // } // // override func textDidChange(textInput: UITextInput) { // // The app has just changed the document's contents, the document context has been updated. // } func setHeight(height: CGFloat) { if self.heightConstraint == nil { assert(self.view.bounds.height != 0, "attempted to set height when view hasn't appeared yet") self.heightConstraint = NSLayoutConstraint( item:self.view, attribute:NSLayoutAttribute.Height, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute, multiplier:0, constant:height) self.heightConstraint!.priority = 1000 self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added? NSLog("constraint added") } else { self.heightConstraint?.constant = height } } func keyPressedHelper(sender: KeyboardKey) { // alas, this doesn't seem to work yet UIDevice.currentDevice().playInputClick() if let model = self.layout.keyForView(sender) { self.keyPressed(model) } if self.shiftState == ShiftState.Enabled { self.shiftState = ShiftState.Disabled } } func cancelBackspaceTimers() { self.backspaceDelayTimer?.invalidate() self.backspaceRepeatTimer?.invalidate() self.backspaceDelayTimer = nil self.backspaceRepeatTimer = nil } func backspaceDown(sender: KeyboardKey) { self.cancelBackspaceTimers() // first delete UIDevice.currentDevice().playInputClick() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } // trigger for subsequent deletes self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) } func backspaceUp(sender: KeyboardKey) { self.cancelBackspaceTimers() } func backspaceDelayCallback() { self.backspaceDelayTimer = nil self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: Selector("backspaceRepeatCallback"), userInfo: nil, repeats: true) } func backspaceRepeatCallback() { if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } } func shiftDown(sender: KeyboardKey) { switch self.shiftState { case .Disabled: self.shiftState = .Enabled sender.highlighted = true case .Enabled: self.shiftState = .Disabled sender.highlighted = false case .Locked: self.shiftState = .Disabled sender.highlighted = false } sender.text = "⇪" } func shiftDoubleTapped(sender: KeyboardKey) { switch self.shiftState { case .Disabled: self.shiftState = .Locked sender.highlighted = true case .Enabled: self.shiftState = .Locked sender.highlighted = true case .Locked: self.shiftState = .Locked sender.highlighted = true } sender.text = "L" } func updateKeyCaps(lowercase: Bool) { for (model, key) in self.layout.modelToView { key.text = model.keyCapForCase(!lowercase) } } func modeChangeTapped() { self.currentMode = ((self.currentMode + 1) % 3) } func setMode(mode: Int) { for (pageIndex, page) in enumerate(self.keyboard.pages) { for (rowIndex, row) in enumerate(page.rows) { for (keyIndex, key) in enumerate(row) { if self.layout.modelToView[key] != nil { var keyView = self.layout.modelToView[key] keyView?.hidden = (pageIndex != mode) } } } } } func keyPressed(key: Key) {} } //// does not work; drops CPU to 0% when run on device //extension UIInputView: UIInputViewAudioFeedback { // public var enableInputClicksWhenVisible: Bool { // return true // } //} Correct shift lock setting behavior. // // KeyboardViewController.swift // Keyboard // // Created by Alexei Baboulevitch on 6/9/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit let metrics: [String:Double] = [ "topBanner": 30 ] func metric(name: String) -> CGFloat { return CGFloat(metrics[name]!) } class KeyboardViewController: UIInputViewController { let backspaceDelay: NSTimeInterval = 0.5 let backspaceRepeat: NSTimeInterval = 0.05 var keyboard: Keyboard var forwardingView: ForwardingView var layout: KeyboardLayout! var heightConstraint: NSLayoutConstraint? var currentMode: Int { didSet { setMode(currentMode) } } var backspaceActive: Bool { get { return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil) } } var backspaceDelayTimer: NSTimer? var backspaceRepeatTimer: NSTimer? enum ShiftState { case Disabled case Enabled case Locked func uppercase() -> Bool { switch self { case Disabled: return false case Enabled: return true case Locked: return true } } } var shiftState: ShiftState { didSet { switch shiftState { case .Disabled: self.updateKeyCaps(true) case .Enabled: self.updateKeyCaps(false) case .Locked: self.updateKeyCaps(false) } } } var shiftWasMultitapped: Bool = false var keyboardHeight: CGFloat { get { if let constraint = self.heightConstraint { return constraint.constant } else { return 0 } } set { self.setHeight(newValue) } } // TODO: why does the app crash if this isn't here? convenience override init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.keyboard = defaultKeyboard() self.forwardingView = ForwardingView(frame: CGRectZero) self.shiftState = .Disabled self.currentMode = 0 super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.layout = KeyboardLayout(model: self.keyboard, superview: self.forwardingView, topBanner: 0) self.view.addSubview(self.forwardingView) self.view.setNeedsUpdateConstraints() } required init(coder: NSCoder) { fatalError("NSCoding not supported") } /* BUG NOTE For some strange reason, a layout pass of the entire keyboard is triggered whenever a popup shows up, if one of the following is done: a) The forwarding view uses an autoresizing mask. b) The forwarding view has constraints set anywhere other than init. On the other hand, setting (non-autoresizing) constraints or just setting the frame in layoutSubviews works perfectly fine. I don't really know what to make of this. Am I doing Autolayout wrong, is it a bug, or is it expected behavior? Perhaps this has to do with the fact that the view's frame is only ever explicitly modified when set directly in layoutSubviews, and not implicitly modified by various Autolayout constraints (even though it should really not be changing). */ var constraintsAdded: Bool = false func setupConstraints() { if !constraintsAdded { self.layout.initialize() self.setupKeys() self.constraintsAdded = true self.setMode(0) } } override func updateViewConstraints() { super.updateViewConstraints() // // suppresses constraint unsatisfiability on initial zero rect; mostly an issue of log spam // // TODO: there's probably a more sensible/correct way to do this // if CGRectIsEmpty(self.view.bounds) { // NSLayoutConstraint.deactivateConstraints(self.layout.allConstraintObjects) // } // else { // NSLayoutConstraint.activateConstraints(self.layout.allConstraintObjects) // } self.setupConstraints() } override func viewDidLayoutSubviews() { self.forwardingView.frame = self.view.bounds } override func viewDidAppear(animated: Bool) { self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation) self.layout.topBanner = metric("topBanner") } // TODO: the new size "snaps" into place on rotation, which I believe is related to performance override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation) } func heightForOrientation(orientation: UIInterfaceOrientation) -> CGFloat { let canonicalPortraitHeight = CGFloat(216) //TODO: different size for 6+ let canonicalLandscapeHeight = CGFloat(162) return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + metric("topBanner") : canonicalLandscapeHeight + metric("topBanner")) } /* BUG NOTE None of the UIContentContainer methods are called for this controller. */ //override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) //} func setupKeys() { for page in keyboard.pages { for rowKeys in page.rows { // TODO: quick hack for key in rowKeys { var keyView = self.layout.viewForKey(key)! // TODO: check let showOptions: UIControlEvents = .TouchDown | .TouchDragInside | .TouchDragEnter let hideOptions: UIControlEvents = .TouchUpInside | .TouchUpOutside | .TouchDragOutside switch key.type { case Key.KeyType.KeyboardChange: keyView.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside) case Key.KeyType.Backspace: let cancelEvents: UIControlEvents = UIControlEvents.TouchUpInside|UIControlEvents.TouchUpInside|UIControlEvents.TouchDragExit|UIControlEvents.TouchUpOutside|UIControlEvents.TouchCancel|UIControlEvents.TouchDragOutside keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown) keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents) case Key.KeyType.Shift: keyView.addTarget(self, action: Selector("shiftDown:"), forControlEvents: .TouchUpInside) keyView.addTarget(self, action: Selector("shiftDoubleTapped:"), forControlEvents: .TouchDownRepeat) case Key.KeyType.ModeChange: keyView.addTarget(self, action: Selector("modeChangeTapped"), forControlEvents: .TouchUpInside) default: break } if key.hasOutput { keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside) // keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown) } if key.type == Key.KeyType.Character || key.type == Key.KeyType.Period { keyView.addTarget(keyView, action: Selector("showPopup"), forControlEvents: showOptions) keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: hideOptions) } } } } } func takeScreenshotDelay() { var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false) } func takeScreenshot() { if !CGRectIsEmpty(self.view.bounds) { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) var rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) var context = UIGraphicsGetCurrentContext() self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) var capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") var imagePath = "/Users/archagon/Documents/Programming/OSX/TransliteratingKeyboard/\(name).png" UIImagePNGRepresentation(capturedImage).writeToFile(imagePath, atomically: true) self.view.backgroundColor = oldViewColor } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } // override func textWillChange(textInput: UITextInput) { // // The app is about to change the document's contents. Perform any preparation here. // } // // override func textDidChange(textInput: UITextInput) { // // The app has just changed the document's contents, the document context has been updated. // } func setHeight(height: CGFloat) { if self.heightConstraint == nil { assert(self.view.bounds.height != 0, "attempted to set height when view hasn't appeared yet") self.heightConstraint = NSLayoutConstraint( item:self.view, attribute:NSLayoutAttribute.Height, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute, multiplier:0, constant:height) self.heightConstraint!.priority = 1000 self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added? NSLog("constraint added") } else { self.heightConstraint?.constant = height } } func keyPressedHelper(sender: KeyboardKey) { // alas, this doesn't seem to work yet UIDevice.currentDevice().playInputClick() if let model = self.layout.keyForView(sender) { self.keyPressed(model) } if self.shiftState == ShiftState.Enabled { self.shiftState = ShiftState.Disabled } } func cancelBackspaceTimers() { self.backspaceDelayTimer?.invalidate() self.backspaceRepeatTimer?.invalidate() self.backspaceDelayTimer = nil self.backspaceRepeatTimer = nil } func backspaceDown(sender: KeyboardKey) { self.cancelBackspaceTimers() // first delete UIDevice.currentDevice().playInputClick() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } // trigger for subsequent deletes self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) } func backspaceUp(sender: KeyboardKey) { self.cancelBackspaceTimers() } func backspaceDelayCallback() { self.backspaceDelayTimer = nil self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: Selector("backspaceRepeatCallback"), userInfo: nil, repeats: true) } func backspaceRepeatCallback() { if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } } func shiftDown(sender: KeyboardKey) { if self.shiftWasMultitapped { self.shiftWasMultitapped = false return } switch self.shiftState { case .Disabled: self.shiftState = .Enabled sender.highlighted = true case .Enabled: self.shiftState = .Disabled sender.highlighted = false case .Locked: self.shiftState = .Disabled sender.highlighted = false } sender.text = "⇪" } func shiftDoubleTapped(sender: KeyboardKey) { self.shiftWasMultitapped = true switch self.shiftState { case .Disabled: self.shiftState = .Locked sender.text = "L" sender.highlighted = true case .Enabled: self.shiftState = .Locked sender.text = "L" sender.highlighted = true case .Locked: self.shiftState = .Disabled sender.text = "⇪" sender.highlighted = false } } func updateKeyCaps(lowercase: Bool) { for (model, key) in self.layout.modelToView { key.text = model.keyCapForCase(!lowercase) } } func modeChangeTapped() { self.currentMode = ((self.currentMode + 1) % 3) } func setMode(mode: Int) { for (pageIndex, page) in enumerate(self.keyboard.pages) { for (rowIndex, row) in enumerate(page.rows) { for (keyIndex, key) in enumerate(row) { if self.layout.modelToView[key] != nil { var keyView = self.layout.modelToView[key] keyView?.hidden = (pageIndex != mode) } } } } } func keyPressed(key: Key) {} } //// does not work; drops CPU to 0% when run on device //extension UIInputView: UIInputViewAudioFeedback { // public var enableInputClicksWhenVisible: Bool { // return true // } //}
// // KeyboardViewController.swift // Keyboard // // Created by Joon Park on 10/18/16. // import UIKit import CoreMotion import AudioToolbox class KeyboardViewController: UIInputViewController { var nextKeyboardButton: UIButton! var hideKeyboardButton: UIButton! var keyboardRows: [[UIButton]] = [] // An array of arrays of UIButtons: [Row][Button] var selectedRowIndex = 0 var selectedButtonIndex = 0 let manager = CMMotionManager() override func updateViewConstraints() { super.updateViewConstraints() // Add custom view sizing constraints here. } // Executed once the view finishes loading. override func viewDidLoad() { super.viewDidLoad() addKeyboardButtons() addClickArea() } func selectMovement() { /*let rawx = manager.deviceMotion?.gravity.x let rawy = manager.deviceMotion?.gravity.y _ = atan2(rawx!, rawy!)*/ } // Called once in 'viewDidLoad()' to render all the keyboard buttons. func addKeyboardButtons() { addNextKeyboardButton() addHideKeyboardButton() addAlphabetButtons() // Set the initially selected character. selectButton(rowIndex: 0, buttonIndex: 6) if manager.isGyroAvailable && manager.isDeviceMotionAvailable { manager.deviceMotionUpdateInterval = 0.1 manager.startDeviceMotionUpdates() manager.gyroUpdateInterval = 0.1 manager.startGyroUpdates() Timer.scheduledTimer(timeInterval: 0.15, target:self, selector: #selector(KeyboardViewController.selectMovement), userInfo: nil, repeats: true) } else { //keyboard wont work for this device } } // Renders a button to switch to the next system keyboard. func addNextKeyboardButton() { nextKeyboardButton = UIButton(type: .system) nextKeyboardButton.setTitle("Next Keyboard", for: []) nextKeyboardButton.sizeToFit() nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false nextKeyboardButton.backgroundColor = UIColor(white: 0.9, alpha: 1) nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) view.addSubview(self.nextKeyboardButton) nextKeyboardButton.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true nextKeyboardButton.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } func addHideKeyboardButton() { hideKeyboardButton = UIButton(type: .system) hideKeyboardButton.setTitle("Hide Keyboard", for: .normal) hideKeyboardButton.sizeToFit() hideKeyboardButton.translatesAutoresizingMaskIntoConstraints = false hideKeyboardButton.backgroundColor = UIColor(white: 0.9, alpha: 1) hideKeyboardButton.addTarget(self, action: #selector(UIInputViewController.dismissKeyboard), for: .touchUpInside) view.addSubview(hideKeyboardButton) hideKeyboardButton.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true hideKeyboardButton.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } func addAlphabetButtons() { let buttonTitles = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u{232b}"] let alphabetButtons = createButtons(titles: buttonTitles) let alphabetRow = UIView(frame: CGRect(x: 0, y: 0, width: 415, height: 40)) for alphabetButton in alphabetButtons { alphabetRow.addSubview(alphabetButton) } self.view.addSubview(alphabetRow) addConstraints(buttons: alphabetButtons, containingView: alphabetRow) keyboardRows.append(alphabetButtons) } func createButtons(titles: [String]) -> [UIButton] { var buttons = [UIButton!]() for title in titles { // Initialize the button. let button = UIButton(type: .system) button.setTitle(title, for: .normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false // Adding a callback. button.addTarget(self, action: #selector(KeyboardViewController.didTapButton(sender:)), for: .touchUpInside) // Make the font bigger. // button.titleLabel!.font = UIFont.systemFont(ofSize: 32) // Add rounded corners. button.backgroundColor = UIColor(white: 0.9, alpha: 1) button.layer.cornerRadius = 5 button.layer.borderColor = UIColor.black.cgColor buttons.append(button) } return buttons } func didTapButton(sender: AnyObject?) { let button = sender as! UIButton let title = button.title(for: .normal) // If it is the "delete" unicode character. if title == "\u{232b}" { (textDocumentProxy as UIKeyInput).deleteBackward() } else { (textDocumentProxy as UIKeyInput).insertText(title!) } } func addConstraints(buttons: [UIButton], containingView: UIView){ for (index, button) in buttons.enumerated() { let topConstraint = NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: containingView, attribute: .top, multiplier: 1.0, constant: 1) let bottomConstraint = NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: containingView, attribute: .bottom, multiplier: 1.0, constant: -1) var leftConstraint : NSLayoutConstraint! if index == 0 { leftConstraint = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: containingView, attribute: .left, multiplier: 1.0, constant: 1) } else { leftConstraint = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: buttons[index-1], attribute: .right, multiplier: 1.0, constant: 1) let widthConstraint = NSLayoutConstraint(item: buttons[0], attribute: .width, relatedBy: .equal, toItem: button, attribute: .width, multiplier: 1.0, constant: 0) containingView.addConstraint(widthConstraint) } var rightConstraint : NSLayoutConstraint! if index == buttons.count - 1 { rightConstraint = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: containingView, attribute: .right, multiplier: 1.0, constant: -1) } else { rightConstraint = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: buttons[index+1], attribute: .left, multiplier: 1.0, constant: -1) } containingView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint]) } } func selectButton(rowIndex: Int, buttonIndex: Int) { // Update the class-wide index variables. selectedRowIndex = rowIndex selectedButtonIndex = buttonIndex // Give the newly selected button an outline. keyboardRows[selectedRowIndex][selectedButtonIndex].layer.borderWidth = 1 } func selectLeft(num: Int = 1) { deselectButton(rowIndex: selectedRowIndex, buttonIndex: selectedButtonIndex) var newIndex = selectedButtonIndex - num; newIndex = newIndex >= 0 ? newIndex : 0; selectButton(rowIndex: selectedRowIndex, buttonIndex: newIndex) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } func selectRight(num: Int = 1) { deselectButton(rowIndex: selectedRowIndex, buttonIndex: selectedButtonIndex) var newIndex = selectedButtonIndex + num; newIndex = newIndex < keyboardRows[selectedRowIndex].count ? newIndex : keyboardRows[selectedRowIndex].count; selectButton(rowIndex: selectedRowIndex, buttonIndex: newIndex) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } func deselectButton(rowIndex: Int, buttonIndex: Int) { keyboardRows[rowIndex][buttonIndex].layer.borderWidth = 0 } func addClickArea() { // 1. Create UIView programmetically. let clickView = UIView(frame: CGRect(x: 0, y: 40, width: 415, height: 155)) clickView.backgroundColor = UIColor.lightGray // 2. Add myView to UIView hierarchy. view.addSubview(clickView) // 3. Add action to clickView. let gesture = UITapGestureRecognizer(target: self, action: #selector(insertSelectedButton (_:))) clickView.addGestureRecognizer(gesture) } func insertSelectedButton(_ sender: UITapGestureRecognizer){ let selectedCharacter = keyboardRows[selectedRowIndex][selectedButtonIndex].title(for: .normal) // If it is the "delete" unicode character. if selectedCharacter == "\u{232b}" { (textDocumentProxy as UIKeyInput).deleteBackward() } else { (textDocumentProxy as UIKeyInput).insertText(selectedCharacter!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func textWillChange(_ textInput: UITextInput?) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(_ textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { textColor = UIColor.white } else { textColor = UIColor.black } self.nextKeyboardButton.setTitleColor(textColor, for: []) } } attempt 1 to use gyroscope // // KeyboardViewController.swift // Keyboard // // Created by Joon Park on 10/18/16. // import UIKit import CoreMotion import AudioToolbox class KeyboardViewController: UIInputViewController { var nextKeyboardButton: UIButton! var hideKeyboardButton: UIButton! var keyboardRows: [[UIButton]] = [] // An array of arrays of UIButtons: [Row][Button] var selectedRowIndex = 0 var selectedButtonIndex = 0 let manager = CMMotionManager() override func updateViewConstraints() { super.updateViewConstraints() // Add custom view sizing constraints here. } // Executed once the view finishes loading. override func viewDidLoad() { super.viewDidLoad() addKeyboardButtons() addClickArea() } func selectMovement() { let rawx = manager.deviceMotion?.gravity.x let rawy = manager.deviceMotion?.gravity.y let angle = atan2(rawx!, rawy!) if angle > 0 { selectRight() } else { selectLeft() } } // Called once in 'viewDidLoad()' to render all the keyboard buttons. func addKeyboardButtons() { addNextKeyboardButton() addHideKeyboardButton() addAlphabetButtons() // Set the initially selected character. selectButton(rowIndex: 0, buttonIndex: 6) if manager.isGyroAvailable && manager.isDeviceMotionAvailable { manager.deviceMotionUpdateInterval = 0.1 manager.startDeviceMotionUpdates() manager.gyroUpdateInterval = 0.1 manager.startGyroUpdates() Timer.scheduledTimer(timeInterval: 0.15, target:self, selector: #selector(KeyboardViewController.selectMovement), userInfo: nil, repeats: true) } else { //keyboard wont work for this device } } // Renders a button to switch to the next system keyboard. func addNextKeyboardButton() { nextKeyboardButton = UIButton(type: .system) nextKeyboardButton.setTitle("Next Keyboard", for: []) nextKeyboardButton.sizeToFit() nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false nextKeyboardButton.backgroundColor = UIColor(white: 0.9, alpha: 1) nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) view.addSubview(self.nextKeyboardButton) nextKeyboardButton.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true nextKeyboardButton.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } func addHideKeyboardButton() { hideKeyboardButton = UIButton(type: .system) hideKeyboardButton.setTitle("Hide Keyboard", for: .normal) hideKeyboardButton.sizeToFit() hideKeyboardButton.translatesAutoresizingMaskIntoConstraints = false hideKeyboardButton.backgroundColor = UIColor(white: 0.9, alpha: 1) hideKeyboardButton.addTarget(self, action: #selector(UIInputViewController.dismissKeyboard), for: .touchUpInside) view.addSubview(hideKeyboardButton) hideKeyboardButton.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true hideKeyboardButton.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } func addAlphabetButtons() { let buttonTitles = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u{232b}"] let alphabetButtons = createButtons(titles: buttonTitles) let alphabetRow = UIView(frame: CGRect(x: 0, y: 0, width: 415, height: 40)) for alphabetButton in alphabetButtons { alphabetRow.addSubview(alphabetButton) } self.view.addSubview(alphabetRow) addConstraints(buttons: alphabetButtons, containingView: alphabetRow) keyboardRows.append(alphabetButtons) } func createButtons(titles: [String]) -> [UIButton] { var buttons = [UIButton!]() for title in titles { // Initialize the button. let button = UIButton(type: .system) button.setTitle(title, for: .normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false // Adding a callback. button.addTarget(self, action: #selector(KeyboardViewController.didTapButton(sender:)), for: .touchUpInside) // Make the font bigger. // button.titleLabel!.font = UIFont.systemFont(ofSize: 32) // Add rounded corners. button.backgroundColor = UIColor(white: 0.9, alpha: 1) button.layer.cornerRadius = 5 button.layer.borderColor = UIColor.black.cgColor buttons.append(button) } return buttons } func didTapButton(sender: AnyObject?) { let button = sender as! UIButton let title = button.title(for: .normal) // If it is the "delete" unicode character. if title == "\u{232b}" { (textDocumentProxy as UIKeyInput).deleteBackward() } else { (textDocumentProxy as UIKeyInput).insertText(title!) } } func addConstraints(buttons: [UIButton], containingView: UIView){ for (index, button) in buttons.enumerated() { let topConstraint = NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: containingView, attribute: .top, multiplier: 1.0, constant: 1) let bottomConstraint = NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: containingView, attribute: .bottom, multiplier: 1.0, constant: -1) var leftConstraint : NSLayoutConstraint! if index == 0 { leftConstraint = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: containingView, attribute: .left, multiplier: 1.0, constant: 1) } else { leftConstraint = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: buttons[index-1], attribute: .right, multiplier: 1.0, constant: 1) let widthConstraint = NSLayoutConstraint(item: buttons[0], attribute: .width, relatedBy: .equal, toItem: button, attribute: .width, multiplier: 1.0, constant: 0) containingView.addConstraint(widthConstraint) } var rightConstraint : NSLayoutConstraint! if index == buttons.count - 1 { rightConstraint = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: containingView, attribute: .right, multiplier: 1.0, constant: -1) } else { rightConstraint = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: buttons[index+1], attribute: .left, multiplier: 1.0, constant: -1) } containingView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint]) } } func selectButton(rowIndex: Int, buttonIndex: Int) { // Update the class-wide index variables. selectedRowIndex = rowIndex selectedButtonIndex = buttonIndex // Give the newly selected button an outline. keyboardRows[selectedRowIndex][selectedButtonIndex].layer.borderWidth = 1 } func selectLeft(num: Int = 1) { deselectButton(rowIndex: selectedRowIndex, buttonIndex: selectedButtonIndex) var newIndex = selectedButtonIndex - num; newIndex = newIndex >= 0 ? newIndex : 0; selectButton(rowIndex: selectedRowIndex, buttonIndex: newIndex) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } func selectRight(num: Int = 1) { deselectButton(rowIndex: selectedRowIndex, buttonIndex: selectedButtonIndex) var newIndex = selectedButtonIndex + num; newIndex = newIndex < keyboardRows[selectedRowIndex].count ? newIndex : keyboardRows[selectedRowIndex].count; selectButton(rowIndex: selectedRowIndex, buttonIndex: newIndex) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } func deselectButton(rowIndex: Int, buttonIndex: Int) { keyboardRows[rowIndex][buttonIndex].layer.borderWidth = 0 } func addClickArea() { // 1. Create UIView programmetically. let clickView = UIView(frame: CGRect(x: 0, y: 40, width: 415, height: 155)) clickView.backgroundColor = UIColor.lightGray // 2. Add myView to UIView hierarchy. view.addSubview(clickView) // 3. Add action to clickView. let gesture = UITapGestureRecognizer(target: self, action: #selector(insertSelectedButton (_:))) clickView.addGestureRecognizer(gesture) } func insertSelectedButton(_ sender: UITapGestureRecognizer){ let selectedCharacter = keyboardRows[selectedRowIndex][selectedButtonIndex].title(for: .normal) // If it is the "delete" unicode character. if selectedCharacter == "\u{232b}" { (textDocumentProxy as UIKeyInput).deleteBackward() } else { (textDocumentProxy as UIKeyInput).insertText(selectedCharacter!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func textWillChange(_ textInput: UITextInput?) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(_ textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { textColor = UIColor.white } else { textColor = UIColor.black } self.nextKeyboardButton.setTitleColor(textColor, for: []) } }
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-opt-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify // REQUIRES: optimized_stdlib public class Klass {} public var global = Klass() @inline(never) public func getGlobal() -> Klass { return global // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-5:12 {{of 'global'}} } public func useGlobal() { let x = getGlobal() // Make sure that the retain msg is at the beginning of the print and the // releases are the end of the print. print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:9 {{of 'x'}} // expected-remark @-2:12 {{release of type}} // expected-remark @-3:12 {{release of type 'Klass'}} // expected-note @-7:9 {{of 'x'}} } public enum TrivialState { case first case second case third } struct StructWithOwner { // This retain is from the initializers of owner. // // TODO: Should we emit this? var owner = Klass() // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.owner'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.owner'}} var state = TrivialState.first } func printStructWithOwner(x : StructWithOwner) { print(x) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:27 {{of 'x.owner'}} // We should be able to infer the arg here. // expected-remark @-3:12 {{release of type}} } func printStructWithOwnerOwner(x : StructWithOwner) { print(x.owner) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:32 {{of 'x.owner'}} // We should be able to infer the arg here. // expected-remark @-3:18 {{release of type}} } func returnStructWithOwnerOwner(x: StructWithOwner) -> Klass { return x.owner // expected-remark {{retain of type 'Klass'}} // expected-note @-2:33 {{of 'x.owner'}} } func callingAnInitializerStructWithOwner(x: Klass) -> StructWithOwner { return StructWithOwner(owner: x) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:42 {{of 'x'}} } struct KlassPair { var lhs: Klass // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.lhs'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.lhs'}} var rhs: Klass // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.rhs'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.rhs'}} } func printKlassPair(x : KlassPair) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:21 {{of 'x.lhs'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-6:21 {{of 'x.rhs'}} // This is a release for Array<Any> for print. // expected-remark @-5:12 {{release of type}} } func printKlassPairLHS(x : KlassPair) { // We print the remarks at the 'p' and at the ending ')'. print(x.lhs) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-3:24 {{of 'x.lhs'}} // Release for Array<Any> needed for print. // expected-remark @-3:16 {{release of type}} } func returnKlassPairLHS(x: KlassPair) -> Klass { return x.lhs // expected-remark @:14 {{retain of type 'Klass'}} // expected-note @-2:25 {{of 'x.lhs'}} } func callingAnInitializerKlassPair(x: Klass, y: Klass) -> KlassPair { return KlassPair(lhs: x, rhs: y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:36 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:46 {{of 'y'}} } func printKlassTuplePair(x : (Klass, Klass)) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:26 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-6:26 {{of 'x'}} // Release on temp array for print(...). // expected-remark @-5:12 {{release of type}} } func printKlassTupleLHS(x : (Klass, Klass)) { // We print the remarks at the 'p' and at the ending ')'. print(x.0) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-3:25 {{of 'x'}} // Release on Array<Any> for print. // expected-remark @-3:14 {{release of type}} } func returnKlassTupleLHS(x: (Klass, Klass)) -> Klass { return x.0 // expected-remark @:12 {{retain of type 'Klass'}} // expected-note @-2:26 {{of 'x'}} } func callingAnInitializerKlassTuplePair(x: Klass, y: Klass) -> (Klass, Klass) { return (x, y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:41 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:51 {{of 'y'}} } public class SubKlass : Klass { @inline(never) final func doSomething() {} } func lookThroughCast(x: SubKlass) -> Klass { return x as Klass // expected-remark {{retain of type 'SubKlass'}} // expected-note @-2:22 {{of 'x'}} } func lookThroughRefCast(x: Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:25 {{of 'x'}} } func lookThroughEnum(x: Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2:22 {{of 'x.some'}} } func castAsQuestion(x: Klass) -> SubKlass? { x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:21 {{of 'x'}} } func castAsQuestionDiamond(x: Klass) -> SubKlass? { guard let y = x as? SubKlass else { return nil } y.doSomething() return y // expected-remark {{retain of type 'Klass'}} // expected-note @-7:28 {{of 'x'}} } func castAsQuestionDiamondGEP(x: KlassPair) -> SubKlass? { guard let y = x.lhs as? SubKlass else { return nil } y.doSomething() // We eliminate the rhs retain/release. return y // expected-remark {{retain of type 'Klass'}} // expected-note @-8:31 {{of 'x.lhs'}} } // We don't handle this test case as well. func castAsQuestionDiamondGEP2(x: KlassPair) { switch (x.lhs as? SubKlass, x.rhs as? SubKlass) { // expected-remark @:19 {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} // expected-remark @-2:39 {{retain of type 'Klass'}} // expected-note @-4 {{of 'x.rhs'}} case let (.some(x1), .some(x2)): print(x1, x2) // expected-remark {{retain of type 'Optional<SubKlass>'}} // expected-remark @-1 {{retain of type 'Optional<SubKlass>'}} // expected-remark @-2 {{release of type}} // expected-remark @-3 {{release of type 'Optional<SubKlass>'}} // expected-remark @-4 {{release of type 'Optional<SubKlass>'}} case let (.some(x1), nil): print(x1) // expected-remark {{retain of type 'SubKlass'}} // expected-remark @-1 {{release of type}} // expected-remark @-2 {{release of type 'Optional<SubKlass>'}} case let (nil, .some(x2)): print(x2) // expected-remark {{retain of type 'SubKlass'}} // expected-remark @-1 {{release of type}} // expected-remark @-2 {{release of type 'Optional<SubKlass>'}} case (nil, nil): break } } func inoutKlassPairArgument(x: inout KlassPair) -> Klass { return x.lhs // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} } func inoutKlassTuplePairArgument(x: inout (Klass, Klass)) -> Klass { return x.0 // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.0'}} } func inoutKlassOptionalArgument(x: inout Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassBangCastArgument(x: inout Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassQuestionCastArgument(x: inout Klass) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassBangCastArgument2(x: inout Klass?) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassQuestionCastArgument2(x: inout Klass?) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } [android] XFAIL opt-remark-generator.swift in ARMv7 Android ARMv7 doesn't seem to simplify the remarks from Optional<SubKlass> to just SubKlass, while other platforms do. I did not find any clues in #33171 what it might be happening, so XFAIL the test to avoid a failing build. // RUN: %target-swiftc_driver -O -Rpass-missed=sil-opt-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify // REQUIRES: optimized_stdlib // XFAIL: OS=linux-androideabi && CPU=armv7 public class Klass {} public var global = Klass() @inline(never) public func getGlobal() -> Klass { return global // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-5:12 {{of 'global'}} } public func useGlobal() { let x = getGlobal() // Make sure that the retain msg is at the beginning of the print and the // releases are the end of the print. print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:9 {{of 'x'}} // expected-remark @-2:12 {{release of type}} // expected-remark @-3:12 {{release of type 'Klass'}} // expected-note @-7:9 {{of 'x'}} } public enum TrivialState { case first case second case third } struct StructWithOwner { // This retain is from the initializers of owner. // // TODO: Should we emit this? var owner = Klass() // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.owner'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.owner'}} var state = TrivialState.first } func printStructWithOwner(x : StructWithOwner) { print(x) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:27 {{of 'x.owner'}} // We should be able to infer the arg here. // expected-remark @-3:12 {{release of type}} } func printStructWithOwnerOwner(x : StructWithOwner) { print(x.owner) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:32 {{of 'x.owner'}} // We should be able to infer the arg here. // expected-remark @-3:18 {{release of type}} } func returnStructWithOwnerOwner(x: StructWithOwner) -> Klass { return x.owner // expected-remark {{retain of type 'Klass'}} // expected-note @-2:33 {{of 'x.owner'}} } func callingAnInitializerStructWithOwner(x: Klass) -> StructWithOwner { return StructWithOwner(owner: x) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:42 {{of 'x'}} } struct KlassPair { var lhs: Klass // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.lhs'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.lhs'}} var rhs: Klass // expected-remark {{retain of type 'Klass'}} // expected-note @-1 {{of 'self.rhs'}} // expected-remark @-2 {{release of type 'Klass'}} // expected-note @-3 {{of 'self.rhs'}} } func printKlassPair(x : KlassPair) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:21 {{of 'x.lhs'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-6:21 {{of 'x.rhs'}} // This is a release for Array<Any> for print. // expected-remark @-5:12 {{release of type}} } func printKlassPairLHS(x : KlassPair) { // We print the remarks at the 'p' and at the ending ')'. print(x.lhs) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-3:24 {{of 'x.lhs'}} // Release for Array<Any> needed for print. // expected-remark @-3:16 {{release of type}} } func returnKlassPairLHS(x: KlassPair) -> Klass { return x.lhs // expected-remark @:14 {{retain of type 'Klass'}} // expected-note @-2:25 {{of 'x.lhs'}} } func callingAnInitializerKlassPair(x: Klass, y: Klass) -> KlassPair { return KlassPair(lhs: x, rhs: y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:36 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:46 {{of 'y'}} } func printKlassTuplePair(x : (Klass, Klass)) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-4:26 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-6:26 {{of 'x'}} // Release on temp array for print(...). // expected-remark @-5:12 {{release of type}} } func printKlassTupleLHS(x : (Klass, Klass)) { // We print the remarks at the 'p' and at the ending ')'. print(x.0) // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-3:25 {{of 'x'}} // Release on Array<Any> for print. // expected-remark @-3:14 {{release of type}} } func returnKlassTupleLHS(x: (Klass, Klass)) -> Klass { return x.0 // expected-remark @:12 {{retain of type 'Klass'}} // expected-note @-2:26 {{of 'x'}} } func callingAnInitializerKlassTuplePair(x: Klass, y: Klass) -> (Klass, Klass) { return (x, y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:41 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:51 {{of 'y'}} } public class SubKlass : Klass { @inline(never) final func doSomething() {} } func lookThroughCast(x: SubKlass) -> Klass { return x as Klass // expected-remark {{retain of type 'SubKlass'}} // expected-note @-2:22 {{of 'x'}} } func lookThroughRefCast(x: Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:25 {{of 'x'}} } func lookThroughEnum(x: Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2:22 {{of 'x.some'}} } func castAsQuestion(x: Klass) -> SubKlass? { x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:21 {{of 'x'}} } func castAsQuestionDiamond(x: Klass) -> SubKlass? { guard let y = x as? SubKlass else { return nil } y.doSomething() return y // expected-remark {{retain of type 'Klass'}} // expected-note @-7:28 {{of 'x'}} } func castAsQuestionDiamondGEP(x: KlassPair) -> SubKlass? { guard let y = x.lhs as? SubKlass else { return nil } y.doSomething() // We eliminate the rhs retain/release. return y // expected-remark {{retain of type 'Klass'}} // expected-note @-8:31 {{of 'x.lhs'}} } // We don't handle this test case as well. func castAsQuestionDiamondGEP2(x: KlassPair) { switch (x.lhs as? SubKlass, x.rhs as? SubKlass) { // expected-remark @:19 {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} // expected-remark @-2:39 {{retain of type 'Klass'}} // expected-note @-4 {{of 'x.rhs'}} case let (.some(x1), .some(x2)): print(x1, x2) // expected-remark {{retain of type 'Optional<SubKlass>'}} // expected-remark @-1 {{retain of type 'Optional<SubKlass>'}} // expected-remark @-2 {{release of type}} // expected-remark @-3 {{release of type 'Optional<SubKlass>'}} // expected-remark @-4 {{release of type 'Optional<SubKlass>'}} case let (.some(x1), nil): print(x1) // expected-remark {{retain of type 'SubKlass'}} // expected-remark @-1 {{release of type}} // expected-remark @-2 {{release of type 'Optional<SubKlass>'}} case let (nil, .some(x2)): print(x2) // expected-remark {{retain of type 'SubKlass'}} // expected-remark @-1 {{release of type}} // expected-remark @-2 {{release of type 'Optional<SubKlass>'}} case (nil, nil): break } } func inoutKlassPairArgument(x: inout KlassPair) -> Klass { return x.lhs // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} } func inoutKlassTuplePairArgument(x: inout (Klass, Klass)) -> Klass { return x.0 // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.0'}} } func inoutKlassOptionalArgument(x: inout Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassBangCastArgument(x: inout Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassQuestionCastArgument(x: inout Klass) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassBangCastArgument2(x: inout Klass?) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassQuestionCastArgument2(x: inout Klass?) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} }
import Aztec import Foundation public extension Element { static let gutenpack = Element("gutenpack") } public class GutenpackConverter: ElementConverter { // MARK: - ElementConverter public func convert( _ element: ElementNode, inheriting attributes: [NSAttributedStringKey: Any], childrenSerializer serializeChildren: ChildrenSerializer) -> NSAttributedString { precondition(element.type == .gutenpack) let attachment = HTMLAttachment() let decoder = GutenbergAttributeDecoder() if let content = decoder.decodedAttribute(named: GutenbergAttributeNames.selfCloser, from: element) { attachment.rawHTML = String(content.prefix(upTo: content.index(before:content.endIndex))) attachment.rootTagName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in char != " " })) } else { let serializer = HTMLSerializer() attachment.rootTagName = element.name attachment.rawHTML = serializer.serialize(element) } return NSAttributedString(attachment: attachment, attributes: attributes) } } Remove double space. import Aztec import Foundation public extension Element { static let gutenpack = Element("gutenpack") } public class GutenpackConverter: ElementConverter { // MARK: - ElementConverter public func convert( _ element: ElementNode, inheriting attributes: [NSAttributedStringKey: Any], childrenSerializer serializeChildren: ChildrenSerializer) -> NSAttributedString { precondition(element.type == .gutenpack) let attachment = HTMLAttachment() let decoder = GutenbergAttributeDecoder() if let content = decoder.decodedAttribute(named: GutenbergAttributeNames.selfCloser, from: element) { attachment.rawHTML = String(content.prefix(upTo: content.index(before:content.endIndex))) attachment.rootTagName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in char != " " })) } else { let serializer = HTMLSerializer() attachment.rootTagName = element.name attachment.rawHTML = serializer.serialize(element) } return NSAttributedString(attachment: attachment, attributes: attributes) } }
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreImage import TensorFlowLite import UIKit /// A result from invoking the `Interpreter`. struct Result { let inferenceTime: Double let inferences: [Inference] } /// An inference from invoking the `Interpreter`. struct Inference { let confidence: Float let label: String } /// Information about a model file or labels file. typealias FileInfo = (name: String, extension: String) /// Information about the MobileNet model. enum MobileNet { static let modelInfo: FileInfo = (name: "mobilenet_quant_v1_224", extension: "tflite") static let labelsInfo: FileInfo = (name: "labels", extension: "txt") } /// This class handles all data preprocessing and makes calls to run inference on a given frame /// by invoking the `Interpreter`. It then formats the inferences obtained and returns the top N /// results for a successful inference. class ModelDataHandler { // MARK: - Public Properties /// The current thread count used by the TensorFlow Lite Interpreter. let threadCount: Int let resultCount = 3 let threadCountLimit = 10 // MARK: - Model Parameters let batchSize = 1 let inputChannels = 3 let inputWidth = 224 let inputHeight = 224 // MARK: - Private Properties /// List of labels from the given labels file. private var labels: [String] = [] /// TensorFlow Lite `Interpreter` object for performing inference on a given model. private var interpreter: Interpreter /// Information about the alpha component in RGBA data. private let alphaComponent = (baseOffset: 4, moduloRemainder: 3) // MARK: - Initialization /// A failable initializer for `ModelDataHandler`. A new instance is created if the model and /// labels files are successfully loaded from the app's main bundle. Default `threadCount` is 1. init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) { let modelFilename = modelFileInfo.name // Construct the path to the model file. guard let modelPath = Bundle.main.path( forResource: modelFilename, ofType: modelFileInfo.extension ) else { print("Failed to load the model file with name: \(modelFilename).") return nil } // Specify the options for the `Interpreter`. self.threadCount = threadCount var options = InterpreterOptions() options.threadCount = threadCount options.isErrorLoggingEnabled = true do { // Create the `Interpreter`. interpreter = try Interpreter(modelPath: modelPath, options: options) } catch let error { print("Failed to create the interpreter with error: \(error.localizedDescription)") return nil } // Load the classes listed in the labels file. loadLabels(fileInfo: labelsFileInfo) } // MARK: - Public Methods /// Performs image preprocessing, invokes the `Interpreter`, and process the inference results. func runModel(onFrame pixelBuffer: CVPixelBuffer) -> Result? { let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer) assert(sourcePixelFormat == kCVPixelFormatType_32ARGB || sourcePixelFormat == kCVPixelFormatType_32BGRA || sourcePixelFormat == kCVPixelFormatType_32RGBA) let imageChannels = 4 assert(imageChannels >= inputChannels) // Crops the image to the biggest square in the center and scales it down to model dimensions. let scaledSize = CGSize(width: inputWidth, height: inputHeight) guard let thumbnailPixelBuffer = pixelBuffer.centerThumbnail(ofSize: scaledSize) else { return nil } let interval: TimeInterval let outputTensor: Tensor do { // Allocate memory for the model's input `Tensor`s. try interpreter.allocateTensors() let inputTensor = try interpreter.input(at: 0) // Remove the alpha component from the image buffer to get the RGB data. guard let rgbData = rgbDataFromBuffer( thumbnailPixelBuffer, byteCount: batchSize * inputWidth * inputHeight * inputChannels, isModelQuantized: inputTensor.dataType == .uInt8 ) else { print("Failed to convert the image buffer to RGB data.") return nil } // Copy the RGB data to the input `Tensor`. try interpreter.copy(rgbData, toInputAt: 0) // Run inference by invoking the `Interpreter`. let startDate = Date() try interpreter.invoke() interval = Date().timeIntervalSince(startDate) * 1000 // Get the output `Tensor` to process the inference results. outputTensor = try interpreter.output(at: 0) } catch let error { print("Failed to invoke the interpreter with error: \(error.localizedDescription)") return nil } let results: [Float] switch outputTensor.dataType { case .uInt8: guard let quantization = outputTensor.quantizationParameters else { print("No results returned because the quantization values for the output tensor are nil.") return nil } let quantizedResults = [UInt8](outputTensor.data) results = quantizedResults.map { quantization.scale * Float(Int($0) - quantization.zeroPoint) } case .float32: results = [Float32](unsafeData: outputTensor.data) ?? [] case .bool, .int16, .int32, .int64: print("Output tensor data type \(outputTensor.dataType) is unsupported.") return nil } // Process the results. let topNInferences = getTopN(results: results) // Return the inference time and inference results. return Result(inferenceTime: interval, inferences: topNInferences) } // MARK: - Private Methods /// Returns the top N inference results sorted in descending order. private func getTopN(results: [Float]) -> [Inference] { // Create a zipped array of tuples [(labelIndex: Int, confidence: Float)]. let zippedResults = zip(labels.indices, results) // Sort the zipped results by confidence value in descending order. let sortedResults = zippedResults.sorted { $0.1 > $1.1 }.prefix(resultCount) // Return the `Inference` results. return sortedResults.map { result in Inference(confidence: result.1, label: labels[result.0]) } } /// Loads the labels from the labels file and stores them in the `labels` property. private func loadLabels(fileInfo: FileInfo) { let filename = fileInfo.name let fileExtension = fileInfo.extension guard let fileURL = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { fatalError("Labels file not found in bundle. Please add a labels file with name " + "\(filename).\(fileExtension) and try again.") } do { let contents = try String(contentsOf: fileURL, encoding: .utf8) labels = contents.components(separatedBy: .newlines) } catch { fatalError("Labels file named \(filename).\(fileExtension) cannot be read. Please add a " + "valid labels file and try again.") } } /// Returns the RGB data representation of the given image buffer with the specified `byteCount`. /// /// - Parameters /// - buffer: The pixel buffer to convert to RGB data. /// - byteCount: The expected byte count for the RGB data calculated using the values that the /// model was trained on: `batchSize * imageWidth * imageHeight * componentsCount`. /// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than /// floating point values). /// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be /// converted. private func rgbDataFromBuffer( _ buffer: CVPixelBuffer, byteCount: Int, isModelQuantized: Bool ) -> Data? { CVPixelBufferLockBaseAddress(buffer, .readOnly) defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) } guard let mutableRawPointer = CVPixelBufferGetBaseAddress(buffer) else { return nil } let count = CVPixelBufferGetDataSize(buffer) let bufferData = Data(bytesNoCopy: mutableRawPointer, count: count, deallocator: .none) var rgbBytes = [UInt8](repeating: 0, count: byteCount) var index = 0 for component in bufferData.enumerated() { let offset = component.offset let isAlphaComponent = (offset % alphaComponent.baseOffset) == alphaComponent.moduloRemainder guard !isAlphaComponent else { continue } rgbBytes[index] = component.element index += 1 } if isModelQuantized { return Data(bytes: rgbBytes) } return Data(copyingBufferOf: rgbBytes.map { Float($0) / 255.0 }) } } // MARK: - Extensions extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } } extension Array { /// Creates a new array from the bytes of the given unsafe data. /// /// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit /// with no indirection or reference-counting operations; otherwise, copying the raw bytes in /// the `unsafeData`'s buffer to a new array returns an unsafe copy. /// - Note: Returns `nil` if `unsafeData.count` is not a multiple of /// `MemoryLayout<Element>.stride`. /// - Parameter unsafeData: The data containing the bytes to turn into an array. init?(unsafeData: Data) { guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil } #if swift(>=5.0) self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) } #else self = unsafeData.withUnsafeBytes { .init(UnsafeBufferPointer<Element>( start: $0, count: unsafeData.count / MemoryLayout<Element>.stride )) } #endif // swift(>=5.0) } } Removes the `isErrorLoggingEnabled` property from the `InterpreterOptions` struct. Error logging is enabled by default to match ObjC behavior. PiperOrigin-RevId: 248392591 // Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreImage import TensorFlowLite import UIKit /// A result from invoking the `Interpreter`. struct Result { let inferenceTime: Double let inferences: [Inference] } /// An inference from invoking the `Interpreter`. struct Inference { let confidence: Float let label: String } /// Information about a model file or labels file. typealias FileInfo = (name: String, extension: String) /// Information about the MobileNet model. enum MobileNet { static let modelInfo: FileInfo = (name: "mobilenet_quant_v1_224", extension: "tflite") static let labelsInfo: FileInfo = (name: "labels", extension: "txt") } /// This class handles all data preprocessing and makes calls to run inference on a given frame /// by invoking the `Interpreter`. It then formats the inferences obtained and returns the top N /// results for a successful inference. class ModelDataHandler { // MARK: - Public Properties /// The current thread count used by the TensorFlow Lite Interpreter. let threadCount: Int let resultCount = 3 let threadCountLimit = 10 // MARK: - Model Parameters let batchSize = 1 let inputChannels = 3 let inputWidth = 224 let inputHeight = 224 // MARK: - Private Properties /// List of labels from the given labels file. private var labels: [String] = [] /// TensorFlow Lite `Interpreter` object for performing inference on a given model. private var interpreter: Interpreter /// Information about the alpha component in RGBA data. private let alphaComponent = (baseOffset: 4, moduloRemainder: 3) // MARK: - Initialization /// A failable initializer for `ModelDataHandler`. A new instance is created if the model and /// labels files are successfully loaded from the app's main bundle. Default `threadCount` is 1. init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) { let modelFilename = modelFileInfo.name // Construct the path to the model file. guard let modelPath = Bundle.main.path( forResource: modelFilename, ofType: modelFileInfo.extension ) else { print("Failed to load the model file with name: \(modelFilename).") return nil } // Specify the options for the `Interpreter`. self.threadCount = threadCount var options = InterpreterOptions() options.threadCount = threadCount do { // Create the `Interpreter`. interpreter = try Interpreter(modelPath: modelPath, options: options) } catch let error { print("Failed to create the interpreter with error: \(error.localizedDescription)") return nil } // Load the classes listed in the labels file. loadLabels(fileInfo: labelsFileInfo) } // MARK: - Public Methods /// Performs image preprocessing, invokes the `Interpreter`, and process the inference results. func runModel(onFrame pixelBuffer: CVPixelBuffer) -> Result? { let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer) assert(sourcePixelFormat == kCVPixelFormatType_32ARGB || sourcePixelFormat == kCVPixelFormatType_32BGRA || sourcePixelFormat == kCVPixelFormatType_32RGBA) let imageChannels = 4 assert(imageChannels >= inputChannels) // Crops the image to the biggest square in the center and scales it down to model dimensions. let scaledSize = CGSize(width: inputWidth, height: inputHeight) guard let thumbnailPixelBuffer = pixelBuffer.centerThumbnail(ofSize: scaledSize) else { return nil } let interval: TimeInterval let outputTensor: Tensor do { // Allocate memory for the model's input `Tensor`s. try interpreter.allocateTensors() let inputTensor = try interpreter.input(at: 0) // Remove the alpha component from the image buffer to get the RGB data. guard let rgbData = rgbDataFromBuffer( thumbnailPixelBuffer, byteCount: batchSize * inputWidth * inputHeight * inputChannels, isModelQuantized: inputTensor.dataType == .uInt8 ) else { print("Failed to convert the image buffer to RGB data.") return nil } // Copy the RGB data to the input `Tensor`. try interpreter.copy(rgbData, toInputAt: 0) // Run inference by invoking the `Interpreter`. let startDate = Date() try interpreter.invoke() interval = Date().timeIntervalSince(startDate) * 1000 // Get the output `Tensor` to process the inference results. outputTensor = try interpreter.output(at: 0) } catch let error { print("Failed to invoke the interpreter with error: \(error.localizedDescription)") return nil } let results: [Float] switch outputTensor.dataType { case .uInt8: guard let quantization = outputTensor.quantizationParameters else { print("No results returned because the quantization values for the output tensor are nil.") return nil } let quantizedResults = [UInt8](outputTensor.data) results = quantizedResults.map { quantization.scale * Float(Int($0) - quantization.zeroPoint) } case .float32: results = [Float32](unsafeData: outputTensor.data) ?? [] case .bool, .int16, .int32, .int64: print("Output tensor data type \(outputTensor.dataType) is unsupported.") return nil } // Process the results. let topNInferences = getTopN(results: results) // Return the inference time and inference results. return Result(inferenceTime: interval, inferences: topNInferences) } // MARK: - Private Methods /// Returns the top N inference results sorted in descending order. private func getTopN(results: [Float]) -> [Inference] { // Create a zipped array of tuples [(labelIndex: Int, confidence: Float)]. let zippedResults = zip(labels.indices, results) // Sort the zipped results by confidence value in descending order. let sortedResults = zippedResults.sorted { $0.1 > $1.1 }.prefix(resultCount) // Return the `Inference` results. return sortedResults.map { result in Inference(confidence: result.1, label: labels[result.0]) } } /// Loads the labels from the labels file and stores them in the `labels` property. private func loadLabels(fileInfo: FileInfo) { let filename = fileInfo.name let fileExtension = fileInfo.extension guard let fileURL = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { fatalError("Labels file not found in bundle. Please add a labels file with name " + "\(filename).\(fileExtension) and try again.") } do { let contents = try String(contentsOf: fileURL, encoding: .utf8) labels = contents.components(separatedBy: .newlines) } catch { fatalError("Labels file named \(filename).\(fileExtension) cannot be read. Please add a " + "valid labels file and try again.") } } /// Returns the RGB data representation of the given image buffer with the specified `byteCount`. /// /// - Parameters /// - buffer: The pixel buffer to convert to RGB data. /// - byteCount: The expected byte count for the RGB data calculated using the values that the /// model was trained on: `batchSize * imageWidth * imageHeight * componentsCount`. /// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than /// floating point values). /// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be /// converted. private func rgbDataFromBuffer( _ buffer: CVPixelBuffer, byteCount: Int, isModelQuantized: Bool ) -> Data? { CVPixelBufferLockBaseAddress(buffer, .readOnly) defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) } guard let mutableRawPointer = CVPixelBufferGetBaseAddress(buffer) else { return nil } let count = CVPixelBufferGetDataSize(buffer) let bufferData = Data(bytesNoCopy: mutableRawPointer, count: count, deallocator: .none) var rgbBytes = [UInt8](repeating: 0, count: byteCount) var index = 0 for component in bufferData.enumerated() { let offset = component.offset let isAlphaComponent = (offset % alphaComponent.baseOffset) == alphaComponent.moduloRemainder guard !isAlphaComponent else { continue } rgbBytes[index] = component.element index += 1 } if isModelQuantized { return Data(bytes: rgbBytes) } return Data(copyingBufferOf: rgbBytes.map { Float($0) / 255.0 }) } } // MARK: - Extensions extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } } extension Array { /// Creates a new array from the bytes of the given unsafe data. /// /// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit /// with no indirection or reference-counting operations; otherwise, copying the raw bytes in /// the `unsafeData`'s buffer to a new array returns an unsafe copy. /// - Note: Returns `nil` if `unsafeData.count` is not a multiple of /// `MemoryLayout<Element>.stride`. /// - Parameter unsafeData: The data containing the bytes to turn into an array. init?(unsafeData: Data) { guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil } #if swift(>=5.0) self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) } #else self = unsafeData.withUnsafeBytes { .init(UnsafeBufferPointer<Element>( start: $0, count: unsafeData.count / MemoryLayout<Element>.stride )) } #endif // swift(>=5.0) } }
// // TokenListViewController.swift // breadwallet // // Created by Adrian Corscadden on 2018-04-08. // Copyright © 2018 breadwallet LLC. All rights reserved. // import UIKit enum TokenListType { case manage case add var title: String { switch self { case .manage: return S.TokenList.manageTitle case .add: return S.TokenList.addTitle } } var addTitle: String { switch self { case .manage: return S.TokenList.show case .add: return S.TokenList.add } } var removeTitle: String { switch self { case .manage: return S.TokenList.hide case .add: return S.TokenList.remove } } } class EditWalletsViewController : UITableViewController { private let type: TokenListType private let cellIdentifier = "CellIdentifier" private let kvStore: BRReplicatedKVStore private let metaData: CurrencyListMetaData private var tokens = [StoredTokenData]() { didSet { tableView.reloadData() } } private var tokenAddressesToBeAdded = [String]() { didSet { tokens = tokens.map { var token = $0 if tokenAddressesToBeAdded.contains($0.address) { token.isHidden = false } return token } } } private var tokenAddressesToBeRemoved = [String]() { didSet { tokens = tokens.map { var token = $0 if tokenAddressesToBeRemoved.contains($0.address) { token.isHidden = true } return token } } } init(type: TokenListType, kvStore: BRReplicatedKVStore) { self.type = type self.kvStore = kvStore self.metaData = CurrencyListMetaData(kvStore: kvStore)! super.init(style: .plain) } override func viewDidLoad() { title = type.title tableView.register(TokenCell.self, forCellReuseIdentifier: cellIdentifier) tableView.separatorStyle = .none StoredTokenData.fetchTokens(callback: { [weak self] in guard let `self` = self else { return } switch self.type { case .add: self.tokens = $0.filter { !self.metaData.previouslyAddedTokenAddresses.contains($0.address) } case .manage: let addedTokens = $0.filter { self.metaData.enabledTokenAddresses.contains($0.address) } var hiddenTokens = $0.filter { self.metaData.hiddenTokenAddresses.contains($0.address) } hiddenTokens = hiddenTokens.map { var token = $0 token.isHidden = true return token } self.tokens = addedTokens + hiddenTokens } }) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) reconcileChanges() navigationController?.navigationBar.backgroundColor = nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.backgroundColor = .white } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tokens.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TokenCell else { return UITableViewCell() } cell.set(token: tokens[indexPath.row], listType: type) cell.didAddToken = { [unowned self] address in if !self.tokenAddressesToBeAdded.contains(address) { self.tokenAddressesToBeAdded.append(address) } self.tokenAddressesToBeRemoved = self.tokenAddressesToBeRemoved.filter { $0 != address } } cell.didRemoveToken = { [unowned self] address in self.tokenAddressesToBeAdded = self.tokenAddressesToBeAdded.filter { $0 != address } if !self.tokenAddressesToBeRemoved.contains(address) { self.tokenAddressesToBeRemoved.append(address) } } return cell } private func reconcileChanges() { switch type { case .add: addAddedTokens() case .manage: removeRemovedTokens() addAddedTokens() } } private func addAddedTokens() { guard tokenAddressesToBeAdded.count > 0 else { return } var currentWalletCount = Store.state.wallets.values.count let newWallets: [String: WalletState] = tokens.filter { return self.tokenAddressesToBeAdded.contains($0.address) }.map { ERC20Token(tokenData: $0) }.reduce([String: WalletState]()) { (dictionary, currency) -> [String: WalletState] in var dictionary = dictionary dictionary[currency.code] = WalletState.initial(currency, displayOrder: currentWalletCount) currentWalletCount = currentWalletCount + 1 return dictionary } metaData.addTokenAddresses(addresses: tokenAddressesToBeAdded) save() Store.perform(action: ManageWallets.addWallets(newWallets)) } private func removeRemovedTokens() { guard tokenAddressesToBeRemoved.count > 0 else { return } metaData.removeTokenAddresses(addresses: tokenAddressesToBeRemoved) save() Store.perform(action: ManageWallets.removeTokenAddresses(tokenAddressesToBeRemoved)) } private func save() { do { let _ = try kvStore.set(metaData) } catch let error { print("error setting wallet info: \(error)") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct StoredTokenData : Codable { let address: String let name: String let code: String let colors: [String] let decimal: String //extras not in json var isHidden = false private enum CodingKeys: String, CodingKey { case address case name case code case colors case decimal } } extension StoredTokenData { static func fetchTokens(callback: @escaping ([StoredTokenData])->Void) { DispatchQueue.global(qos: .utility).async { do { let path = Bundle.main.path(forResource: "tokens", ofType: "json") let data = try Data(contentsOf: URL(fileURLWithPath: path!)) var tokens = try JSONDecoder().decode([StoredTokenData].self, from: data) if E.isDebug { tokens.append(StoredTokenData.tst) tokens.append(StoredTokenData.viu) } DispatchQueue.main.async { callback(tokens) } } catch let e { print("json errro: \(e)") } } } } extension StoredTokenData { static var tst: StoredTokenData { return StoredTokenData(address: E.isTestnet ? "0x722dd3f80bac40c951b51bdd28dd19d435762180" : "0x3efd578b271d034a69499e4a2d933c631d44b9ad", name: "Test Token", code: "TST", colors: ["2FB8E6", "2FB8E6"], decimal: "18", isHidden: false) } //this is a random token I was airdropped...using for testing static var viu: StoredTokenData { return StoredTokenData(address: "0x519475b31653e46d20cd09f9fdcf3b12bdacb4f5", name: "VIU Token", code: "VIU", colors: ["2FB8E6", "2FB8E6"], decimal: "18", isHidden: false) } } Fix transparent status bar on manage wallet list // // TokenListViewController.swift // breadwallet // // Created by Adrian Corscadden on 2018-04-08. // Copyright © 2018 breadwallet LLC. All rights reserved. // import UIKit enum TokenListType { case manage case add var title: String { switch self { case .manage: return S.TokenList.manageTitle case .add: return S.TokenList.addTitle } } var addTitle: String { switch self { case .manage: return S.TokenList.show case .add: return S.TokenList.add } } var removeTitle: String { switch self { case .manage: return S.TokenList.hide case .add: return S.TokenList.remove } } } class EditWalletsViewController : UIViewController, UITableViewDelegate, UITableViewDataSource { private let type: TokenListType private let cellIdentifier = "CellIdentifier" private let kvStore: BRReplicatedKVStore private let metaData: CurrencyListMetaData private var tokens = [StoredTokenData]() { didSet { tableView.reloadData() } } private var tokenAddressesToBeAdded = [String]() { didSet { tokens = tokens.map { var token = $0 if tokenAddressesToBeAdded.contains($0.address) { token.isHidden = false } return token } } } private var tokenAddressesToBeRemoved = [String]() { didSet { tokens = tokens.map { var token = $0 if tokenAddressesToBeRemoved.contains($0.address) { token.isHidden = true } return token } } } private let tableView = UITableView() init(type: TokenListType, kvStore: BRReplicatedKVStore) { self.type = type self.kvStore = kvStore self.metaData = CurrencyListMetaData(kvStore: kvStore)! //super.init(style: .plain) super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { view.backgroundColor = .white view.addSubview(tableView) if #available(iOS 11.0, *) { tableView.constrain([ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)]) } else { tableView.constrain([ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)]) } tableView.delegate = self tableView.dataSource = self title = type.title tableView.register(TokenCell.self, forCellReuseIdentifier: cellIdentifier) tableView.separatorStyle = .none StoredTokenData.fetchTokens(callback: { [weak self] in guard let `self` = self else { return } switch self.type { case .add: self.tokens = $0.filter { !self.metaData.previouslyAddedTokenAddresses.contains($0.address) } case .manage: let addedTokens = $0.filter { self.metaData.enabledTokenAddresses.contains($0.address) } var hiddenTokens = $0.filter { self.metaData.hiddenTokenAddresses.contains($0.address) } hiddenTokens = hiddenTokens.map { var token = $0 token.isHidden = true return token } self.tokens = addedTokens + hiddenTokens } }) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) reconcileChanges() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tokens.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TokenCell else { return UITableViewCell() } cell.set(token: tokens[indexPath.row], listType: type) cell.didAddToken = { [unowned self] address in if !self.tokenAddressesToBeAdded.contains(address) { self.tokenAddressesToBeAdded.append(address) } self.tokenAddressesToBeRemoved = self.tokenAddressesToBeRemoved.filter { $0 != address } } cell.didRemoveToken = { [unowned self] address in self.tokenAddressesToBeAdded = self.tokenAddressesToBeAdded.filter { $0 != address } if !self.tokenAddressesToBeRemoved.contains(address) { self.tokenAddressesToBeRemoved.append(address) } } return cell } private func reconcileChanges() { switch type { case .add: addAddedTokens() case .manage: removeRemovedTokens() addAddedTokens() } } private func addAddedTokens() { guard tokenAddressesToBeAdded.count > 0 else { return } var currentWalletCount = Store.state.wallets.values.count let newWallets: [String: WalletState] = tokens.filter { return self.tokenAddressesToBeAdded.contains($0.address) }.map { ERC20Token(tokenData: $0) }.reduce([String: WalletState]()) { (dictionary, currency) -> [String: WalletState] in var dictionary = dictionary dictionary[currency.code] = WalletState.initial(currency, displayOrder: currentWalletCount) currentWalletCount = currentWalletCount + 1 return dictionary } metaData.addTokenAddresses(addresses: tokenAddressesToBeAdded) save() Store.perform(action: ManageWallets.addWallets(newWallets)) } private func removeRemovedTokens() { guard tokenAddressesToBeRemoved.count > 0 else { return } metaData.removeTokenAddresses(addresses: tokenAddressesToBeRemoved) save() Store.perform(action: ManageWallets.removeTokenAddresses(tokenAddressesToBeRemoved)) } private func save() { do { let _ = try kvStore.set(metaData) } catch let error { print("error setting wallet info: \(error)") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct StoredTokenData : Codable { let address: String let name: String let code: String let colors: [String] let decimal: String //extras not in json var isHidden = false private enum CodingKeys: String, CodingKey { case address case name case code case colors case decimal } } extension StoredTokenData { static func fetchTokens(callback: @escaping ([StoredTokenData])->Void) { DispatchQueue.global(qos: .utility).async { do { let path = Bundle.main.path(forResource: "tokens", ofType: "json") let data = try Data(contentsOf: URL(fileURLWithPath: path!)) var tokens = try JSONDecoder().decode([StoredTokenData].self, from: data) if E.isDebug { tokens.append(StoredTokenData.tst) tokens.append(StoredTokenData.viu) } DispatchQueue.main.async { callback(tokens) } } catch let e { print("json errro: \(e)") } } } } extension StoredTokenData { static var tst: StoredTokenData { return StoredTokenData(address: E.isTestnet ? "0x722dd3f80bac40c951b51bdd28dd19d435762180" : "0x3efd578b271d034a69499e4a2d933c631d44b9ad", name: "Test Token", code: "TST", colors: ["2FB8E6", "2FB8E6"], decimal: "18", isHidden: false) } //this is a random token I was airdropped...using for testing static var viu: StoredTokenData { return StoredTokenData(address: "0x519475b31653e46d20cd09f9fdcf3b12bdacb4f5", name: "VIU Token", code: "VIU", colors: ["2FB8E6", "2FB8E6"], decimal: "18", isHidden: false) } }
// // TransactionDetailCollectionViewCell.swift // breadwallet // // Created by Adrian Corscadden on 2017-02-09. // Copyright © 2017 breadwallet LLC. All rights reserved. // import UIKit class TransactionDetailCollectionViewCell : UICollectionViewCell { //MARK: - Public override init(frame: CGRect) { super.init(frame: frame) setup() } func set(transaction: Transaction, isBtcSwapped: Bool, rate: Rate, rates: [Rate], maxDigits: Int) { timestamp.text = transaction.longTimestamp amount.text = String(format: transaction.direction.amountFormat, "\(transaction.amountDescription(isBtcSwapped: isBtcSwapped, rate: rate, maxDigits: maxDigits))") address.text = transaction.direction.addressText status.text = transaction.status comment.text = transaction.comment amountDetails.text = transaction.amountDetails(isBtcSwapped: isBtcSwapped, rate: rate, rates: rates, maxDigits: maxDigits) addressHeader.text = transaction.direction.addressHeader.capitalized fullAddress.text = transaction.toAddress ?? "" txHash.text = transaction.hash availability.isHidden = !transaction.shouldDisplayAvailableToSpend self.transaction = transaction self.rate = rate } var closeCallback: (() -> Void)? { didSet { header.closeCallback = closeCallback } } var kvStore: BRReplicatedKVStore? var transaction: Transaction? var rate: Rate? var store: Store? { didSet { if oldValue == nil { guard let store = store else { return } header.faqInfo = (store, ArticleIds.transactionDetails) } } } //MARK: - Private private let header = ModalHeaderView(title: S.TransactionDetails.title, style: .dark) private let timestamp = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let amount = UILabel(font: .customBold(size: 26.0), color: .darkText) private let address = UILabel(font: .customBold(size: 14.0), color: .darkText) private let separators = (0...4).map { _ in UIView(color: .secondaryShadow) } private let statusHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let status = UILabel.wrapping(font: .customBody(size: 13.0), color: .darkText) private let commentsHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let comment = UITextField() private let amountHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let amountDetails = UILabel.wrapping(font: .customBody(size: 13.0), color: .darkText) private let addressHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let fullAddress = UILabel(font: .customBody(size: 13.0), color: .darkText) private let headerHeight: CGFloat = 48.0 private let scrollViewContent = UIView() private let scrollView = UIScrollView() private let moreButton = UIButton(type: .system) private let moreContentView = UIView() private let txHash = UILabel(font: .customBody(size: 13.0), color: .darkText) private let txHashHeader = UILabel(font: .customBody(size: 14.0), color: .grayTextTint) private let availability = UILabel(font: .customBold(size: 13.0), color: .cameraGuidePositive) private func setup() { addSubviews() addConstraints() setData() } private func addSubviews() { contentView.addSubview(scrollView) contentView.addSubview(header) scrollView.addSubview(scrollViewContent) scrollViewContent.addSubview(timestamp) scrollViewContent.addSubview(amount) scrollViewContent.addSubview(address) separators.forEach { scrollViewContent.addSubview($0) } scrollViewContent.addSubview(statusHeader) scrollViewContent.addSubview(status) scrollViewContent.addSubview(availability) scrollViewContent.addSubview(commentsHeader) scrollViewContent.addSubview(comment) scrollViewContent.addSubview(amountHeader) scrollViewContent.addSubview(amountDetails) scrollViewContent.addSubview(addressHeader) scrollViewContent.addSubview(fullAddress) scrollViewContent.addSubview(moreContentView) moreContentView.addSubview(moreButton) } private func addConstraints() { header.constrainTopCorners(height: headerHeight) scrollView.constrain(toSuperviewEdges: UIEdgeInsets(top: headerHeight, left: 0, bottom: 0, right: 0)) scrollViewContent.constrain([ scrollViewContent.topAnchor.constraint(equalTo: scrollView.topAnchor), scrollViewContent.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), scrollViewContent.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), scrollViewContent.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), scrollViewContent.widthAnchor.constraint(equalTo: scrollView.widthAnchor) ]) timestamp.constrain([ timestamp.leadingAnchor.constraint(equalTo: scrollViewContent.leadingAnchor, constant: C.padding[2]), timestamp.topAnchor.constraint(equalTo: scrollViewContent.topAnchor, constant: C.padding[3]), timestamp.trailingAnchor.constraint(equalTo: scrollViewContent.trailingAnchor, constant: -C.padding[2]) ]) amount.constrain([ amount.leadingAnchor.constraint(equalTo: timestamp.leadingAnchor), amount.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), amount.topAnchor.constraint(equalTo: timestamp.bottomAnchor, constant: C.padding[1]) ]) address.constrain([ address.leadingAnchor.constraint(equalTo: amount.leadingAnchor), address.trailingAnchor.constraint(equalTo: amount.trailingAnchor), address.topAnchor.constraint(equalTo: amount.bottomAnchor) ]) separators[0].constrain([ separators[0].topAnchor.constraint(equalTo: address.bottomAnchor, constant: C.padding[2]), separators[0].leadingAnchor.constraint(equalTo: address.leadingAnchor), separators[0].trailingAnchor.constraint(equalTo: address.trailingAnchor), separators[0].heightAnchor.constraint(equalToConstant: 1.0)]) statusHeader.constrain([ statusHeader.topAnchor.constraint(equalTo: separators[0].bottomAnchor, constant: C.padding[2]), statusHeader.leadingAnchor.constraint(equalTo: separators[0].leadingAnchor), statusHeader.trailingAnchor.constraint(equalTo: separators[0].trailingAnchor) ]) status.constrain([ status.topAnchor.constraint(equalTo: statusHeader.bottomAnchor), status.leadingAnchor.constraint(equalTo: statusHeader.leadingAnchor), status.trailingAnchor.constraint(equalTo: statusHeader.trailingAnchor) ]) availability.constrain([ availability.topAnchor.constraint(equalTo: status.bottomAnchor), availability.leadingAnchor.constraint(equalTo: status.leadingAnchor)]) separators[1].constrain([ separators[1].topAnchor.constraint(equalTo: availability.bottomAnchor, constant: C.padding[2]), separators[1].leadingAnchor.constraint(equalTo: status.leadingAnchor), separators[1].trailingAnchor.constraint(equalTo: status.trailingAnchor), separators[1].heightAnchor.constraint(equalToConstant: 1.0) ]) commentsHeader.constrain([ commentsHeader.topAnchor.constraint(equalTo: separators[1].bottomAnchor, constant: C.padding[2]), commentsHeader.leadingAnchor.constraint(equalTo: separators[1].leadingAnchor), commentsHeader.trailingAnchor.constraint(equalTo: separators[1].trailingAnchor) ]) comment.constrain([ comment.topAnchor.constraint(equalTo: commentsHeader.bottomAnchor), comment.leadingAnchor.constraint(equalTo: commentsHeader.leadingAnchor), comment.trailingAnchor.constraint(equalTo: commentsHeader.trailingAnchor), comment.heightAnchor.constraint(greaterThanOrEqualToConstant: 44.0) ]) separators[2].constrain([ separators[2].topAnchor.constraint(equalTo: comment.bottomAnchor, constant: C.padding[2]), separators[2].leadingAnchor.constraint(equalTo: comment.leadingAnchor), separators[2].trailingAnchor.constraint(equalTo: comment.trailingAnchor), separators[2].heightAnchor.constraint(equalToConstant: 1.0) ]) amountHeader.constrain([ amountHeader.topAnchor.constraint(equalTo: separators[2].bottomAnchor, constant: C.padding[2]), amountHeader.leadingAnchor.constraint(equalTo: separators[2].leadingAnchor), amountHeader.trailingAnchor.constraint(equalTo: separators[2].trailingAnchor) ]) amountDetails.constrain([ amountDetails.topAnchor.constraint(equalTo: amountHeader.bottomAnchor), amountDetails.leadingAnchor.constraint(equalTo: amountHeader.leadingAnchor), amountDetails.trailingAnchor.constraint(equalTo: amountHeader.trailingAnchor) ]) separators[3].constrain([ separators[3].topAnchor.constraint(equalTo: amountDetails.bottomAnchor, constant: C.padding[2]), separators[3].leadingAnchor.constraint(equalTo: amountDetails.leadingAnchor), separators[3].trailingAnchor.constraint(equalTo: amountDetails.trailingAnchor), separators[3].heightAnchor.constraint(equalToConstant: 1.0) ]) addressHeader.constrain([ addressHeader.topAnchor.constraint(equalTo: separators[3].bottomAnchor, constant: C.padding[2]), addressHeader.leadingAnchor.constraint(equalTo: separators[3].leadingAnchor), addressHeader.trailingAnchor.constraint(equalTo: separators[3].trailingAnchor) ]) fullAddress.constrain([ fullAddress.topAnchor.constraint(equalTo: addressHeader.bottomAnchor), fullAddress.leadingAnchor.constraint(equalTo: addressHeader.leadingAnchor), fullAddress.trailingAnchor.constraint(equalTo: addressHeader.trailingAnchor) ]) separators[4].constrain([ separators[4].topAnchor.constraint(equalTo: fullAddress.bottomAnchor, constant: C.padding[2]), separators[4].leadingAnchor.constraint(equalTo: fullAddress.leadingAnchor), separators[4].trailingAnchor.constraint(equalTo: fullAddress.trailingAnchor), separators[4].heightAnchor.constraint(equalToConstant: 1.0) ]) moreContentView.constrain([ moreContentView.leadingAnchor.constraint(equalTo: separators[4].leadingAnchor), moreContentView.topAnchor.constraint(equalTo: separators[4].bottomAnchor, constant: C.padding[2]), moreContentView.trailingAnchor.constraint(equalTo: separators[4].trailingAnchor), moreContentView.bottomAnchor.constraint(equalTo: scrollViewContent.bottomAnchor, constant: -C.padding[2]) ]) moreButton.constrain([ moreButton.leadingAnchor.constraint(equalTo: moreContentView.leadingAnchor), moreButton.topAnchor.constraint(equalTo: moreContentView.topAnchor), moreButton.bottomAnchor.constraint(equalTo: moreContentView.bottomAnchor) ]) } private func setData() { backgroundColor = .white statusHeader.text = S.TransactionDetails.statusHeader commentsHeader.text = S.TransactionDetails.commentsHeader amountHeader.text = S.TransactionDetails.amountHeader availability.text = S.Transaction.available fullAddress.numberOfLines = 0 fullAddress.lineBreakMode = .byCharWrapping comment.font = .customBody(size: 13.0) comment.textColor = .darkText comment.contentVerticalAlignment = .top comment.returnKeyType = .done comment.delegate = self moreButton.setTitle(S.TransactionDetails.more, for: .normal) moreButton.tintColor = .grayTextTint moreButton.titleLabel?.font = .customBold(size: 14.0) txHash.numberOfLines = 0 txHash.lineBreakMode = .byCharWrapping moreButton.tap = { [weak self] in self?.addMoreView() } } private func addMoreView() { moreButton.removeFromSuperview() let newSeparator = UIView(color: .secondaryShadow) moreContentView.addSubview(newSeparator) moreContentView.addSubview(txHashHeader) moreContentView.addSubview(txHash) txHashHeader.text = S.TransactionDetails.txHashHeader txHashHeader.constrain([ txHashHeader.leadingAnchor.constraint(equalTo: moreContentView.leadingAnchor), txHashHeader.topAnchor.constraint(equalTo: moreContentView.topAnchor) ]) txHash.constrain([ txHash.leadingAnchor.constraint(equalTo: txHashHeader.leadingAnchor), txHash.topAnchor.constraint(equalTo: txHashHeader.bottomAnchor), txHash.trailingAnchor.constraint(equalTo: moreContentView.trailingAnchor) ]) newSeparator.constrain([ newSeparator.leadingAnchor.constraint(equalTo: txHash.leadingAnchor), newSeparator.topAnchor.constraint(equalTo: txHash.bottomAnchor, constant: C.padding[2]), newSeparator.trailingAnchor.constraint(equalTo: moreContentView.trailingAnchor), newSeparator.heightAnchor.constraint(equalToConstant: 1.0), newSeparator.bottomAnchor.constraint(equalTo: moreContentView.bottomAnchor) ]) let gr = UITapGestureRecognizer(target: self, action: #selector(tapTxHash)) txHash.addGestureRecognizer(gr) txHash.isUserInteractionEnabled = true //Scroll to expaned more view scrollView.layoutIfNeeded() if scrollView.contentSize.height > scrollView.bounds.height { let point = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height) self.scrollView.setContentOffset(point, animated: true) } } @objc private func tapTxHash() { guard let hash = transaction?.hash else { return } UIPasteboard.general.string = hash } override func layoutSubviews() { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0)).cgPath let maskLayer = CAShapeLayer() maskLayer.path = path layer.mask = maskLayer } fileprivate func saveComment(comment: String) { guard let kvStore = self.kvStore else { return } if let metaData = transaction?.metaData { metaData.comment = comment do { let _ = try kvStore.set(metaData) } catch let error { print("could not update metadata: \(error)") } } else { guard let rate = self.rate else { return } guard let transaction = self.transaction else { return } let newMetaData = BRTxMetadataObject(transaction: transaction.rawTransaction, exchangeRate: rate.rate, exchangeRateCurrency: rate.code, feeRate: 0.0, deviceId: UserDefaults.standard.deviceID) newMetaData.comment = comment do { let _ = try kvStore.set(newMetaData) } catch let error { print("could not update metadata: \(error)") } } NotificationCenter.default.post(name: .WalletTxStatusUpdateNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TransactionDetailCollectionViewCell : UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text else { return } saveComment(comment: text) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let count = (textField.text ?? "").utf8.count + string.utf8.count if count > C.maxMemoLength { return false } else { return true } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } Make amount label in tx details scale for large amounts // // TransactionDetailCollectionViewCell.swift // breadwallet // // Created by Adrian Corscadden on 2017-02-09. // Copyright © 2017 breadwallet LLC. All rights reserved. // import UIKit class TransactionDetailCollectionViewCell : UICollectionViewCell { //MARK: - Public override init(frame: CGRect) { super.init(frame: frame) setup() } func set(transaction: Transaction, isBtcSwapped: Bool, rate: Rate, rates: [Rate], maxDigits: Int) { timestamp.text = transaction.longTimestamp amount.text = String(format: transaction.direction.amountFormat, "\(transaction.amountDescription(isBtcSwapped: isBtcSwapped, rate: rate, maxDigits: maxDigits))") address.text = transaction.direction.addressText status.text = transaction.status comment.text = transaction.comment amountDetails.text = transaction.amountDetails(isBtcSwapped: isBtcSwapped, rate: rate, rates: rates, maxDigits: maxDigits) addressHeader.text = transaction.direction.addressHeader.capitalized fullAddress.text = transaction.toAddress ?? "" txHash.text = transaction.hash availability.isHidden = !transaction.shouldDisplayAvailableToSpend self.transaction = transaction self.rate = rate } var closeCallback: (() -> Void)? { didSet { header.closeCallback = closeCallback } } var kvStore: BRReplicatedKVStore? var transaction: Transaction? var rate: Rate? var store: Store? { didSet { if oldValue == nil { guard let store = store else { return } header.faqInfo = (store, ArticleIds.transactionDetails) } } } //MARK: - Private private let header = ModalHeaderView(title: S.TransactionDetails.title, style: .dark) private let timestamp = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let amount = UILabel(font: .customBold(size: 26.0), color: .darkText) private let address = UILabel(font: .customBold(size: 14.0), color: .darkText) private let separators = (0...4).map { _ in UIView(color: .secondaryShadow) } private let statusHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let status = UILabel.wrapping(font: .customBody(size: 13.0), color: .darkText) private let commentsHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let comment = UITextField() private let amountHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let amountDetails = UILabel.wrapping(font: .customBody(size: 13.0), color: .darkText) private let addressHeader = UILabel(font: .customBold(size: 14.0), color: .grayTextTint) private let fullAddress = UILabel(font: .customBody(size: 13.0), color: .darkText) private let headerHeight: CGFloat = 48.0 private let scrollViewContent = UIView() private let scrollView = UIScrollView() private let moreButton = UIButton(type: .system) private let moreContentView = UIView() private let txHash = UILabel(font: .customBody(size: 13.0), color: .darkText) private let txHashHeader = UILabel(font: .customBody(size: 14.0), color: .grayTextTint) private let availability = UILabel(font: .customBold(size: 13.0), color: .cameraGuidePositive) private func setup() { addSubviews() addConstraints() setData() } private func addSubviews() { contentView.addSubview(scrollView) contentView.addSubview(header) scrollView.addSubview(scrollViewContent) scrollViewContent.addSubview(timestamp) scrollViewContent.addSubview(amount) scrollViewContent.addSubview(address) separators.forEach { scrollViewContent.addSubview($0) } scrollViewContent.addSubview(statusHeader) scrollViewContent.addSubview(status) scrollViewContent.addSubview(availability) scrollViewContent.addSubview(commentsHeader) scrollViewContent.addSubview(comment) scrollViewContent.addSubview(amountHeader) scrollViewContent.addSubview(amountDetails) scrollViewContent.addSubview(addressHeader) scrollViewContent.addSubview(fullAddress) scrollViewContent.addSubview(moreContentView) moreContentView.addSubview(moreButton) } private func addConstraints() { header.constrainTopCorners(height: headerHeight) scrollView.constrain(toSuperviewEdges: UIEdgeInsets(top: headerHeight, left: 0, bottom: 0, right: 0)) scrollViewContent.constrain([ scrollViewContent.topAnchor.constraint(equalTo: scrollView.topAnchor), scrollViewContent.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), scrollViewContent.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), scrollViewContent.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), scrollViewContent.widthAnchor.constraint(equalTo: scrollView.widthAnchor) ]) timestamp.constrain([ timestamp.leadingAnchor.constraint(equalTo: scrollViewContent.leadingAnchor, constant: C.padding[2]), timestamp.topAnchor.constraint(equalTo: scrollViewContent.topAnchor, constant: C.padding[3]), timestamp.trailingAnchor.constraint(equalTo: scrollViewContent.trailingAnchor, constant: -C.padding[2]) ]) amount.constrain([ amount.leadingAnchor.constraint(equalTo: timestamp.leadingAnchor), amount.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), amount.topAnchor.constraint(equalTo: timestamp.bottomAnchor, constant: C.padding[1]) ]) address.constrain([ address.leadingAnchor.constraint(equalTo: amount.leadingAnchor), address.trailingAnchor.constraint(equalTo: amount.trailingAnchor), address.topAnchor.constraint(equalTo: amount.bottomAnchor) ]) separators[0].constrain([ separators[0].topAnchor.constraint(equalTo: address.bottomAnchor, constant: C.padding[2]), separators[0].leadingAnchor.constraint(equalTo: address.leadingAnchor), separators[0].trailingAnchor.constraint(equalTo: address.trailingAnchor), separators[0].heightAnchor.constraint(equalToConstant: 1.0)]) statusHeader.constrain([ statusHeader.topAnchor.constraint(equalTo: separators[0].bottomAnchor, constant: C.padding[2]), statusHeader.leadingAnchor.constraint(equalTo: separators[0].leadingAnchor), statusHeader.trailingAnchor.constraint(equalTo: separators[0].trailingAnchor) ]) status.constrain([ status.topAnchor.constraint(equalTo: statusHeader.bottomAnchor), status.leadingAnchor.constraint(equalTo: statusHeader.leadingAnchor), status.trailingAnchor.constraint(equalTo: statusHeader.trailingAnchor) ]) availability.constrain([ availability.topAnchor.constraint(equalTo: status.bottomAnchor), availability.leadingAnchor.constraint(equalTo: status.leadingAnchor)]) separators[1].constrain([ separators[1].topAnchor.constraint(equalTo: availability.bottomAnchor, constant: C.padding[2]), separators[1].leadingAnchor.constraint(equalTo: status.leadingAnchor), separators[1].trailingAnchor.constraint(equalTo: status.trailingAnchor), separators[1].heightAnchor.constraint(equalToConstant: 1.0) ]) commentsHeader.constrain([ commentsHeader.topAnchor.constraint(equalTo: separators[1].bottomAnchor, constant: C.padding[2]), commentsHeader.leadingAnchor.constraint(equalTo: separators[1].leadingAnchor), commentsHeader.trailingAnchor.constraint(equalTo: separators[1].trailingAnchor) ]) comment.constrain([ comment.topAnchor.constraint(equalTo: commentsHeader.bottomAnchor), comment.leadingAnchor.constraint(equalTo: commentsHeader.leadingAnchor), comment.trailingAnchor.constraint(equalTo: commentsHeader.trailingAnchor), comment.heightAnchor.constraint(greaterThanOrEqualToConstant: 44.0) ]) separators[2].constrain([ separators[2].topAnchor.constraint(equalTo: comment.bottomAnchor, constant: C.padding[2]), separators[2].leadingAnchor.constraint(equalTo: comment.leadingAnchor), separators[2].trailingAnchor.constraint(equalTo: comment.trailingAnchor), separators[2].heightAnchor.constraint(equalToConstant: 1.0) ]) amountHeader.constrain([ amountHeader.topAnchor.constraint(equalTo: separators[2].bottomAnchor, constant: C.padding[2]), amountHeader.leadingAnchor.constraint(equalTo: separators[2].leadingAnchor), amountHeader.trailingAnchor.constraint(equalTo: separators[2].trailingAnchor) ]) amountDetails.constrain([ amountDetails.topAnchor.constraint(equalTo: amountHeader.bottomAnchor), amountDetails.leadingAnchor.constraint(equalTo: amountHeader.leadingAnchor), amountDetails.trailingAnchor.constraint(equalTo: amountHeader.trailingAnchor) ]) separators[3].constrain([ separators[3].topAnchor.constraint(equalTo: amountDetails.bottomAnchor, constant: C.padding[2]), separators[3].leadingAnchor.constraint(equalTo: amountDetails.leadingAnchor), separators[3].trailingAnchor.constraint(equalTo: amountDetails.trailingAnchor), separators[3].heightAnchor.constraint(equalToConstant: 1.0) ]) addressHeader.constrain([ addressHeader.topAnchor.constraint(equalTo: separators[3].bottomAnchor, constant: C.padding[2]), addressHeader.leadingAnchor.constraint(equalTo: separators[3].leadingAnchor), addressHeader.trailingAnchor.constraint(equalTo: separators[3].trailingAnchor) ]) fullAddress.constrain([ fullAddress.topAnchor.constraint(equalTo: addressHeader.bottomAnchor), fullAddress.leadingAnchor.constraint(equalTo: addressHeader.leadingAnchor), fullAddress.trailingAnchor.constraint(equalTo: addressHeader.trailingAnchor) ]) separators[4].constrain([ separators[4].topAnchor.constraint(equalTo: fullAddress.bottomAnchor, constant: C.padding[2]), separators[4].leadingAnchor.constraint(equalTo: fullAddress.leadingAnchor), separators[4].trailingAnchor.constraint(equalTo: fullAddress.trailingAnchor), separators[4].heightAnchor.constraint(equalToConstant: 1.0) ]) moreContentView.constrain([ moreContentView.leadingAnchor.constraint(equalTo: separators[4].leadingAnchor), moreContentView.topAnchor.constraint(equalTo: separators[4].bottomAnchor, constant: C.padding[2]), moreContentView.trailingAnchor.constraint(equalTo: separators[4].trailingAnchor), moreContentView.bottomAnchor.constraint(equalTo: scrollViewContent.bottomAnchor, constant: -C.padding[2]) ]) moreButton.constrain([ moreButton.leadingAnchor.constraint(equalTo: moreContentView.leadingAnchor), moreButton.topAnchor.constraint(equalTo: moreContentView.topAnchor), moreButton.bottomAnchor.constraint(equalTo: moreContentView.bottomAnchor) ]) } private func setData() { backgroundColor = .white statusHeader.text = S.TransactionDetails.statusHeader commentsHeader.text = S.TransactionDetails.commentsHeader amountHeader.text = S.TransactionDetails.amountHeader availability.text = S.Transaction.available fullAddress.numberOfLines = 0 fullAddress.lineBreakMode = .byCharWrapping comment.font = .customBody(size: 13.0) comment.textColor = .darkText comment.contentVerticalAlignment = .top comment.returnKeyType = .done comment.delegate = self moreButton.setTitle(S.TransactionDetails.more, for: .normal) moreButton.tintColor = .grayTextTint moreButton.titleLabel?.font = .customBold(size: 14.0) txHash.numberOfLines = 0 txHash.lineBreakMode = .byCharWrapping moreButton.tap = { [weak self] in self?.addMoreView() } amount.minimumScaleFactor = 0.5 amount.adjustsFontSizeToFitWidth = true } private func addMoreView() { moreButton.removeFromSuperview() let newSeparator = UIView(color: .secondaryShadow) moreContentView.addSubview(newSeparator) moreContentView.addSubview(txHashHeader) moreContentView.addSubview(txHash) txHashHeader.text = S.TransactionDetails.txHashHeader txHashHeader.constrain([ txHashHeader.leadingAnchor.constraint(equalTo: moreContentView.leadingAnchor), txHashHeader.topAnchor.constraint(equalTo: moreContentView.topAnchor) ]) txHash.constrain([ txHash.leadingAnchor.constraint(equalTo: txHashHeader.leadingAnchor), txHash.topAnchor.constraint(equalTo: txHashHeader.bottomAnchor), txHash.trailingAnchor.constraint(equalTo: moreContentView.trailingAnchor) ]) newSeparator.constrain([ newSeparator.leadingAnchor.constraint(equalTo: txHash.leadingAnchor), newSeparator.topAnchor.constraint(equalTo: txHash.bottomAnchor, constant: C.padding[2]), newSeparator.trailingAnchor.constraint(equalTo: moreContentView.trailingAnchor), newSeparator.heightAnchor.constraint(equalToConstant: 1.0), newSeparator.bottomAnchor.constraint(equalTo: moreContentView.bottomAnchor) ]) let gr = UITapGestureRecognizer(target: self, action: #selector(tapTxHash)) txHash.addGestureRecognizer(gr) txHash.isUserInteractionEnabled = true //Scroll to expaned more view scrollView.layoutIfNeeded() if scrollView.contentSize.height > scrollView.bounds.height { let point = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height) self.scrollView.setContentOffset(point, animated: true) } } @objc private func tapTxHash() { guard let hash = transaction?.hash else { return } UIPasteboard.general.string = hash } override func layoutSubviews() { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0)).cgPath let maskLayer = CAShapeLayer() maskLayer.path = path layer.mask = maskLayer } fileprivate func saveComment(comment: String) { guard let kvStore = self.kvStore else { return } if let metaData = transaction?.metaData { metaData.comment = comment do { let _ = try kvStore.set(metaData) } catch let error { print("could not update metadata: \(error)") } } else { guard let rate = self.rate else { return } guard let transaction = self.transaction else { return } let newMetaData = BRTxMetadataObject(transaction: transaction.rawTransaction, exchangeRate: rate.rate, exchangeRateCurrency: rate.code, feeRate: 0.0, deviceId: UserDefaults.standard.deviceID) newMetaData.comment = comment do { let _ = try kvStore.set(newMetaData) } catch let error { print("could not update metadata: \(error)") } } NotificationCenter.default.post(name: .WalletTxStatusUpdateNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TransactionDetailCollectionViewCell : UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text else { return } saveComment(comment: text) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let count = (textField.text ?? "").utf8.count + string.utf8.count if count > C.maxMemoLength { return false } else { return true } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster that approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. Strings are collections of `Character` instances, so /// the number of visible characters is generally the most natural way to /// count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Length: \(greeting.count)") /// // Prints "Length: 8" /// /// Because each character in a string can be made up of one or more Unicode /// scalar values, the number of characters in a string may not match the /// length of the Unicode scalar value representation or the length of the /// string in a particular binary representation. /// /// print("Unicode scalar value count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode scalar value count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode scalar values /// that are grouped together as an *extended grapheme cluster*. The way these /// scalar values are grouped is defined by a canonical, localized, or /// otherwise tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator scalar values that correspond to that country's ISO 3166-1 /// alpha-2 code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a string literal, these two /// scalar values are combined into a single grapheme cluster, represented by /// a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value @_fixed_layout public struct Character { // Fundamentally, it is just a String, but it is optimized for the common case // where the UTF-16 representation fits in 63 bits. The remaining bit is used // to discriminate between small and large representations. Since a grapheme // cluster cannot have U+0000 anywhere but in its first scalar, we can store // zero in empty code units above the first one. @_fixed_layout // FIXME(sil-serialize-all) @_versioned internal enum Representation { case smallUTF16(Builtin.Int63) case large(_UTF16StringStorage) } @_versioned internal var _representation: Representation // FIXME(sil-serialize-all): Should be @_inlineable @_versioned // <rdar://problem/34557187> internal static func _smallValue(_ value: Builtin.Int63) -> UInt64 { return UInt64(Builtin.zext_Int63_Int64(value)) } typealias UTF16View = String.UTF16View @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var utf16: UTF16View { return String(self).utf16 } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_smallRepresentation b: _SmallUTF16) { _sanityCheck(Int64(b._storage) >= 0) _representation = .smallUTF16( Builtin.trunc_Int64_Int63(b._storage._value)) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_largeRepresentation storage: _UTF16StringStorage) { _representation = .large(storage) } /// Creates a Character from a String that is already known to require the /// large representation. /// /// - Note: `s` should contain only a single grapheme, but we can't require /// that formally because of grapheme cluster literals and the shifting /// sands of Unicode. https://bugs.swift.org/browse/SR-4955 @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_largeRepresentationString s: String) { let storage = s._guts._extractNativeStorage(of: UTF16.CodeUnit.self) self.init(_largeRepresentation: storage) } } extension Character : _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral { /// Creates a character containing the given Unicode scalar value. /// /// - Parameter content: The Unicode scalar value to convert into a character. @_inlineable // FIXME(sil-serialize-all) public init(_ content: Unicode.Scalar) { let content16 = UTF16.encode(content)._unsafelyUnwrappedUnchecked _representation = .smallUTF16( Builtin.zext_Int32_Int63(content16._storage._value)) } @_inlineable // FIXME(sil-serialize-all) @effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = Character( String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value)))) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @_inlineable // FIXME(sil-serialize-all) @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { let utf8 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount)) if utf8.count == 1 { _representation = .smallUTF16( Builtin.zext_Int8_Int63(utf8.first._unsafelyUnwrappedUnchecked._value)) return } FastPath: repeat { var shift = 0 let maxShift = 64 - 16 var bits: UInt64 = 0 for s8 in Unicode._ParsingIterator( codeUnits: utf8.makeIterator(), parser: UTF8.ForwardParser()) { let s16 = UTF16.transcode(s8, from: UTF8.self)._unsafelyUnwrappedUnchecked for u16 in s16 { guard _fastPath(shift <= maxShift) else { break FastPath } bits |= UInt64(u16) &<< shift shift += 16 } } guard _fastPath(Int64(truncatingIfNeeded: bits) >= 0) else { break FastPath } _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) return } while false // For anything that doesn't fit in 63 bits, build the large // representation. self = Character(_largeRepresentationString: String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @_inlineable // FIXME(sil-serialize-all) @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { let utf16 = _UnmanagedString<UTF16.CodeUnit>( start: UnsafePointer(start), count: Int(utf16CodeUnitCount)) switch utf16.count { case 1: _representation = .smallUTF16(Builtin.zext_Int16_Int63(utf16[0]._value)) case 2: let bits = UInt32(utf16[0]) | UInt32(utf16[1]) &<< 16 _representation = .smallUTF16(Builtin.zext_Int32_Int63(bits._value)) case 3: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) case 4 where utf16[3] < 0x8000: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 | UInt64(utf16[3]) &<< 48 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) default: _representation = Character( _largeRepresentationString: String(_StringGuts(utf16)))._representation } } /// Creates a character with the specified value. /// /// Do not call this initalizer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. @_inlineable // FIXME(sil-serialize-all) public init(extendedGraphemeClusterLiteral value: Character) { self = value } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) public init(_ s: String) { let count = s._guts.count _precondition(count != 0, "Can't form a Character from an empty String") _debugPrecondition(s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") self.init(_unverified: s._guts) } /// Construct a Character from a _StringGuts, assuming it consists of exactly /// one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_unverified guts: _StringGuts) { defer { _fixLifetime(guts) } if _slowPath(guts._isOpaque) { self.init(_unverified: guts._asOpaque()) return } if guts.isASCII { let ascii = guts._unmanagedASCIIView if _fastPath(ascii.count == 1) { self.init(_singleCodeUnit: ascii[0]) } else { // The only multi-scalar ASCII grapheme cluster is CR/LF. _sanityCheck(ascii.count == 2) _sanityCheck(ascii.start[0] == _CR) _sanityCheck(ascii.start[1] == _LF) self.init(_codeUnitPair: UInt16(_CR), UInt16(_LF)) } return } if guts._isNative { self.init(_unverified: guts._object.nativeStorage(of: UTF16.CodeUnit.self)) } else { self.init(_unverified: guts._unmanagedUTF16View) } } /// Construct a Character from a slice of a _StringGuts, assuming /// the specified range covers exactly one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_unverified guts: _StringGuts, range: Range<Int>) { defer { _fixLifetime(guts) } if _fastPath(range.count == 1) { let cu = guts.codeUnit(atCheckedOffset: range.lowerBound) // Check for half a surrogate pair. (We may encounter these at boundaries // of String slices or when the data itself has an invalid encoding.) if _fastPath(UTF16._isScalar(cu)) { self.init(_singleCodeUnit: cu) } else { self.init(_singleCodeUnit: UTF16._replacementCodeUnit) } return } if guts.isASCII { let ascii = guts._unmanagedASCIIView // The only multi-scalar ASCII grapheme cluster is CR/LF. ascii._boundsCheck(offsetRange: range) _sanityCheck(range.count == 2) _sanityCheck(ascii.start[range.lowerBound] == _CR) _sanityCheck(ascii.start[range.lowerBound + 1] == _LF) self.init(_codeUnitPair: UInt16(_CR), UInt16(_LF)) } else if guts._isContiguous { let utf16 = guts._unmanagedUTF16View.checkedSlice(range) self.init(_unverified: utf16) } else { let opaque = guts._asOpaque().checkedSlice(range) self.init(_unverified: opaque._copyToNativeStorage()) } } @_inlineable @_versioned internal init(_singleCodeUnit cu: UInt16) { _sanityCheck(UTF16._isScalar(cu)) _representation = .smallUTF16( Builtin.zext_Int16_Int63(Builtin.reinterpretCast(cu))) } @_inlineable @_versioned internal init(_codeUnitPair first: UInt16, _ second: UInt16) { _sanityCheck( (UTF16._isScalar(first) && UTF16._isScalar(second)) || (UTF16.isLeadSurrogate(first) && UTF16.isTrailSurrogate(second))) _representation = .smallUTF16( Builtin.zext_Int32_Int63( Builtin.reinterpretCast( UInt32(first) | UInt32(second) &<< 16))) } @_inlineable @_versioned internal init(_unverified storage: _SwiftStringStorage<Unicode.UTF16.CodeUnit>) { if _fastPath(storage.count <= 4) { _sanityCheck(storage.count > 0) let b = _SmallUTF16(storage.unmanagedView) if _fastPath(Int64(bitPattern: b._storage) >= 0) { self.init(_smallRepresentation: b) _fixLifetime(storage) return } } // FIXME: We may want to make a copy if storage.unusedCapacity > 0 self.init(_largeRepresentation: storage) } @_inlineable @_versioned internal init<V: _StringVariant>(_unverified variant: V) { if _fastPath(variant.count <= 4) { _sanityCheck(variant.count > 0) let b = _SmallUTF16(variant) if _fastPath(Int64(bitPattern: b._storage) >= 0) { self.init(_smallRepresentation: b) return } } self.init(_largeRepresentation: variant._copyToNativeStorage()) } } extension Character : CustomStringConvertible { @_inlineable // FIXME(sil-serialize-all) public var description: String { return String(describing: self) } } extension Character : LosslessStringConvertible { } extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return String(self).debugDescription } } extension Character { internal typealias _SmallUTF16 = _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit> @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _smallUTF16 : _SmallUTF16? { guard case .smallUTF16(let _63bits) = _representation else { return nil } _onFastPath() let bits = UInt64(Builtin.zext_Int63_Int64(_63bits)) let minBitWidth = type(of: bits).bitWidth - bits.leadingZeroBitCount return _SmallUTF16( _storage: bits, _bitCount: UInt8( truncatingIfNeeded: 16 * Swift.max(1, (minBitWidth + 15) / 16)) ) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _largeUTF16 : _UTF16StringStorage? { guard case .large(let storage) = _representation else { return nil } return storage } } extension Character { @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _count : Int { if let small = _smallUTF16 { return small.count } return _largeUTF16._unsafelyUnwrappedUnchecked.count } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. @_inlineable // FIXME(sil-serialize-all) public init(_ c: Character) { if let utf16 = c._smallUTF16 { self = String(decoding: utf16, as: Unicode.UTF16.self) } else { self = String(_StringGuts(c._largeUTF16!)) } } } /// `.small` characters are stored in an Int63 with their UTF-8 representation, /// with any unused bytes set to 0xFF. ASCII characters will have all bytes set /// to 0xFF except for the lowest byte, which will store the ASCII value. Since /// 0x7FFFFFFFFFFFFF80 or greater is an invalid UTF-8 sequence, we know if a /// value is ASCII by checking if it is greater than or equal to /// 0x7FFFFFFFFFFFFF00. // FIXME(sil-serialize-all): Should be @_inlineable @_versioned // <rdar://problem/34557187> internal var _minASCIICharReprBuiltin: Builtin.Int63 { @inline(__always) get { let x: Int64 = 0x7FFFFFFFFFFFFF00 return Builtin.truncOrBitCast_Int64_Int63(x._value) } } extension Character : Equatable { @_inlineable @inline(__always) public static func == (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x300 { return l == r } if l == r { return true } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) == String(rhs) } } extension Character : Comparable { @_inlineable @inline(__always) public static func < (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x80 { return l < r } if l == r { return false } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) < String(rhs) } } extension Character: Hashable { /// The character's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. @_inlineable // FIXME(sil-serialize-all) public var hashValue: Int { // FIXME(performance): constructing a temporary string is extremely // wasteful and inefficient. return String(self).hashValue } } [string] Minor expression simplification. NFC //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster that approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. Strings are collections of `Character` instances, so /// the number of visible characters is generally the most natural way to /// count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Length: \(greeting.count)") /// // Prints "Length: 8" /// /// Because each character in a string can be made up of one or more Unicode /// scalar values, the number of characters in a string may not match the /// length of the Unicode scalar value representation or the length of the /// string in a particular binary representation. /// /// print("Unicode scalar value count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode scalar value count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode scalar values /// that are grouped together as an *extended grapheme cluster*. The way these /// scalar values are grouped is defined by a canonical, localized, or /// otherwise tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator scalar values that correspond to that country's ISO 3166-1 /// alpha-2 code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a string literal, these two /// scalar values are combined into a single grapheme cluster, represented by /// a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value @_fixed_layout public struct Character { // Fundamentally, it is just a String, but it is optimized for the common case // where the UTF-16 representation fits in 63 bits. The remaining bit is used // to discriminate between small and large representations. Since a grapheme // cluster cannot have U+0000 anywhere but in its first scalar, we can store // zero in empty code units above the first one. @_fixed_layout // FIXME(sil-serialize-all) @_versioned internal enum Representation { case smallUTF16(Builtin.Int63) case large(_UTF16StringStorage) } @_versioned internal var _representation: Representation // FIXME(sil-serialize-all): Should be @_inlineable @_versioned // <rdar://problem/34557187> internal static func _smallValue(_ value: Builtin.Int63) -> UInt64 { return UInt64(Builtin.zext_Int63_Int64(value)) } typealias UTF16View = String.UTF16View @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var utf16: UTF16View { return String(self).utf16 } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_smallRepresentation b: _SmallUTF16) { _sanityCheck(Int64(b._storage) >= 0) _representation = .smallUTF16( Builtin.trunc_Int64_Int63(b._storage._value)) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_largeRepresentation storage: _UTF16StringStorage) { _representation = .large(storage) } /// Creates a Character from a String that is already known to require the /// large representation. /// /// - Note: `s` should contain only a single grapheme, but we can't require /// that formally because of grapheme cluster literals and the shifting /// sands of Unicode. https://bugs.swift.org/browse/SR-4955 @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_largeRepresentationString s: String) { let storage = s._guts._extractNativeStorage(of: UTF16.CodeUnit.self) self.init(_largeRepresentation: storage) } } extension Character : _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral { /// Creates a character containing the given Unicode scalar value. /// /// - Parameter content: The Unicode scalar value to convert into a character. @_inlineable // FIXME(sil-serialize-all) public init(_ content: Unicode.Scalar) { let content16 = UTF16.encode(content)._unsafelyUnwrappedUnchecked _representation = .smallUTF16( Builtin.zext_Int32_Int63(content16._storage._value)) } @_inlineable // FIXME(sil-serialize-all) @effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = Character( String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value)))) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @_inlineable // FIXME(sil-serialize-all) @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { let utf8 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount)) if utf8.count == 1 { _representation = .smallUTF16( Builtin.zext_Int8_Int63(utf8.first._unsafelyUnwrappedUnchecked._value)) return } FastPath: repeat { var shift = 0 let maxShift = 64 - 16 var bits: UInt64 = 0 for s8 in Unicode._ParsingIterator( codeUnits: utf8.makeIterator(), parser: UTF8.ForwardParser()) { let s16 = UTF16.transcode(s8, from: UTF8.self)._unsafelyUnwrappedUnchecked for u16 in s16 { guard _fastPath(shift <= maxShift) else { break FastPath } bits |= UInt64(u16) &<< shift shift += 16 } } guard _fastPath(Int64(truncatingIfNeeded: bits) >= 0) else { break FastPath } _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) return } while false // For anything that doesn't fit in 63 bits, build the large // representation. self = Character(_largeRepresentationString: String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @_inlineable // FIXME(sil-serialize-all) @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { let utf16 = _UnmanagedString<UTF16.CodeUnit>( start: UnsafePointer(start), count: Int(utf16CodeUnitCount)) switch utf16.count { case 1: _representation = .smallUTF16(Builtin.zext_Int16_Int63(utf16[0]._value)) case 2: let bits = UInt32(utf16[0]) | UInt32(utf16[1]) &<< 16 _representation = .smallUTF16(Builtin.zext_Int32_Int63(bits._value)) case 3: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) case 4 where utf16[3] < 0x8000: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 | UInt64(utf16[3]) &<< 48 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) default: _representation = .large(_StringGuts(utf16)._extractNativeStorage()) } } /// Creates a character with the specified value. /// /// Do not call this initalizer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. @_inlineable // FIXME(sil-serialize-all) public init(extendedGraphemeClusterLiteral value: Character) { self = value } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) public init(_ s: String) { let count = s._guts.count _precondition(count != 0, "Can't form a Character from an empty String") _debugPrecondition(s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") self.init(_unverified: s._guts) } /// Construct a Character from a _StringGuts, assuming it consists of exactly /// one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_unverified guts: _StringGuts) { defer { _fixLifetime(guts) } if _slowPath(guts._isOpaque) { self.init(_unverified: guts._asOpaque()) return } if guts.isASCII { let ascii = guts._unmanagedASCIIView if _fastPath(ascii.count == 1) { self.init(_singleCodeUnit: ascii[0]) } else { // The only multi-scalar ASCII grapheme cluster is CR/LF. _sanityCheck(ascii.count == 2) _sanityCheck(ascii.start[0] == _CR) _sanityCheck(ascii.start[1] == _LF) self.init(_codeUnitPair: UInt16(_CR), UInt16(_LF)) } return } if guts._isNative { self.init(_unverified: guts._object.nativeStorage(of: UTF16.CodeUnit.self)) } else { self.init(_unverified: guts._unmanagedUTF16View) } } /// Construct a Character from a slice of a _StringGuts, assuming /// the specified range covers exactly one extended grapheme cluster. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_unverified guts: _StringGuts, range: Range<Int>) { defer { _fixLifetime(guts) } if _fastPath(range.count == 1) { let cu = guts.codeUnit(atCheckedOffset: range.lowerBound) // Check for half a surrogate pair. (We may encounter these at boundaries // of String slices or when the data itself has an invalid encoding.) if _fastPath(UTF16._isScalar(cu)) { self.init(_singleCodeUnit: cu) } else { self.init(_singleCodeUnit: UTF16._replacementCodeUnit) } return } if guts.isASCII { let ascii = guts._unmanagedASCIIView // The only multi-scalar ASCII grapheme cluster is CR/LF. ascii._boundsCheck(offsetRange: range) _sanityCheck(range.count == 2) _sanityCheck(ascii.start[range.lowerBound] == _CR) _sanityCheck(ascii.start[range.lowerBound + 1] == _LF) self.init(_codeUnitPair: UInt16(_CR), UInt16(_LF)) } else if guts._isContiguous { let utf16 = guts._unmanagedUTF16View.checkedSlice(range) self.init(_unverified: utf16) } else { let opaque = guts._asOpaque().checkedSlice(range) self.init(_unverified: opaque._copyToNativeStorage()) } } @_inlineable @_versioned internal init(_singleCodeUnit cu: UInt16) { _sanityCheck(UTF16._isScalar(cu)) _representation = .smallUTF16( Builtin.zext_Int16_Int63(Builtin.reinterpretCast(cu))) } @_inlineable @_versioned internal init(_codeUnitPair first: UInt16, _ second: UInt16) { _sanityCheck( (UTF16._isScalar(first) && UTF16._isScalar(second)) || (UTF16.isLeadSurrogate(first) && UTF16.isTrailSurrogate(second))) _representation = .smallUTF16( Builtin.zext_Int32_Int63( Builtin.reinterpretCast( UInt32(first) | UInt32(second) &<< 16))) } @_inlineable @_versioned internal init(_unverified storage: _SwiftStringStorage<Unicode.UTF16.CodeUnit>) { if _fastPath(storage.count <= 4) { _sanityCheck(storage.count > 0) let b = _SmallUTF16(storage.unmanagedView) if _fastPath(Int64(bitPattern: b._storage) >= 0) { self.init(_smallRepresentation: b) _fixLifetime(storage) return } } // FIXME: We may want to make a copy if storage.unusedCapacity > 0 self.init(_largeRepresentation: storage) } @_inlineable @_versioned internal init<V: _StringVariant>(_unverified variant: V) { if _fastPath(variant.count <= 4) { _sanityCheck(variant.count > 0) let b = _SmallUTF16(variant) if _fastPath(Int64(bitPattern: b._storage) >= 0) { self.init(_smallRepresentation: b) return } } self.init(_largeRepresentation: variant._copyToNativeStorage()) } } extension Character : CustomStringConvertible { @_inlineable // FIXME(sil-serialize-all) public var description: String { return String(describing: self) } } extension Character : LosslessStringConvertible { } extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return String(self).debugDescription } } extension Character { internal typealias _SmallUTF16 = _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit> @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _smallUTF16 : _SmallUTF16? { guard case .smallUTF16(let _63bits) = _representation else { return nil } _onFastPath() let bits = UInt64(Builtin.zext_Int63_Int64(_63bits)) let minBitWidth = type(of: bits).bitWidth - bits.leadingZeroBitCount return _SmallUTF16( _storage: bits, _bitCount: UInt8( truncatingIfNeeded: 16 * Swift.max(1, (minBitWidth + 15) / 16)) ) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _largeUTF16 : _UTF16StringStorage? { guard case .large(let storage) = _representation else { return nil } return storage } } extension Character { @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _count : Int { if let small = _smallUTF16 { return small.count } return _largeUTF16._unsafelyUnwrappedUnchecked.count } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. @_inlineable // FIXME(sil-serialize-all) public init(_ c: Character) { if let utf16 = c._smallUTF16 { self = String(decoding: utf16, as: Unicode.UTF16.self) } else { self = String(_StringGuts(c._largeUTF16!)) } } } /// `.small` characters are stored in an Int63 with their UTF-8 representation, /// with any unused bytes set to 0xFF. ASCII characters will have all bytes set /// to 0xFF except for the lowest byte, which will store the ASCII value. Since /// 0x7FFFFFFFFFFFFF80 or greater is an invalid UTF-8 sequence, we know if a /// value is ASCII by checking if it is greater than or equal to /// 0x7FFFFFFFFFFFFF00. // FIXME(sil-serialize-all): Should be @_inlineable @_versioned // <rdar://problem/34557187> internal var _minASCIICharReprBuiltin: Builtin.Int63 { @inline(__always) get { let x: Int64 = 0x7FFFFFFFFFFFFF00 return Builtin.truncOrBitCast_Int64_Int63(x._value) } } extension Character : Equatable { @_inlineable @inline(__always) public static func == (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x300 { return l == r } if l == r { return true } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) == String(rhs) } } extension Character : Comparable { @_inlineable @inline(__always) public static func < (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x80 { return l < r } if l == r { return false } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) < String(rhs) } } extension Character: Hashable { /// The character's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. @_inlineable // FIXME(sil-serialize-all) public var hashValue: Int { // FIXME(performance): constructing a temporary string is extremely // wasteful and inefficient. return String(self).hashValue } }
// // MyConnectionRequestSpec.swift // CreatubblesAPIClient // // Created by Nomtek on 04.07.2016. // Copyright © 2016 Nomtek. All rights reserved. // import Quick import Nimble @testable import CreatubblesAPIClient class MyConnectionsResponseHandlerSpec: QuickSpec { override func spec() { describe("My Connections response handler") { it("Should return correct value after login") { let sender = TestComponentsFactory.requestSender waitUntil(timeout: 10) { done in sender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: ErrorType?) -> Void in expect(error).to(beNil()) sender.send(MyConnectionsRequest(), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?,pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).to(beNil()) expect(users).notTo(beNil()) expect(pageInfo).notTo(beNil()) done() }) } } } it("Should return error when not logged in") { let sender = TestComponentsFactory.requestSender sender.logout() waitUntil(timeout: 10) { done in sender.send(MyConnectionsRequest(), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?, pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).notTo(beNil()) expect(users).to(beNil()) expect(pageInfo).to(beNil()) done() }) } } } } } [CI-130] Added tests for response handler // // MyConnectionRequestSpec.swift // CreatubblesAPIClient // // Created by Nomtek on 04.07.2016. // Copyright © 2016 Nomtek. All rights reserved. // import Quick import Nimble @testable import CreatubblesAPIClient class MyConnectionsResponseHandlerSpec: QuickSpec { override func spec() { describe("My Connections response handler") { it("Should return correct value after login") { let sender = TestComponentsFactory.requestSender waitUntil(timeout: 10) { done in sender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: ErrorType?) -> Void in expect(error).to(beNil()) sender.send(MyConnectionsRequest(), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?,pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).to(beNil()) expect(users).notTo(beNil()) expect(pageInfo).notTo(beNil()) done() }) } } } it("Should return error when not logged in") { let sender = TestComponentsFactory.requestSender sender.logout() waitUntil(timeout: 10) { done in sender.send(MyConnectionsRequest(), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?, pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).notTo(beNil()) expect(users).to(beNil()) expect(pageInfo).to(beNil()) done() }) } } it("Should return error for other user's my connections when not logged in") { let sender = TestComponentsFactory.requestSender sender.logout() let page = 1 let perPage = 10 let userId = TestConfiguration.testUserIdentifier waitUntil(timeout: 10) { done in sender.send(MyConnectionsRequest(page: page, perPage: perPage, userId: userId), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?, pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).notTo(beNil()) expect(users).to(beNil()) expect(pageInfo).to(beNil()) done() }) } } it("Should return correct value for other user's my connections after login") { let sender = TestComponentsFactory.requestSender let page = 1 let perPage = 10 let userId = TestConfiguration.testUserIdentifier waitUntil(timeout: 10) { done in sender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: ErrorType?) -> Void in expect(error).to(beNil()) sender.send(MyConnectionsRequest(page: page, perPage: perPage, userId: userId), withResponseHandler: MyConnectionsResponseHandler() { (users: Array<User>?,pageInfo: PagingInfo?, error: ErrorType?) -> Void in expect(error).to(beNil()) expect(users).notTo(beNil()) expect(pageInfo).notTo(beNil()) done() }) } } } } } }
// // FloatingTitleTextField.swift // FloatingTitleTextField // // Created by Gustavo Saume on 11/15/15. // Copyright © 2015 BigPanza. All rights reserved. // import UIKit @IBDesignable public class FloatingTitleTextField: UITextField { // Publics vars @IBInspectable public var title: String? { didSet { self.titleLabel.text = title self.titleLabel.sizeToFit() let centerY = self.frame.height / 2.0 let deltaY = centerY - self.titleLabel.frame.midY self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0.0, dy: deltaY) } } @IBInspectable public var leftInset: CGFloat = 0.0 { didSet { self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: leftInset, dy: 0.0) } } override public var placeholder: String? { get { return internalPlaceholder } set(newPlaceholder) { internalPlaceholder = newPlaceholder } } // Private vars private lazy var titleLabel: UILabel! = { return UILabel() }() private var internalPlaceholder: String? // Initialization override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.titleLabel) self.internalPlaceholder = super.placeholder super.placeholder = nil } // Overrides override public func becomeFirstResponder() -> Bool { let becameResponder = super.becomeFirstResponder() let scale = CGFloat(0.75) let scaleTransform = CGAffineTransformMakeScale(scale, scale) UIView.animateWithDuration(0.35, animations:{ self.titleLabel.transform = scaleTransform self.titleLabel.alpha = 0.6 let distanceToTopCorner = CGPoint(x: -self.titleLabel.frame.minX, y: -self.titleLabel.frame.minY) let topFrame = self.titleLabel.frame.offsetBy(dx: distanceToTopCorner.x, dy: distanceToTopCorner.y) self.titleLabel.frame = topFrame }) { _ in super.placeholder = self.internalPlaceholder } return becameResponder } override public func resignFirstResponder() -> Bool { let resigned = super.resignFirstResponder() if self.text?.characters.count == 0 { UIView.animateWithDuration(0.35) { self.titleLabel.transform = CGAffineTransformMakeScale(1.0, 1.0) self.titleLabel.alpha = 1.0 let distanceToCenterX = -self.titleLabel.frame.minX let distanceToCenterY = ((self.bounds.height - self.titleLabel.bounds.height) / 2.0) - self.titleLabel.frame.minY let centerFrame = self.titleLabel.frame.offsetBy(dx: distanceToCenterX, dy: distanceToCenterY) self.titleLabel.frame = centerFrame super.placeholder = nil } } return resigned } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, leftInset, 0.0) } override public func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } } Refactors title animation code into a single function // // FloatingTitleTextField.swift // FloatingTitleTextField // // Created by Gustavo Saume on 11/15/15. // Copyright © 2015 BigPanza. All rights reserved. // import UIKit @IBDesignable public class FloatingTitleTextField: UITextField { // Publics vars @IBInspectable public var title: String? { didSet { self.titleLabel.text = title self.titleLabel.sizeToFit() let centerY = self.frame.height / 2.0 let deltaY = centerY - self.titleLabel.frame.midY self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0.0, dy: deltaY) } } @IBInspectable public var leftInset: CGFloat = 0.0 { didSet { self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: leftInset, dy: 0.0) } } override public var placeholder: String? { get { return internalPlaceholder } set(newPlaceholder) { internalPlaceholder = newPlaceholder } } // Private vars private lazy var titleLabel: UILabel! = { return UILabel() }() private var internalPlaceholder: String? // Initialization override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.titleLabel) self.internalPlaceholder = super.placeholder super.placeholder = nil } // Overrides override public func becomeFirstResponder() -> Bool { self.repositionTitleLabel(true, animated: true) { _ in super.placeholder = self.internalPlaceholder } return super.becomeFirstResponder() } override public func resignFirstResponder() -> Bool { self.repositionTitleLabel(self.text?.characters.count == 0, animated: true, completion: nil) super.placeholder = nil return super.resignFirstResponder() } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, leftInset, 0.0) } override public func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } // Utils private func repositionTitleLabel(minimized: Bool, animated: Bool = false, completion: (Bool -> Void)?) { let alpha:CGFloat = minimized ? 0.6 : 1.0 let scale:CGFloat = minimized ? CGFloat(0.75) : CGFloat(1.0) let scaleTransform = CGAffineTransformMakeScale(scale, scale) let topFrame: CGRect if minimized { let distanceToTopCorner = CGPoint(x: -self.titleLabel.frame.minX, y: -self.titleLabel.frame.minY) topFrame = self.titleLabel.frame.offsetBy(dx: distanceToTopCorner.x, dy: distanceToTopCorner.y) } else { let distanceToCenterX = -self.titleLabel.frame.minX let distanceToCenterY = ((self.bounds.height - self.titleLabel.bounds.height) / 2.0) - self.titleLabel.frame.minY let centerFrame = self.titleLabel.frame.offsetBy(dx: distanceToCenterX, dy: distanceToCenterY) topFrame = centerFrame.offsetBy(dx: self.leftInset, dy: 0.0) } let changes = { self.titleLabel.transform = scaleTransform self.titleLabel.alpha = alpha self.titleLabel.frame = topFrame } if animated { UIView.animateWithDuration(0.35, animations:changes) { completed in if let completion = completion { completion(completed) } } } else { changes() if let completion = completion { completion(true) } } } }
// // LSBook.swift // LHiOSAccumulatesInSwift // // Created by 李辉 on 2017/8/11. // Copyright © 2017年 Lihux. All rights reserved. // import Foundation struct LSBook: Codable { let rating: Rating let subTitle: String let publisher: String let title: String let price: String let image: String let images: Image let authors: [String] let publishDate: String let tags: [Tag] let originTitle: String let binding: String let translator: [String] let catalog: String let pages: String let isbn: String let authorIntroduction: String let summary: String } // MARK: CodingKey extension LSBook { enum CodingKeys: String, CodingKey { case rating case subTitle = "subtitle" case publisher case title case price case image case images case authors = "author" case publishDate = "pubdate" case tags case originTitle = "origin_title" case binding case translator case catalog case pages case isbn = "isbn13" case authorIntroduction = "author_intro" case summary } } // MARK: Inner Struct Defines extension LSBook { struct Rating: Codable { let max: Int let numRaters: Int let average: String } struct Image: Codable { let small: String let large: String let medium: String } struct Tag: Codable { let count: Int let name: String let title: String } } <Swift>对于书系series字段,服务端可能返回为nil,必须显示设置为optional的方式解析才能成功!!! // // LSBook.swift // LHiOSAccumulatesInSwift // // Created by 李辉 on 2017/8/11. // Copyright © 2017年 Lihux. All rights reserved. // import Foundation struct LSBook: Codable { let rating: Rating let subTitle: String let publisher: String let title: String let price: String let image: String let images: Image let authors: [String] let publishDate: String let tags: [Tag] let originTitle: String let binding: String let translator: [String] let catalog: String let pages: String let isbn: String let authorIntroduction: String let summary: String var series: Series? } // MARK: CodingKey extension LSBook { enum CodingKeys: String, CodingKey { case rating case subTitle = "subtitle" case publisher case title case price case image case images case authors = "author" case publishDate = "pubdate" case tags case originTitle = "origin_title" case binding case translator case catalog case pages case isbn = "isbn13" case authorIntroduction = "author_intro" case summary case series } } // MARK: Inner Struct Defines extension LSBook { struct Rating: Codable { let max: Int let numRaters: Int let average: String } struct Image: Codable { let small: String let large: String let medium: String } struct Tag: Codable { let count: Int let name: String let title: String } struct Series: Codable { let seriesID: String let title: String enum CodingKeys: String, CodingKey { case seriesID = "id" case title } } }
// // BlockEditorTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/10. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class BlockEditorTableViewController: BaseTableViewController, AddAssetDelegate { var blog: Blog! var entry: BaseEntry! var blocks: EntryBlocksItem! var items: [BaseEntryItem]! var noItemLabel = UILabel() var tophImage = UIImageView(image: UIImage(named: "guide_toph_sleep")) var guidanceBgView = UIView() 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() self.title = blocks.label items = blocks.blocks self.tableView.registerNib(UINib(nibName: "TextBlockTableViewCell", bundle: nil), forCellReuseIdentifier: "TextBlockTableViewCell") self.tableView.registerNib(UINib(nibName: "ImageBlockTableViewCell", bundle: nil), forCellReuseIdentifier: "ImageBlockTableViewCell") self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "saveButtonPushed:") self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:") self.view.addSubview(tophImage) tophImage.center = view.center var frame = tophImage.frame frame.origin.y = 109.0 tophImage.frame = frame noItemLabel.textColor = Color.placeholderText noItemLabel.font = UIFont.systemFontOfSize(18.0) noItemLabel.text = String(format: NSLocalizedString("No %@", comment: "No %@"), arguments: [blocks.label]) noItemLabel.sizeToFit() self.view.addSubview(noItemLabel) noItemLabel.center = view.center frame = noItemLabel.frame frame.origin.y = tophImage.frame.origin.y + tophImage.frame.size.height + 13.0 noItemLabel.frame = frame tophImage.hidden = true noItemLabel.hidden = true guidanceBgView.backgroundColor = colorize(0x000000, alpha: 0.3) let app = UIApplication.sharedApplication().delegate as! AppDelegate guidanceBgView.frame = app.window!.frame app.window!.addSubview(guidanceBgView) var guidanceView = BlockGuidanceView.instanceFromNib() as! BlockGuidanceView guidanceView.closeButton.addTarget(self, action: "guidanceCloseButtonPushed:", forControlEvents: UIControlEvents.TouchUpInside) guidanceBgView.addSubview(guidanceView) guidanceView.center = guidanceBgView.center frame = guidanceView.frame frame.origin.y = 70.0 guidanceView.frame = frame let defaults = NSUserDefaults.standardUserDefaults() let showed = defaults.boolForKey("blocksGuidanceShowed") if showed { guidanceBgView.removeFromSuperview() } self.tableView.backgroundColor = Color.tableBg } override func viewWillAppear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setToolbarHidden(false, animated: false) self.makeToolbarItems(false) self.tableView.reloadData() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setToolbarHidden(true, animated: false) } 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 Potentially incomplete method implementation. // Return the number of sections. if items == nil { return 0 } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. if items == nil { return 0 } tophImage.hidden = !(items.count == 0) noItemLabel.hidden = !(items.count == 0) return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() // Configure the cell... let item = items[indexPath.row] if item.type == "textarea" { var c = tableView.dequeueReusableCellWithIdentifier("TextBlockTableViewCell", forIndexPath: indexPath) as! TextBlockTableViewCell var text = item.dispValue() if text.isEmpty { c.placeholderLabel?.text = (item as! EntryTextAreaItem).placeholder() c.placeholderLabel.hidden = false c.blockTextLabel.hidden = true } else { c.blockTextLabel?.text = Utils.removeHTMLTags(text) c.placeholderLabel.hidden = true c.blockTextLabel.hidden = false } cell = c } else { var c = tableView.dequeueReusableCellWithIdentifier("ImageBlockTableViewCell", forIndexPath: indexPath) as! ImageBlockTableViewCell c.blockImageView.sd_setImageWithURL(NSURL(string: item.dispValue())) cell = c } self.adjustCellLayoutMargins(cell) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110.0 } /* // 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 items.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } /* // 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 } */ // 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 } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let item = items[sourceIndexPath.row]; items.removeAtIndex(sourceIndexPath.row); items.insert(item, atIndex: destinationIndexPath.row) } private func showHTMLEditor(object: EntryTextAreaItem) { if self.entry.editMode == Entry.EditMode.PlainText { let vc = EntryHTMLEditorViewController() vc.object = object vc.blog = blog vc.entry = entry self.navigationController?.pushViewController(vc, animated: true) } else { let vc = EntryRichTextViewController() vc.object = object self.navigationController?.pushViewController(vc, animated: true) } } private func showAssetSelector(object: EntryImageItem) { let storyboard: UIStoryboard = UIStoryboard(name: "ImageSelector", bundle: nil) let nav = storyboard.instantiateInitialViewController() as! UINavigationController let vc = nav.topViewController as! ImageSelectorTableViewController vc.blog = blog vc.delegate = self vc.showAlign = true vc.object = object vc.entry = self.entry self.presentViewController(nav, animated: true, completion: nil) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if let items = self.items { let item = items[indexPath.row] if item.type == "textarea" { self.showHTMLEditor(item as! EntryTextAreaItem) } else if item.type == "image" { self.showAssetSelector(item as! EntryImageItem) } } } /* // 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. } */ @IBAction func saveButtonPushed(sender: UIBarButtonItem) { blocks.blocks = self.items self.navigationController?.popViewControllerAnimated(true) } private func makeToolbarItems(editMode: Bool) { var buttons = [UIBarButtonItem]() if editMode { var flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:") buttons = [flexible, doneButton] } else { var cameraButton = UIBarButtonItem(image: UIImage(named: "btn_camera"), left: true, target: self, action: "cameraButtonPushed:") var textAddButton = UIBarButtonItem(image: UIImage(named: "btn_textadd"), left: false, target: self, action: "textAddButtonPushed:") var flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var previewButton = UIBarButtonItem(image: UIImage(named: "btn_preview"), style: UIBarButtonItemStyle.Plain, target: self, action: "previewButtonPushed:") var editButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editButtonPushed:") buttons = [cameraButton, textAddButton, flexible, previewButton, editButton] } self.setToolbarItems(buttons, animated: true) } @IBAction func editButtonPushed(sender: UIBarButtonItem) { self.tableView.setEditing(true, animated: true) self.navigationItem.rightBarButtonItem?.enabled = false self.makeToolbarItems(true) } @IBAction func doneButtonPushed(sender: UIBarButtonItem) { self.tableView.setEditing(false, animated: true) self.navigationItem.rightBarButtonItem?.enabled = true self.makeToolbarItems(false) } @IBAction func cameraButtonPushed(sender: UIBarButtonItem) { var item = BlockImageItem() item.label = NSLocalizedString("Image", comment: "Image") items.append(item) self.tableView.reloadData() self.showAssetSelector(item) } func AddAssetDone(controller: AddAssetTableViewController, asset: Asset) { self.dismissViewControllerAnimated(true, completion: nil) let vc = controller as! ImageSelectorTableViewController let item = vc.object item.asset = asset (item as! BlockImageItem).align = controller.imageAlign self.tableView.reloadData() } @IBAction func textAddButtonPushed(sender: UIBarButtonItem) { var item = BlockTextItem() item.label = NSLocalizedString("Text", comment: "Text") items.append(item) self.tableView.reloadData() self.showHTMLEditor(item) } @IBAction func previewButtonPushed(sender: UIBarButtonItem) { let vc = PreviewViewController() let nav = UINavigationController(rootViewController: vc) var html = self.makeHTML() vc.html = html self.presentViewController(nav, animated: true, completion: nil) } func makeItemsHTML()-> String { var html = "" for item in items { html += item.value() + "\n" } return html } func makeHTML()-> String { var html = "<!DOCTYPE html><html><head><title>Preview</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head><body>" html += self.makeItemsHTML() html += "</body></html>" return html } @IBAction func backButtonPushed(sender: UIBarButtonItem) { if self.makeItemsHTML() == blocks.value() { self.navigationController?.popViewControllerAnimated(true) return } blocks.isDirty = true Utils.confrimSave(self) } func guidanceCloseButtonPushed(sender: UIButton) { UIView.animateWithDuration(0.3, animations: {_ in self.guidanceBgView.alpha = 0.0 }, completion: {_ in self.guidanceBgView.removeFromSuperview() let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(true, forKey: "blocksGuidanceShowed") defaults.synchronize() } ) } } dirtyフラグのタイミングがおかしかったので修正 // // BlockEditorTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/10. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class BlockEditorTableViewController: BaseTableViewController, AddAssetDelegate { var blog: Blog! var entry: BaseEntry! var blocks: EntryBlocksItem! var items: [BaseEntryItem]! var noItemLabel = UILabel() var tophImage = UIImageView(image: UIImage(named: "guide_toph_sleep")) var guidanceBgView = UIView() 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() self.title = blocks.label items = blocks.blocks self.tableView.registerNib(UINib(nibName: "TextBlockTableViewCell", bundle: nil), forCellReuseIdentifier: "TextBlockTableViewCell") self.tableView.registerNib(UINib(nibName: "ImageBlockTableViewCell", bundle: nil), forCellReuseIdentifier: "ImageBlockTableViewCell") self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "saveButtonPushed:") self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:") self.view.addSubview(tophImage) tophImage.center = view.center var frame = tophImage.frame frame.origin.y = 109.0 tophImage.frame = frame noItemLabel.textColor = Color.placeholderText noItemLabel.font = UIFont.systemFontOfSize(18.0) noItemLabel.text = String(format: NSLocalizedString("No %@", comment: "No %@"), arguments: [blocks.label]) noItemLabel.sizeToFit() self.view.addSubview(noItemLabel) noItemLabel.center = view.center frame = noItemLabel.frame frame.origin.y = tophImage.frame.origin.y + tophImage.frame.size.height + 13.0 noItemLabel.frame = frame tophImage.hidden = true noItemLabel.hidden = true guidanceBgView.backgroundColor = colorize(0x000000, alpha: 0.3) let app = UIApplication.sharedApplication().delegate as! AppDelegate guidanceBgView.frame = app.window!.frame app.window!.addSubview(guidanceBgView) var guidanceView = BlockGuidanceView.instanceFromNib() as! BlockGuidanceView guidanceView.closeButton.addTarget(self, action: "guidanceCloseButtonPushed:", forControlEvents: UIControlEvents.TouchUpInside) guidanceBgView.addSubview(guidanceView) guidanceView.center = guidanceBgView.center frame = guidanceView.frame frame.origin.y = 70.0 guidanceView.frame = frame let defaults = NSUserDefaults.standardUserDefaults() let showed = defaults.boolForKey("blocksGuidanceShowed") if showed { guidanceBgView.removeFromSuperview() } self.tableView.backgroundColor = Color.tableBg } override func viewWillAppear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setToolbarHidden(false, animated: false) self.makeToolbarItems(false) self.tableView.reloadData() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setToolbarHidden(true, animated: false) } 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 Potentially incomplete method implementation. // Return the number of sections. if items == nil { return 0 } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. if items == nil { return 0 } tophImage.hidden = !(items.count == 0) noItemLabel.hidden = !(items.count == 0) return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() // Configure the cell... let item = items[indexPath.row] if item.type == "textarea" { var c = tableView.dequeueReusableCellWithIdentifier("TextBlockTableViewCell", forIndexPath: indexPath) as! TextBlockTableViewCell var text = item.dispValue() if text.isEmpty { c.placeholderLabel?.text = (item as! EntryTextAreaItem).placeholder() c.placeholderLabel.hidden = false c.blockTextLabel.hidden = true } else { c.blockTextLabel?.text = Utils.removeHTMLTags(text) c.placeholderLabel.hidden = true c.blockTextLabel.hidden = false } cell = c } else { var c = tableView.dequeueReusableCellWithIdentifier("ImageBlockTableViewCell", forIndexPath: indexPath) as! ImageBlockTableViewCell c.blockImageView.sd_setImageWithURL(NSURL(string: item.dispValue())) cell = c } self.adjustCellLayoutMargins(cell) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110.0 } /* // 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 items.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } /* // 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 } */ // 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 } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let item = items[sourceIndexPath.row]; items.removeAtIndex(sourceIndexPath.row); items.insert(item, atIndex: destinationIndexPath.row) } private func showHTMLEditor(object: EntryTextAreaItem) { if self.entry.editMode == Entry.EditMode.PlainText { let vc = EntryHTMLEditorViewController() vc.object = object vc.blog = blog vc.entry = entry self.navigationController?.pushViewController(vc, animated: true) } else { let vc = EntryRichTextViewController() vc.object = object self.navigationController?.pushViewController(vc, animated: true) } } private func showAssetSelector(object: EntryImageItem) { let storyboard: UIStoryboard = UIStoryboard(name: "ImageSelector", bundle: nil) let nav = storyboard.instantiateInitialViewController() as! UINavigationController let vc = nav.topViewController as! ImageSelectorTableViewController vc.blog = blog vc.delegate = self vc.showAlign = true vc.object = object vc.entry = self.entry self.presentViewController(nav, animated: true, completion: nil) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if let items = self.items { let item = items[indexPath.row] if item.type == "textarea" { self.showHTMLEditor(item as! EntryTextAreaItem) } else if item.type == "image" { self.showAssetSelector(item as! EntryImageItem) } } } /* // 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. } */ @IBAction func saveButtonPushed(sender: UIBarButtonItem) { blocks.blocks = self.items blocks.isDirty = true self.navigationController?.popViewControllerAnimated(true) } private func makeToolbarItems(editMode: Bool) { var buttons = [UIBarButtonItem]() if editMode { var flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:") buttons = [flexible, doneButton] } else { var cameraButton = UIBarButtonItem(image: UIImage(named: "btn_camera"), left: true, target: self, action: "cameraButtonPushed:") var textAddButton = UIBarButtonItem(image: UIImage(named: "btn_textadd"), left: false, target: self, action: "textAddButtonPushed:") var flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var previewButton = UIBarButtonItem(image: UIImage(named: "btn_preview"), style: UIBarButtonItemStyle.Plain, target: self, action: "previewButtonPushed:") var editButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editButtonPushed:") buttons = [cameraButton, textAddButton, flexible, previewButton, editButton] } self.setToolbarItems(buttons, animated: true) } @IBAction func editButtonPushed(sender: UIBarButtonItem) { self.tableView.setEditing(true, animated: true) self.navigationItem.rightBarButtonItem?.enabled = false self.makeToolbarItems(true) } @IBAction func doneButtonPushed(sender: UIBarButtonItem) { self.tableView.setEditing(false, animated: true) self.navigationItem.rightBarButtonItem?.enabled = true self.makeToolbarItems(false) } @IBAction func cameraButtonPushed(sender: UIBarButtonItem) { var item = BlockImageItem() item.label = NSLocalizedString("Image", comment: "Image") items.append(item) self.tableView.reloadData() self.showAssetSelector(item) } func AddAssetDone(controller: AddAssetTableViewController, asset: Asset) { self.dismissViewControllerAnimated(true, completion: nil) let vc = controller as! ImageSelectorTableViewController let item = vc.object item.asset = asset (item as! BlockImageItem).align = controller.imageAlign self.tableView.reloadData() } @IBAction func textAddButtonPushed(sender: UIBarButtonItem) { var item = BlockTextItem() item.label = NSLocalizedString("Text", comment: "Text") items.append(item) self.tableView.reloadData() self.showHTMLEditor(item) } @IBAction func previewButtonPushed(sender: UIBarButtonItem) { let vc = PreviewViewController() let nav = UINavigationController(rootViewController: vc) var html = self.makeHTML() vc.html = html self.presentViewController(nav, animated: true, completion: nil) } func makeItemsHTML()-> String { var html = "" for item in items { html += item.value() + "\n" } return html } func makeHTML()-> String { var html = "<!DOCTYPE html><html><head><title>Preview</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head><body>" html += self.makeItemsHTML() html += "</body></html>" return html } @IBAction func backButtonPushed(sender: UIBarButtonItem) { if self.makeItemsHTML() == blocks.value() { self.navigationController?.popViewControllerAnimated(true) return } Utils.confrimSave(self) } func guidanceCloseButtonPushed(sender: UIButton) { UIView.animateWithDuration(0.3, animations: {_ in self.guidanceBgView.alpha = 0.0 }, completion: {_ in self.guidanceBgView.removeFromSuperview() let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(true, forKey: "blocksGuidanceShowed") defaults.synchronize() } ) } }
// // VIMVideoTests.swift // VimeoNetworkingExample-iOS // // Copyright © 2017 Vimeo. 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 XCTest @testable import VimeoNetworking class VIMVideoTests: XCTestCase { private var liveDictionary: [String: Any] = ["link": "vimeo.com", "key": "abcdefg", "activeTime": Date(), "endedTime": Date(), "archivedTime": Date()] func test_isLive_returnsTrue_whenLiveObjectExists() { let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLive()) } func test_isLive_returnsFalse_whenLiveObjectDoesNotExist() { let videoDictionary: [String: Any] = ["link": "vimeo.com"] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testVideoObject) XCTAssertFalse(testVideoObject.isLive()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInUnavailablePreBroadcastState() { liveDictionary["status"] = "unavailable" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInPendingPreBroadcastState() { liveDictionary["status"] = "pending" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInReadyPreBroadcastState() { liveDictionary["status"] = "ready" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInMidBroadcastState() { liveDictionary["status"] = "streaming" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInArchivingState() { liveDictionary["status"] = "archiving" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsFalse_whenEventIsInPostBroadcastState() { liveDictionary["status"] = "done" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertFalse(testVideoObject.isLiveEventInProgress()) } func test_isPostBroadcast_returnsTrue_whenEventIsInDoneState() { liveDictionary["status"] = "done" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isPostBroadcast()) } // MARK: - Review Page func test_video_has_review_page() { let reviewPageDictionary: [String: Any] = ["active": true, "link": "test/linkNotEmpty"] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(reviewObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.hasReviewPage()) } func test_video_hasnt_review_page() { let reviewPageDictionary: [String: Any] = ["active": true, "link": ""] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertFalse(testVideoObject.hasReviewPage()) } func test_video_hasnt_review_page_because_is_inactive() { let reviewPageDictionary: [String: Any] = ["active": false, "link": "test/LinkExistButIsNotActive"] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertEqual(testVideoObject.hasReviewPage(), false) } // MARK: - Privacy // Note: Invalid values of `canDownload` will trigger an assertion failure. func test_canDownloadFromDesktop_returnsTrue_whenCanDownloadIsOne() { let privacyDictionary: [String: Any] = ["canDownload": 1] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! let canDownload = testVideoObject.canDownloadFromDesktop() XCTAssertTrue(canDownload, "canDownloadFromDesktop unexpectedly returns false") } func test_canDownloadFromDesktop_returnsFalse_whenCanDownloadIsZero() { let privacyDictionary: [String: Any] = ["canDownload": 0] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! let canDownload = testVideoObject.canDownloadFromDesktop() XCTAssertFalse(canDownload, "canDownloadFromDesktop unexpectedly returns true") } } Add tests for isStock() method // // VIMVideoTests.swift // VimeoNetworkingExample-iOS // // Copyright © 2017 Vimeo. 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 XCTest @testable import VimeoNetworking class VIMVideoTests: XCTestCase { private var liveDictionary: [String: Any] = ["link": "vimeo.com", "key": "abcdefg", "activeTime": Date(), "endedTime": Date(), "archivedTime": Date()] func test_isLive_returnsTrue_whenLiveObjectExists() { let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLive()) } func test_isLive_returnsFalse_whenLiveObjectDoesNotExist() { let videoDictionary: [String: Any] = ["link": "vimeo.com"] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testVideoObject) XCTAssertFalse(testVideoObject.isLive()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInUnavailablePreBroadcastState() { liveDictionary["status"] = "unavailable" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInPendingPreBroadcastState() { liveDictionary["status"] = "pending" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInReadyPreBroadcastState() { liveDictionary["status"] = "ready" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInMidBroadcastState() { liveDictionary["status"] = "streaming" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsTrue_whenEventIsInArchivingState() { liveDictionary["status"] = "archiving" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isLiveEventInProgress()) } func test_isLiveEventInProgress_returnsFalse_whenEventIsInPostBroadcastState() { liveDictionary["status"] = "done" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertFalse(testVideoObject.isLiveEventInProgress()) } func test_isPostBroadcast_returnsTrue_whenEventIsInDoneState() { liveDictionary["status"] = "done" let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)! let videoDictionary: [String: Any] = ["live": testLiveObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(testLiveObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.isPostBroadcast()) } // MARK: - Review Page func test_video_has_review_page() { let reviewPageDictionary: [String: Any] = ["active": true, "link": "test/linkNotEmpty"] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertNotNil(reviewObject) XCTAssertNotNil(testVideoObject) XCTAssertTrue(testVideoObject.hasReviewPage()) } func test_video_hasnt_review_page() { let reviewPageDictionary: [String: Any] = ["active": true, "link": ""] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertFalse(testVideoObject.hasReviewPage()) } func test_video_hasnt_review_page_because_is_inactive() { let reviewPageDictionary: [String: Any] = ["active": false, "link": "test/LinkExistButIsNotActive"] let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))! let videoDictionary: [String: Any] = ["reviewPage": reviewObject] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertEqual(testVideoObject.hasReviewPage(), false) } // MARK: - Privacy // Note: Invalid values of `canDownload` will trigger an assertion failure. func test_canDownloadFromDesktop_returnsTrue_whenCanDownloadIsOne() { let privacyDictionary: [String: Any] = ["canDownload": 1] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! let canDownload = testVideoObject.canDownloadFromDesktop() XCTAssertTrue(canDownload, "canDownloadFromDesktop unexpectedly returns false") } func test_canDownloadFromDesktop_returnsFalse_whenCanDownloadIsZero() { let privacyDictionary: [String: Any] = ["canDownload": 0] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! let canDownload = testVideoObject.canDownloadFromDesktop() XCTAssertFalse(canDownload, "canDownloadFromDesktop unexpectedly returns true") } func test_isStock_returnsTrue_whenPrivacyViewIsStock() { let privacyDictionary: [String: Any] = ["view": "stock"] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertTrue(testVideoObject.isStock(), "Test video object was stock but unexpectedly returned false.") } func test_isStock_returnsFalse_whenPrivacyViewIsNotStock() { let privacyDictionary: [String: Any] = ["view": "unlisted"] let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)! let videoDictionary: [String: Any] = ["privacy": privacy as Any] let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)! XCTAssertFalse(testVideoObject.isStock(), "Test video object was not stock but unexpectedly returned true.") } }
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/22/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let oscillator = AKFMOscillator() connect(operatoscillatorion) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:oscillator) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let cutoffFrequency = AKLine(firstPoint: 220.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak) connect(cutoffFrequency) let bandwidth = AKLine(firstPoint: 10.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak) connect(bandwidth) let variableFrequencyResponseBandPassFilter = AKVariableFrequencyResponseBandPassFilter(audioSource: audioSource) variableFrequencyResponseBandPassFilter.cutoffFrequency = cutoffFrequency variableFrequencyResponseBandPassFilter.bandwidth = bandwidth connect(variableFrequencyResponseBandPassFilter) let balance = AKBalance(input: variableFrequencyResponseBandPassFilter, comparatorAudioSource: audioSource) connect(balance) enableParameterLog( "Cutoff Frequency = ", parameter: variableFrequencyResponseBandPassFilter.cutoffFrequency, timeInterval:0.1 ) enableParameterLog( "Bandwidth = ", parameter: variableFrequencyResponseBandPassFilter.bandwidth, timeInterval:0.1 ) connect(AKAudioOutput(audioSource:balance)) } } let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) AKOrchestra.testForDuration(testDuration) processor.play() instrument.play() while(AKManager.sharedManager().isRunning) {} //do nothing println("Test complete!") Fixed a cut and paste typo caught by tests // // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/22/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let oscillator = AKFMOscillator() connect(oscillator) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:oscillator) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let cutoffFrequency = AKLine(firstPoint: 220.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak) connect(cutoffFrequency) let bandwidth = AKLine(firstPoint: 10.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak) connect(bandwidth) let variableFrequencyResponseBandPassFilter = AKVariableFrequencyResponseBandPassFilter(audioSource: audioSource) variableFrequencyResponseBandPassFilter.cutoffFrequency = cutoffFrequency variableFrequencyResponseBandPassFilter.bandwidth = bandwidth connect(variableFrequencyResponseBandPassFilter) let balance = AKBalance(input: variableFrequencyResponseBandPassFilter, comparatorAudioSource: audioSource) connect(balance) enableParameterLog( "Cutoff Frequency = ", parameter: variableFrequencyResponseBandPassFilter.cutoffFrequency, timeInterval:0.1 ) enableParameterLog( "Bandwidth = ", parameter: variableFrequencyResponseBandPassFilter.bandwidth, timeInterval:0.1 ) connect(AKAudioOutput(audioSource:balance)) } } let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) AKOrchestra.testForDuration(testDuration) processor.play() instrument.play() while(AKManager.sharedManager().isRunning) {} //do nothing println("Test complete!")
// // fastqueue.swift // QQ // // Created by Guillaume Lessard on 2014-08-16. // Copyright (c) 2014 Guillaume Lessard. All rights reserved. // import Darwin final class FastQueue<T>: QueueType, SequenceType, GeneratorType { private var head: UnsafeMutablePointer<Node<T>> = nil private var tail: UnsafeMutablePointer<Node<T>> = nil private let pool = AtomicStackInit() // MARK: init/deinit init() { } convenience init(_ newElement: T) { self.init() enqueue(newElement) } deinit { // empty the queue while head != nil { let node = head head = node.memory.next node.memory.elem.destroy() node.memory.elem.dealloc(1) node.dealloc(1) } // drain the pool while UnsafePointer<COpaquePointer>(pool).memory != nil { let node = UnsafeMutablePointer<Node<T>>(OSAtomicDequeue(pool, 0)) node.memory.elem.dealloc(1) node.dealloc(1) } // release the pool stack structure AtomicStackRelease(pool) } // MARK: QueueType interface var isEmpty: Bool { return head == nil } var count: Int { return (head == nil) ? 0 : countElements() } func countElements() -> Int { // Not thread safe. var i = 0 var node = head while node != nil { // Iterate along the linked nodes while counting node = node.memory.next i++ } return i } func enqueue(newElement: T) { var node = UnsafeMutablePointer<Node<T>>(OSAtomicDequeue(pool, 0)) if node == nil { node = UnsafeMutablePointer<Node<T>>.alloc(1) node.memory = Node(UnsafeMutablePointer<T>.alloc(1)) } node.memory.next = nil node.memory.elem.initialize(newElement) if head == nil { head = node tail = node } else { tail.memory.next = node tail = node } } func dequeue() -> T? { let node = head if node != nil { // Promote the 2nd item to 1st head = node.memory.next let element = node.memory.elem.move() OSAtomicEnqueue(pool, node, 0) return element } return nil } // MARK: GeneratorType implementation func next() -> T? { return dequeue() } // MARK: SequenceType implementation func generate() -> Self { return self } } private struct Node<T> { var next: UnsafeMutablePointer<Node<T>> = nil let elem: UnsafeMutablePointer<T> init(_ p: UnsafeMutablePointer<T>) { elem = p } } Further simplified FastQueue. The way it was intended. We still have typecasting with a getter and setter for the pointer to the next node, but this is likely to not be needed soon. // // fastqueue.swift // QQ // // Created by Guillaume Lessard on 2014-08-16. // Copyright (c) 2014 Guillaume Lessard. All rights reserved. // import Darwin final class FastQueue<T>: QueueType, SequenceType, GeneratorType { private var head: UnsafeMutablePointer<Node<T>> = nil private var tail: UnsafeMutablePointer<Node<T>> = nil private let pool = AtomicStackInit() // MARK: init/deinit init() { } convenience init(_ newElement: T) { self.init() enqueue(newElement) } deinit { // empty the queue while head != nil { let node = head head = node.memory.next node.destroy() node.dealloc(1) } // drain the pool while UnsafePointer<COpaquePointer>(pool).memory != nil { let node = UnsafeMutablePointer<Node<T>>(OSAtomicDequeue(pool, 0)) node.dealloc(1) } // release the pool stack structure AtomicStackRelease(pool) } // MARK: QueueType interface var isEmpty: Bool { return head == nil } var count: Int { return (head == nil) ? 0 : countElements() } func countElements() -> Int { // Not thread safe. var i = 0 var node = head while node != nil { // Iterate along the linked nodes while counting node = node.memory.next i++ } return i } func enqueue(newElement: T) { var node = UnsafeMutablePointer<Node<T>>(OSAtomicDequeue(pool, 0)) if node == nil { node = UnsafeMutablePointer<Node<T>>.alloc(1) } node.initialize(Node(newElement)) if head == nil { head = node tail = node } else { tail.memory.next = node tail = node } } func dequeue() -> T? { let node = head if node != nil { // Promote the 2nd item to 1st head = node.memory.next let element = node.memory.elem node.destroy() OSAtomicEnqueue(pool, node, 0) return element } return nil } // MARK: GeneratorType implementation func next() -> T? { return dequeue() } // MARK: SequenceType implementation func generate() -> Self { return self } } private struct Node<T> { var nptr: UnsafeMutablePointer<Void> = nil let elem: T init(_ e: T) { elem = e } var next: UnsafeMutablePointer<Node<T>> { get { return UnsafeMutablePointer<Node<T>>(nptr) } set { nptr = UnsafeMutablePointer<Void>(newValue) } } }
// // ViewController.swift // MyWKWebViewProto // // Created by Distributed on 06/12/2016. // Copyright © 2016 Seven Years Later. All rights reserved. // import Cocoa import WebKit class ViewController: NSViewController, WKUIDelegate { var webView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: self.view.bounds, configuration: webConfiguration) webView?.uiDelegate = self view = webView! // Allows for Web Inspector in WKWebView with ctrl click self.webView?.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") _ = webView?.loadHTMLString(mySVGString(), baseURL: nil) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func mySVGString() -> String { let str = "<!DOCTYPE html>\n" + "<html>\n" + "\t<head>\n" + "\t\t<title>\n" + "\t\t</title>\n" + "<script>\n" + "//<![CDATA[ \n\n" + "function startMove(event, moveType){\n" + "\tx1 = event.clientX;\n" + "\ty1 = event.clientY;\n" + "\tdocument.documentElement.setAttribute(\"onmousemove\",\"moveIt(event)\");\n" + "\t\tif (moveType == \'single\'){\n" + "\t\t\tC = event.target;\n" + "} " + "else {\n" + "\t\tC = event.target.parentNode;\n" + "\t}\n" + "}\n\n" + "function moveIt(event){\n" + "\ttranslation = C.getAttributeNS(null, \"transform\").slice(10,-1).split(\' \');\n" + "\tsx = parseInt(translation[0]);\n" + "\tsy = parseInt(translation[1]);\n" + "\tC.setAttributeNS(null, \"transform\", \"translate(\" + (sx + event.clientX - x1) + \" \" + (sy + event.clientY - y1) + \")\");\n" + "\tx1 = event.clientX;\n" + "\ty1 = event.clientY;\n" + "}\n\n" + "function endMove(){\n" + "\tdocument.documentElement.setAttributeNS(null, \"onmousemove\",null);\n" + "}\n\n" + "//]]>\n\n</script>\n" + "</head>\n\n" + "<body style=\"margin:0px; padding:0px;\" >\n" + "\t<svg width=\"800\" height=\"600\">\n" + "\t\t<rect width=\"800\" height=\"600\" fill=\"#fcfaef\">\n" + "\t\t</rect>\n" + "\t\t\t<g transform=\"translate(0 0)\">\n" + "\t\t\t\t<circle id=\"circle1\"" + "onmousedown=\"startMove(evt, \'single\')\" onmouseup=\"endMove()\"" + "transform=\"translate(60 200)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"blue\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t\t<circle id=\"circle2\"" + "onmousedown=\"startMove(evt, \'single\')\" onmouseup=\"endMove()\"" + "transform=\"translate(200 200)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"grey\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t\t<circle id=\"circle3\"" + "onmousedown=\"startMove(evt, \'group\')\" onmouseup=\"endMove()\"" + "transform=\"translate(50 50)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"orange\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t</g>\n" + "\t</svg>\n" + "</body>\n" + "</html>\n" return str } } Update ViewController.swift add x,y = 0 to rect // // ViewController.swift // MyWKWebViewProto // // Created by Distributed on 06/12/2016. // Copyright © 2016 Seven Years Later. All rights reserved. // import Cocoa import WebKit class ViewController: NSViewController, WKUIDelegate { var webView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: self.view.bounds, configuration: webConfiguration) webView?.uiDelegate = self view = webView! // Allows for Web Inspector in WKWebView with ctrl click self.webView?.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") _ = webView?.loadHTMLString(mySVGString(), baseURL: nil) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func mySVGString() -> String { let str = "<!DOCTYPE html>\n" + "<html>\n" + "\t<head>\n" + "\t\t<title>\n" + "\t\t</title>\n" + "<script>\n" + "//<![CDATA[ \n\n" + "function startMove(event, moveType){\n" + "\tx1 = event.clientX;\n" + "\ty1 = event.clientY;\n" + "\tdocument.documentElement.setAttribute(\"onmousemove\",\"moveIt(event)\");\n" + "\t\tif (moveType == \'single\'){\n" + "\t\t\tC = event.target;\n" + "} " + "else {\n" + "\t\tC = event.target.parentNode;\n" + "\t}\n" + "}\n\n" + "function moveIt(event){\n" + "\ttranslation = C.getAttributeNS(null, \"transform\").slice(10,-1).split(\' \');\n" + "\tsx = parseInt(translation[0]);\n" + "\tsy = parseInt(translation[1]);\n" + "\tC.setAttributeNS(null, \"transform\", \"translate(\" + (sx + event.clientX - x1) + \" \" + (sy + event.clientY - y1) + \")\");\n" + "\tx1 = event.clientX;\n" + "\ty1 = event.clientY;\n" + "}\n\n" + "function endMove(){\n" + "\tdocument.documentElement.setAttributeNS(null, \"onmousemove\",null);\n" + "}\n\n" + "//]]>\n\n</script>\n" + "</head>\n\n" + "<body style=\"margin:0px; padding:0px;\" >\n" + "\t<svg width=\"800\" height=\"600\">\n" + "\t\t<rect x=\"0\" y=\"0\" width=\"800\" height=\"600\" fill=\"#fcfaef\">\n" + "\t\t</rect>\n" + "\t\t\t<g transform=\"translate(0 0)\">\n" + "\t\t\t\t<circle id=\"circle1\"" + "onmousedown=\"startMove(evt, \'single\')\" onmouseup=\"endMove()\"" + "transform=\"translate(60 200)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"blue\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t\t<circle id=\"circle2\"" + "onmousedown=\"startMove(evt, \'single\')\" onmouseup=\"endMove()\"" + "transform=\"translate(200 200)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"grey\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t\t<circle id=\"circle3\"" + "onmousedown=\"startMove(evt, \'group\')\" onmouseup=\"endMove()\"" + "transform=\"translate(50 50)\" cx=\"0\" cy=\"0\" r=\"22\"" + "fill=\"orange\" stroke=\"black\" stroke-width=\"8\"></circle>\n" + "\t\t\t</g>\n" + "\t</svg>\n" + "</body>\n" + "</html>\n" return str } }
// // PermissionScope.swift // PermissionScope // // Created by Nick O'Neill on 4/5/15. // Copyright (c) 2015 That Thing in Swift. All rights reserved. // import UIKit import CoreLocation import AddressBook import AVFoundation import Photos import EventKit import CoreBluetooth import CoreMotion import HealthKit import CloudKit public typealias statusRequestClosure = (status: PermissionStatus) -> Void @objc public class PermissionScope: UIViewController, CLLocationManagerDelegate, UIGestureRecognizerDelegate, CBPeripheralManagerDelegate { // MARK: UI Parameters public let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) public let bodyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 240, height: 70)) public var tintColor = UIColor(red: 0, green: 0.47, blue: 1, alpha: 1) public var buttonFont = UIFont.boldSystemFontOfSize(14) public var labelFont = UIFont.systemFontOfSize(14) public var closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 32)) public var closeOffset = CGSizeZero public var authorizedButtonColor = UIColor(red: 0, green: 0.47, blue: 1, alpha: 1) public var unauthorizedButtonColor:UIColor? // MARK: View hierarchy for custom alert let baseView = UIView() let contentView = UIView() // MARK: - Various lazy managers lazy var locationManager:CLLocationManager = { let lm = CLLocationManager() lm.delegate = self return lm }() lazy var bluetoothManager:CBPeripheralManager = { return CBPeripheralManager(delegate: self, queue: nil, options:[CBPeripheralManagerOptionShowPowerAlertKey: true]) }() lazy var motionManager:CMMotionActivityManager = { return CMMotionActivityManager() }() /// NSUserDefaults standardDefaults lazy var lazy var defaults:NSUserDefaults = { return .standardUserDefaults() }() /// Default status for CoreMotion var motionPermissionStatus: PermissionStatus = .Unknown // MARK: - Internal state and resolution /// Permissions configured using addPermission(:) var configuredPermissions: [PermissionConfig] = [] var permissionButtons: [UIButton] = [] var permissionLabels: [UILabel] = [] // Useful for direct use of the request* methods public var authChangeClosure: authClosureType? = nil public typealias authClosureType = (Bool, [PermissionResult]) -> Void public var cancelClosure: cancelClosureType? = nil public typealias cancelClosureType = ([PermissionResult]) -> Void /** Called when the user has disabled or denied access to notifications, and we're presenting them with a help dialog. */ public var disabledOrDeniedClosure: cancelClosureType? = nil /** View controller to be used when presenting alerts. Defaults to self. You'll want to set this if you are calling the `request*` methods directly. */ public var viewControllerForAlerts : UIViewController? // Computed variables func allAuthorized(completion: (Bool) -> Void ) { getResultsForConfig{ (results) -> Void in let result = results .first { $0.status != .Authorized } .isNil completion(result) } } func requiredAuthorized(completion: (Bool) -> Void ) { getResultsForConfig{ (results) -> Void in let result = results .first { $0.status != .Authorized } .isNil completion(result) } } // use the code we have to see permission status public func permissionStatuses(permissionTypes: [PermissionType]?) -> Dictionary<PermissionType, PermissionStatus> { var statuses: Dictionary<PermissionType, PermissionStatus> = [:] let types: [PermissionType] = permissionTypes ?? PermissionType.allValues for type in types { statusForPermission(type, completion: { (status) -> Void in statuses[type] = status }) } return statuses } public init(backgroundTapCancels: Bool) { super.init(nibName: nil, bundle: nil) viewControllerForAlerts = self // Set up main view view.frame = UIScreen.mainScreen().bounds view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0.7) view.addSubview(baseView) // Base View baseView.frame = view.frame baseView.addSubview(contentView) if backgroundTapCancels { let tap = UITapGestureRecognizer(target: self, action: Selector("cancel")) tap.delegate = self baseView.addGestureRecognizer(tap) } // Content View contentView.backgroundColor = UIColor.whiteColor() contentView.layer.cornerRadius = 10 contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 // header label headerLabel.font = UIFont.systemFontOfSize(22) headerLabel.textColor = UIColor.blackColor() headerLabel.textAlignment = NSTextAlignment.Center headerLabel.text = "Hey, listen!" // headerLabel.backgroundColor = UIColor.redColor() contentView.addSubview(headerLabel) // body label bodyLabel.font = UIFont.boldSystemFontOfSize(16) bodyLabel.textColor = UIColor.blackColor() bodyLabel.textAlignment = NSTextAlignment.Center bodyLabel.text = "We need a couple things\r\nbefore you get started." bodyLabel.numberOfLines = 2 // bodyLabel.text = "We need\r\na couple things before you\r\nget started." // bodyLabel.backgroundColor = UIColor.redColor() contentView.addSubview(bodyLabel) // close button closeButton.setTitle("Close", forState: .Normal) closeButton.addTarget(self, action: Selector("cancel"), forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(closeButton) self.statusMotion() //Added to check motion status on load } public convenience init() { self.init(backgroundTapCancels: true) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let screenSize = UIScreen.mainScreen().bounds.size // Set background frame view.frame.size = screenSize // Set frames let x = (screenSize.width - Constants.UI.contentWidth) / 2 let dialogHeight: CGFloat switch self.configuredPermissions.count { case 2: dialogHeight = Constants.UI.dialogHeightTwoPermissions case 3: dialogHeight = Constants.UI.dialogHeightThreePermissions default: dialogHeight = Constants.UI.dialogHeightSinglePermission } let y = (screenSize.height - dialogHeight) / 2 contentView.frame = CGRect(x:x, y:y, width:Constants.UI.contentWidth, height:dialogHeight) // offset the header from the content center, compensate for the content's offset headerLabel.center = contentView.center headerLabel.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) headerLabel.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-50)) // ... same with the body bodyLabel.center = contentView.center bodyLabel.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) bodyLabel.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-100)) closeButton.center = contentView.center closeButton.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) closeButton.frame.offsetInPlace(dx: 105, dy: -((dialogHeight/2)-20)) closeButton.frame.offsetInPlace(dx: self.closeOffset.width, dy: self.closeOffset.height) if closeButton.imageView?.image != nil { closeButton.setTitle("", forState: .Normal) } closeButton.setTitleColor(tintColor, forState: .Normal) let baseOffset = 95 var index = 0 for button in permissionButtons { button.center = contentView.center button.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) button.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-160) + CGFloat(index * baseOffset)) let type = configuredPermissions[index].type statusForPermission(type, completion: { (currentStatus) -> Void in let prettyDescription = type.prettyDescription if currentStatus == .Authorized { self.setButtonAuthorizedStyle(button) button.setTitle("Allowed \(prettyDescription)".localized.uppercaseString, forState: .Normal) } else if currentStatus == .Unauthorized { self.setButtonUnauthorizedStyle(button) button.setTitle("Denied \(prettyDescription)".localized.uppercaseString, forState: .Normal) } else if currentStatus == .Disabled { // setButtonDisabledStyle(button) button.setTitle("\(prettyDescription) Disabled".localized.uppercaseString, forState: .Normal) } let label = self.permissionLabels[index] label.center = self.contentView.center label.frame.offsetInPlace(dx: -self.contentView.frame.origin.x, dy: -self.contentView.frame.origin.y) label.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-205) + CGFloat(index * baseOffset)) index++ }) } } // MARK: - Customizing the permissions @objc public func addPermission(config: PermissionConfig) { assert(!config.message.isEmpty, "Including a message about your permission usage is helpful") assert(configuredPermissions.count < 3, "Ask for three or fewer permissions at a time") assert(configuredPermissions.filter { $0.type == config.type }.isEmpty, "Permission for \(config.type) already set") configuredPermissions.append(config) if config.type == .Bluetooth && askedBluetooth { triggerBluetoothStatusUpdate() } else if config.type == .Motion && askedMotion { triggerMotionStatusUpdate() } } func permissionStyledButton(type: PermissionType) -> UIButton { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 220, height: 40)) button.setTitleColor(tintColor, forState: .Normal) button.titleLabel?.font = buttonFont button.layer.borderWidth = 1 button.layer.borderColor = tintColor.CGColor button.layer.cornerRadius = 6 // this is a bit of a mess, eh? switch type { case .LocationAlways, .LocationInUse: button.setTitle("Enable \(type.prettyDescription)".localized.uppercaseString, forState: .Normal) default: button.setTitle("Allow \(type)".localized.uppercaseString, forState: .Normal) } button.addTarget(self, action: Selector("request\(type)"), forControlEvents: .TouchUpInside) return button } func setButtonAuthorizedStyle(button: UIButton) { button.layer.borderWidth = 0 button.backgroundColor = authorizedButtonColor button.setTitleColor(.whiteColor(), forState: .Normal) } func setButtonUnauthorizedStyle(button: UIButton) { button.layer.borderWidth = 0 button.backgroundColor = unauthorizedButtonColor ?? authorizedButtonColor.inverseColor button.setTitleColor(.whiteColor(), forState: .Normal) } func permissionStyledLabel(message: String) -> UILabel { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 260, height: 50)) label.font = labelFont label.numberOfLines = 2 label.textAlignment = .Center label.text = message // label.backgroundColor = UIColor.greenColor() return label } // MARK: - Status and Requests for each permission // MARK: Location public func statusLocationAlways() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .Disabled } let status = CLLocationManager.authorizationStatus() switch status { case .AuthorizedAlways: return .Authorized case .Restricted, .Denied: return .Unauthorized case .AuthorizedWhenInUse: // Curious why this happens? Details on upgrading from WhenInUse to Always: // https://github.com/nickoneill/PermissionScope/issues/24 if defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedInUseToAlwaysUpgrade) { return .Unauthorized } else { return .Unknown } case .NotDetermined: return .Unknown } } public func requestLocationAlways() { switch statusLocationAlways() { case .Unknown: if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedInUseToAlwaysUpgrade) defaults.synchronize() } locationManager.requestAlwaysAuthorization() case .Unauthorized: self.showDeniedAlert(.LocationAlways) case .Disabled: self.showDisabledAlert(.LocationInUse) default: break } } public func statusLocationInUse() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .Disabled } let status = CLLocationManager.authorizationStatus() // if you're already "always" authorized, then you don't need in use // but the user can still demote you! So I still use them separately. switch status { case .AuthorizedWhenInUse, .AuthorizedAlways: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestLocationInUse() { switch statusLocationInUse() { case .Unknown: locationManager.requestWhenInUseAuthorization() case .Unauthorized: self.showDeniedAlert(.LocationInUse) case .Disabled: self.showDisabledAlert(.LocationInUse) default: break } } // MARK: Contacts public func statusContacts() -> PermissionStatus { let status = ABAddressBookGetAuthorizationStatus() switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestContacts() { switch statusContacts() { case .Unknown: ABAddressBookRequestAccessWithCompletion(nil) { (success, error) -> Void in self.detectAndCallback() } case .Unauthorized: self.showDeniedAlert(.Contacts) default: break } } // MARK: Notifications public func statusNotifications() -> PermissionStatus { let settings = UIApplication.sharedApplication().currentUserNotificationSettings() if let settingTypes = settings?.types where settingTypes != UIUserNotificationType.None { return .Authorized } else { if defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedNotifications) { return .Unauthorized } else { return .Unknown } } } func showingNotificationPermission () { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("finishedShowingNotificationPermission"), name: UIApplicationDidBecomeActiveNotification, object: nil) notificationTimer?.invalidate() } var notificationTimer : NSTimer? func finishedShowingNotificationPermission () { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) notificationTimer?.invalidate() defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedNotifications) defaults.synchronize() getResultsForConfig { (results) -> Void in let _notificationResult = results .filter { $0.type == PermissionType.Notifications } .first guard let notificationResult = _notificationResult else { return } if notificationResult.status == .Unknown { self.showDeniedAlert(notificationResult.type) } else { self.detectAndCallback() } } } public func requestNotifications() { switch statusNotifications() { case .Unknown: let notificationsPermission = self.configuredPermissions .first { $0 is NotificationsPermissionConfig } as? NotificationsPermissionConfig guard let notificationsPermissionSet = notificationsPermission?.notificationCategories else { return } NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("showingNotificationPermission"), name: UIApplicationWillResignActiveNotification, object: nil) notificationTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("finishedShowingNotificationPermission"), userInfo: nil, repeats: false) UIApplication.sharedApplication().registerUserNotificationSettings( UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: notificationsPermissionSet) ) case .Unauthorized: showDeniedAlert(.Notifications) case .Disabled: showDisabledAlert(.Notifications) case .Authorized: break } } // MARK: Microphone public func statusMicrophone() -> PermissionStatus { switch AVAudioSession.sharedInstance().recordPermission() { case AVAudioSessionRecordPermission.Denied: return .Unauthorized case AVAudioSessionRecordPermission.Granted: return .Authorized default: return .Unknown } } public func requestMicrophone() { switch statusMicrophone() { case .Unknown: AVAudioSession.sharedInstance().requestRecordPermission({ (granted) -> Void in self.detectAndCallback() }) case .Unauthorized: showDeniedAlert(.Microphone) case .Disabled: showDisabledAlert(.Microphone) case .Authorized: break } } // MARK: Camera public func statusCamera() -> PermissionStatus { let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestCamera() { switch statusCamera() { case .Unknown: AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) -> Void in self.detectAndCallback() }) case .Unauthorized: showDeniedAlert(.Camera) case .Disabled: showDisabledAlert(.Camera) case .Authorized: break } } // MARK: Photos public func statusPhotos() -> PermissionStatus { let status = PHPhotoLibrary.authorizationStatus() switch status { case .Authorized: return .Authorized case .Denied, .Restricted: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestPhotos() { switch statusPhotos() { case .Unknown: PHPhotoLibrary.requestAuthorization({ (status) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Photos) case .Disabled: showDisabledAlert(.Photos) case .Authorized: break } } // MARK: Reminders public func statusReminders() -> PermissionStatus { let status = EKEventStore.authorizationStatusForEntityType(.Reminder) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestReminders() { switch statusReminders() { case .Unknown: EKEventStore().requestAccessToEntityType(.Reminder, completion: { (granted, error) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Reminders) default: break } } // MARK: Events public func statusEvents() -> PermissionStatus { let status = EKEventStore.authorizationStatusForEntityType(.Event) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestEvents() { switch statusEvents() { case .Unknown: EKEventStore().requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Events) default: break } } // MARK: Bluetooth private var askedBluetooth:Bool { get { return defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedBluetooth) } set { defaults.setBool(newValue, forKey: Constants.NSUserDefaultsKeys.requestedBluetooth) defaults.synchronize() } } private var waitingForBluetooth = false public func statusBluetooth() -> PermissionStatus { // if already asked for bluetooth before, do a request to get status, else wait for user to request if askedBluetooth{ triggerBluetoothStatusUpdate() } else { return .Unknown } switch (bluetoothManager.state, CBPeripheralManager.authorizationStatus()) { case (.Unsupported, _), (.PoweredOff, _), (_, .Restricted): return .Disabled case (.Unauthorized, _), (_, .Denied): return .Unauthorized case (.PoweredOn, .Authorized): return .Authorized default: return .Unknown } } public func requestBluetooth() { switch statusBluetooth() { case .Disabled: showDisabledAlert(.Bluetooth) case .Unauthorized: showDeniedAlert(.Bluetooth) case .Unknown: triggerBluetoothStatusUpdate() default: break } } private func triggerBluetoothStatusUpdate() { if !waitingForBluetooth && bluetoothManager.state == .Unknown { bluetoothManager.startAdvertising(nil) bluetoothManager.stopAdvertising() askedBluetooth = true waitingForBluetooth = true } } // MARK: CoreMotion public func statusMotion() -> PermissionStatus { if askedMotion{ triggerMotionStatusUpdate() } return motionPermissionStatus } public func requestMotion() { switch statusMotion() { case .Unauthorized: showDeniedAlert(.Motion) case .Unknown: triggerMotionStatusUpdate() default: break } } private func triggerMotionStatusUpdate() { let tmpMotionPermissionStatus = motionPermissionStatus defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedMotion) defaults.synchronize() motionManager.queryActivityStartingFromDate(NSDate(), toDate: NSDate(), toQueue: NSOperationQueue.mainQueue(), withHandler: { (_: [CMMotionActivity]?, error:NSError?) -> Void in if (error != nil && error!.code == Int(CMErrorMotionActivityNotAuthorized.rawValue)) { self.motionPermissionStatus = .Unauthorized } else{ self.motionPermissionStatus = .Authorized } self.motionManager.stopActivityUpdates() if (tmpMotionPermissionStatus != self.motionPermissionStatus){ self.waitingForMotion = false self.detectAndCallback() } }) askedMotion = true waitingForMotion = true } private var askedMotion:Bool { get { return defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedMotion) } set { defaults.setBool(newValue, forKey: Constants.NSUserDefaultsKeys.requestedMotion) defaults.synchronize() } } private var waitingForMotion = false // MARK: HealthKit public func statusHealthKit(typesToShare: Set<HKSampleType>?, typesToRead: Set<HKObjectType>?) -> PermissionStatus { guard HKHealthStore.isHealthDataAvailable() else { return .Disabled } var statusArray:[HKAuthorizationStatus] = [] typesToShare?.forEach({ (elem) -> () in statusArray.append(HKHealthStore().authorizationStatusForType(elem)) }) typesToRead?.forEach({ (elem) -> () in statusArray.append(HKHealthStore().authorizationStatusForType(elem)) }) // TODO: What to do? If there's 1 .Denied or ND then return such result ? // Only Auth if they are all Auth ? let typesAuthorized = statusArray .filter { $0 == .SharingAuthorized } let typesDenied = statusArray .filter { $0 == .SharingDenied } let typesNotDetermined = statusArray .filter { $0 == .NotDetermined } if typesNotDetermined.count == statusArray.count || statusArray.isEmpty { return .Unknown } else if !typesDenied.isEmpty { return .Unauthorized } else { return .Authorized } } func requestHealthKit() { guard let healthPermission = self.configuredPermissions .first({ $0.type == .HealthKit }) as? HealthPermissionConfig else { return } switch statusHealthKit(healthPermission.healthTypesToShare, typesToRead: healthPermission.healthTypesToRead) { case .Unknown: HKHealthStore().requestAuthorizationToShareTypes(healthPermission.healthTypesToShare, readTypes: healthPermission.healthTypesToRead, completion: { (granted, error) -> Void in if let error = error { print("error: ", error) } self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.HealthKit) case .Disabled: self.showDisabledAlert(.HealthKit) case .Authorized: break } } // MARK: CloudKit public func statusCloudKit(statusCallback: statusRequestClosure) { CKContainer.defaultContainer().statusForApplicationPermission(.UserDiscoverability) { (status, error) -> Void in switch status { case .InitialState: statusCallback(status: .Unknown) case .Granted: statusCallback(status: .Authorized) case .Denied: statusCallback(status: .Unauthorized) case .CouldNotComplete: // Error ocurred. print(error!.localizedDescription) // TODO: What should we return ? Use throws ? statusCallback(status: .Unknown) } } } public func requestCloudKit() { CKContainer.defaultContainer().accountStatusWithCompletionHandler { (status, error) -> Void in // log error? switch status { case .Available: CKContainer.defaultContainer().requestApplicationPermission(.UserDiscoverability, completionHandler: { (status2, error2) -> Void in self.detectAndCallback() }) case .Restricted, .NoAccount: self.showDisabledAlert(.CloudKit) case .CouldNotDetermine: // Ask user to login to iCloud break } } } // MARK: - UI @objc public func show(authChange: ((finished: Bool, results: [PermissionResult]) -> Void)? = nil, cancelled: ((results: [PermissionResult]) -> Void)? = nil) { assert(!configuredPermissions.isEmpty, "Please add at least one permission") authChangeClosure = authChange cancelClosure = cancelled dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { while self.waitingForBluetooth || self.waitingForMotion { } // call other methods that need to wait before show // no missing required perms? callback and do nothing self.requiredAuthorized({ (areAuthorized) -> Void in if areAuthorized { self.getResultsForConfig({ (results) -> Void in self.authChangeClosure?(true, results) }) } else { dispatch_async(dispatch_get_main_queue()) { self.showAlert() } } }) } } private func showAlert() { // add the backing views let window = UIApplication.sharedApplication().keyWindow! window.addSubview(view) view.frame = window.bounds baseView.frame = window.bounds for button in permissionButtons { button.removeFromSuperview() } permissionButtons = [] for label in permissionLabels { label.removeFromSuperview() } permissionLabels = [] // create the buttons for config in configuredPermissions { let button = permissionStyledButton(config.type) permissionButtons.append(button) contentView.addSubview(button) let label = permissionStyledLabel(config.message) permissionLabels.append(label) contentView.addSubview(label) } self.view.setNeedsLayout() // slide in the view self.baseView.frame.origin.y = self.view.bounds.origin.y - self.baseView.frame.size.height self.view.alpha = 0 UIView.animateWithDuration(0.2, delay: 0.0, options: [], animations: { self.baseView.center.y = window.center.y + 15 self.view.alpha = 1 }, completion: { finished in UIView.animateWithDuration(0.2, animations: { self.baseView.center = window.center }) }) } public func hide() { let window = UIApplication.sharedApplication().keyWindow! UIView.animateWithDuration(0.2, animations: { self.baseView.frame.origin.y = window.center.y + 400 self.view.alpha = 0 }, completion: { finished in self.view.removeFromSuperview() }) notificationTimer?.invalidate() notificationTimer = nil } // MARK: - Delegates // MARK: Gesture delegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // this prevents our tap gesture from firing for subviews of baseview if touch.view == baseView { return true } return false } // MARK: Location delegate public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { detectAndCallback() } // MARK: Bluetooth delegate public func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { waitingForBluetooth = false detectAndCallback() } // MARK: - UI Helpers func cancel() { self.hide() if let cancelClosure = cancelClosure { getResultsForConfig({ (results) -> Void in cancelClosure(results) }) } } func finish() { self.hide() if let authChangeClosure = authChangeClosure { getResultsForConfig({ (results) -> Void in authChangeClosure(true, results) }) } } func showDeniedAlert(permission: PermissionType) { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let disabledOrDeniedClosure = self.disabledOrDeniedClosure { self.getResultsForConfig({ (results) -> Void in disabledOrDeniedClosure(results) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in let alert = UIAlertController(title: "Permission for \(permission) was denied.", message: "Please enable access to \(permission) in the Settings app", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Show me", style: .Default, handler: { (action) -> Void in NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appForegroundedAfterSettings"), name: UIApplicationDidBecomeActiveNotification, object: nil) let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(settingsUrl!) })) self.viewControllerForAlerts?.presentViewController(alert, animated: true, completion: nil) } } func showDisabledAlert(permission: PermissionType) { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let disabledOrDeniedClosure = self.disabledOrDeniedClosure { self.getResultsForConfig({ (results) -> Void in disabledOrDeniedClosure(results) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in let alert = UIAlertController(title: "\(permission) is currently disabled.", message: "Please enable access to \(permission) in Settings", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.viewControllerForAlerts?.presentViewController(alert, animated: true, completion: nil) } } // MARK: Helpers func appForegroundedAfterSettings (){ NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) detectAndCallback() } func statusForPermission(type: PermissionType, completion: statusRequestClosure) { // :( switch type { case .LocationAlways: completion(status: statusLocationAlways()) case .LocationInUse: completion(status: statusLocationInUse()) case .Contacts: completion(status: statusContacts()) case .Notifications: completion(status: statusNotifications()) case .Microphone: completion(status: statusMicrophone()) case .Camera: completion(status: statusCamera()) case .Photos: completion(status: statusPhotos()) case .Reminders: completion(status: statusReminders()) case .Events: completion(status: statusEvents()) case .Bluetooth: completion(status: statusBluetooth()) case .Motion: completion(status: statusMotion()) case .HealthKit: completion(status: statusHealthKit(nil, typesToRead: nil)) case .CloudKit: statusCloudKit(completion) } } func detectAndCallback() { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let authChangeClosure = self.authChangeClosure { self.getResultsForConfig({ (results) -> Void in self.allAuthorized({ (areAuthorized) -> Void in authChangeClosure(areAuthorized, results) }) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in self.view.setNeedsLayout() // and hide if we've sucessfully got all permissions self.allAuthorized({ (areAuthorized) -> Void in if areAuthorized { self.hide() } }) } } typealias resultsForConfigClosure = ([PermissionResult]) -> Void func getResultsForConfig(completionBlock: resultsForConfigClosure) { var results: [PermissionResult] = [] let group: dispatch_group_t = dispatch_group_create() for config in configuredPermissions { dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in self.statusForPermission(config.type, completion: { (status) -> Void in let result = PermissionResult(type: config.type, status: status) results.append(result) }) } } // FIXME: Return after async calls were executed dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in completionBlock(results) } } } Fixed not being able to request Notifications: Notification categories isn't a requirement ;) // // PermissionScope.swift // PermissionScope // // Created by Nick O'Neill on 4/5/15. // Copyright (c) 2015 That Thing in Swift. All rights reserved. // import UIKit import CoreLocation import AddressBook import AVFoundation import Photos import EventKit import CoreBluetooth import CoreMotion import HealthKit import CloudKit public typealias statusRequestClosure = (status: PermissionStatus) -> Void @objc public class PermissionScope: UIViewController, CLLocationManagerDelegate, UIGestureRecognizerDelegate, CBPeripheralManagerDelegate { // MARK: UI Parameters public let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) public let bodyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 240, height: 70)) public var tintColor = UIColor(red: 0, green: 0.47, blue: 1, alpha: 1) public var buttonFont = UIFont.boldSystemFontOfSize(14) public var labelFont = UIFont.systemFontOfSize(14) public var closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 32)) public var closeOffset = CGSizeZero public var authorizedButtonColor = UIColor(red: 0, green: 0.47, blue: 1, alpha: 1) public var unauthorizedButtonColor:UIColor? // MARK: View hierarchy for custom alert let baseView = UIView() let contentView = UIView() // MARK: - Various lazy managers lazy var locationManager:CLLocationManager = { let lm = CLLocationManager() lm.delegate = self return lm }() lazy var bluetoothManager:CBPeripheralManager = { return CBPeripheralManager(delegate: self, queue: nil, options:[CBPeripheralManagerOptionShowPowerAlertKey: true]) }() lazy var motionManager:CMMotionActivityManager = { return CMMotionActivityManager() }() /// NSUserDefaults standardDefaults lazy var lazy var defaults:NSUserDefaults = { return .standardUserDefaults() }() /// Default status for CoreMotion var motionPermissionStatus: PermissionStatus = .Unknown // MARK: - Internal state and resolution /// Permissions configured using addPermission(:) var configuredPermissions: [PermissionConfig] = [] var permissionButtons: [UIButton] = [] var permissionLabels: [UILabel] = [] // Useful for direct use of the request* methods public var authChangeClosure: authClosureType? = nil public typealias authClosureType = (Bool, [PermissionResult]) -> Void public var cancelClosure: cancelClosureType? = nil public typealias cancelClosureType = ([PermissionResult]) -> Void /** Called when the user has disabled or denied access to notifications, and we're presenting them with a help dialog. */ public var disabledOrDeniedClosure: cancelClosureType? = nil /** View controller to be used when presenting alerts. Defaults to self. You'll want to set this if you are calling the `request*` methods directly. */ public var viewControllerForAlerts : UIViewController? // Computed variables func allAuthorized(completion: (Bool) -> Void ) { getResultsForConfig{ (results) -> Void in let result = results .first { $0.status != .Authorized } .isNil completion(result) } } func requiredAuthorized(completion: (Bool) -> Void ) { getResultsForConfig{ (results) -> Void in let result = results .first { $0.status != .Authorized } .isNil completion(result) } } // use the code we have to see permission status public func permissionStatuses(permissionTypes: [PermissionType]?) -> Dictionary<PermissionType, PermissionStatus> { var statuses: Dictionary<PermissionType, PermissionStatus> = [:] let types: [PermissionType] = permissionTypes ?? PermissionType.allValues for type in types { statusForPermission(type, completion: { (status) -> Void in statuses[type] = status }) } return statuses } public init(backgroundTapCancels: Bool) { super.init(nibName: nil, bundle: nil) viewControllerForAlerts = self // Set up main view view.frame = UIScreen.mainScreen().bounds view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0.7) view.addSubview(baseView) // Base View baseView.frame = view.frame baseView.addSubview(contentView) if backgroundTapCancels { let tap = UITapGestureRecognizer(target: self, action: Selector("cancel")) tap.delegate = self baseView.addGestureRecognizer(tap) } // Content View contentView.backgroundColor = UIColor.whiteColor() contentView.layer.cornerRadius = 10 contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 // header label headerLabel.font = UIFont.systemFontOfSize(22) headerLabel.textColor = UIColor.blackColor() headerLabel.textAlignment = NSTextAlignment.Center headerLabel.text = "Hey, listen!" // headerLabel.backgroundColor = UIColor.redColor() contentView.addSubview(headerLabel) // body label bodyLabel.font = UIFont.boldSystemFontOfSize(16) bodyLabel.textColor = UIColor.blackColor() bodyLabel.textAlignment = NSTextAlignment.Center bodyLabel.text = "We need a couple things\r\nbefore you get started." bodyLabel.numberOfLines = 2 // bodyLabel.text = "We need\r\na couple things before you\r\nget started." // bodyLabel.backgroundColor = UIColor.redColor() contentView.addSubview(bodyLabel) // close button closeButton.setTitle("Close", forState: .Normal) closeButton.addTarget(self, action: Selector("cancel"), forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(closeButton) self.statusMotion() //Added to check motion status on load } public convenience init() { self.init(backgroundTapCancels: true) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let screenSize = UIScreen.mainScreen().bounds.size // Set background frame view.frame.size = screenSize // Set frames let x = (screenSize.width - Constants.UI.contentWidth) / 2 let dialogHeight: CGFloat switch self.configuredPermissions.count { case 2: dialogHeight = Constants.UI.dialogHeightTwoPermissions case 3: dialogHeight = Constants.UI.dialogHeightThreePermissions default: dialogHeight = Constants.UI.dialogHeightSinglePermission } let y = (screenSize.height - dialogHeight) / 2 contentView.frame = CGRect(x:x, y:y, width:Constants.UI.contentWidth, height:dialogHeight) // offset the header from the content center, compensate for the content's offset headerLabel.center = contentView.center headerLabel.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) headerLabel.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-50)) // ... same with the body bodyLabel.center = contentView.center bodyLabel.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) bodyLabel.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-100)) closeButton.center = contentView.center closeButton.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) closeButton.frame.offsetInPlace(dx: 105, dy: -((dialogHeight/2)-20)) closeButton.frame.offsetInPlace(dx: self.closeOffset.width, dy: self.closeOffset.height) if closeButton.imageView?.image != nil { closeButton.setTitle("", forState: .Normal) } closeButton.setTitleColor(tintColor, forState: .Normal) let baseOffset = 95 var index = 0 for button in permissionButtons { button.center = contentView.center button.frame.offsetInPlace(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y) button.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-160) + CGFloat(index * baseOffset)) let type = configuredPermissions[index].type statusForPermission(type, completion: { (currentStatus) -> Void in let prettyDescription = type.prettyDescription if currentStatus == .Authorized { self.setButtonAuthorizedStyle(button) button.setTitle("Allowed \(prettyDescription)".localized.uppercaseString, forState: .Normal) } else if currentStatus == .Unauthorized { self.setButtonUnauthorizedStyle(button) button.setTitle("Denied \(prettyDescription)".localized.uppercaseString, forState: .Normal) } else if currentStatus == .Disabled { // setButtonDisabledStyle(button) button.setTitle("\(prettyDescription) Disabled".localized.uppercaseString, forState: .Normal) } let label = self.permissionLabels[index] label.center = self.contentView.center label.frame.offsetInPlace(dx: -self.contentView.frame.origin.x, dy: -self.contentView.frame.origin.y) label.frame.offsetInPlace(dx: 0, dy: -((dialogHeight/2)-205) + CGFloat(index * baseOffset)) index++ }) } } // MARK: - Customizing the permissions @objc public func addPermission(config: PermissionConfig) { assert(!config.message.isEmpty, "Including a message about your permission usage is helpful") assert(configuredPermissions.count < 3, "Ask for three or fewer permissions at a time") assert(configuredPermissions.filter { $0.type == config.type }.isEmpty, "Permission for \(config.type) already set") configuredPermissions.append(config) if config.type == .Bluetooth && askedBluetooth { triggerBluetoothStatusUpdate() } else if config.type == .Motion && askedMotion { triggerMotionStatusUpdate() } } func permissionStyledButton(type: PermissionType) -> UIButton { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 220, height: 40)) button.setTitleColor(tintColor, forState: .Normal) button.titleLabel?.font = buttonFont button.layer.borderWidth = 1 button.layer.borderColor = tintColor.CGColor button.layer.cornerRadius = 6 // this is a bit of a mess, eh? switch type { case .LocationAlways, .LocationInUse: button.setTitle("Enable \(type.prettyDescription)".localized.uppercaseString, forState: .Normal) default: button.setTitle("Allow \(type)".localized.uppercaseString, forState: .Normal) } button.addTarget(self, action: Selector("request\(type)"), forControlEvents: .TouchUpInside) return button } func setButtonAuthorizedStyle(button: UIButton) { button.layer.borderWidth = 0 button.backgroundColor = authorizedButtonColor button.setTitleColor(.whiteColor(), forState: .Normal) } func setButtonUnauthorizedStyle(button: UIButton) { button.layer.borderWidth = 0 button.backgroundColor = unauthorizedButtonColor ?? authorizedButtonColor.inverseColor button.setTitleColor(.whiteColor(), forState: .Normal) } func permissionStyledLabel(message: String) -> UILabel { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 260, height: 50)) label.font = labelFont label.numberOfLines = 2 label.textAlignment = .Center label.text = message // label.backgroundColor = UIColor.greenColor() return label } // MARK: - Status and Requests for each permission // MARK: Location public func statusLocationAlways() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .Disabled } let status = CLLocationManager.authorizationStatus() switch status { case .AuthorizedAlways: return .Authorized case .Restricted, .Denied: return .Unauthorized case .AuthorizedWhenInUse: // Curious why this happens? Details on upgrading from WhenInUse to Always: // https://github.com/nickoneill/PermissionScope/issues/24 if defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedInUseToAlwaysUpgrade) { return .Unauthorized } else { return .Unknown } case .NotDetermined: return .Unknown } } public func requestLocationAlways() { switch statusLocationAlways() { case .Unknown: if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedInUseToAlwaysUpgrade) defaults.synchronize() } locationManager.requestAlwaysAuthorization() case .Unauthorized: self.showDeniedAlert(.LocationAlways) case .Disabled: self.showDisabledAlert(.LocationInUse) default: break } } public func statusLocationInUse() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .Disabled } let status = CLLocationManager.authorizationStatus() // if you're already "always" authorized, then you don't need in use // but the user can still demote you! So I still use them separately. switch status { case .AuthorizedWhenInUse, .AuthorizedAlways: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestLocationInUse() { switch statusLocationInUse() { case .Unknown: locationManager.requestWhenInUseAuthorization() case .Unauthorized: self.showDeniedAlert(.LocationInUse) case .Disabled: self.showDisabledAlert(.LocationInUse) default: break } } // MARK: Contacts public func statusContacts() -> PermissionStatus { let status = ABAddressBookGetAuthorizationStatus() switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestContacts() { switch statusContacts() { case .Unknown: ABAddressBookRequestAccessWithCompletion(nil) { (success, error) -> Void in self.detectAndCallback() } case .Unauthorized: self.showDeniedAlert(.Contacts) default: break } } // MARK: Notifications public func statusNotifications() -> PermissionStatus { let settings = UIApplication.sharedApplication().currentUserNotificationSettings() if let settingTypes = settings?.types where settingTypes != UIUserNotificationType.None { return .Authorized } else { if defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedNotifications) { return .Unauthorized } else { return .Unknown } } } func showingNotificationPermission () { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("finishedShowingNotificationPermission"), name: UIApplicationDidBecomeActiveNotification, object: nil) notificationTimer?.invalidate() } var notificationTimer : NSTimer? func finishedShowingNotificationPermission () { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) notificationTimer?.invalidate() defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedNotifications) defaults.synchronize() getResultsForConfig { (results) -> Void in let _notificationResult = results .filter { $0.type == PermissionType.Notifications } .first guard let notificationResult = _notificationResult else { return } if notificationResult.status == .Unknown { self.showDeniedAlert(notificationResult.type) } else { self.detectAndCallback() } } } public func requestNotifications() { switch statusNotifications() { case .Unknown: let notificationsPermission = self.configuredPermissions .first { $0 is NotificationsPermissionConfig } as? NotificationsPermissionConfig let notificationsPermissionSet = notificationsPermission?.notificationCategories NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("showingNotificationPermission"), name: UIApplicationWillResignActiveNotification, object: nil) notificationTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("finishedShowingNotificationPermission"), userInfo: nil, repeats: false) UIApplication.sharedApplication().registerUserNotificationSettings( UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: notificationsPermissionSet) ) case .Unauthorized: showDeniedAlert(.Notifications) case .Disabled: showDisabledAlert(.Notifications) case .Authorized: break } } // MARK: Microphone public func statusMicrophone() -> PermissionStatus { switch AVAudioSession.sharedInstance().recordPermission() { case AVAudioSessionRecordPermission.Denied: return .Unauthorized case AVAudioSessionRecordPermission.Granted: return .Authorized default: return .Unknown } } public func requestMicrophone() { switch statusMicrophone() { case .Unknown: AVAudioSession.sharedInstance().requestRecordPermission({ (granted) -> Void in self.detectAndCallback() }) case .Unauthorized: showDeniedAlert(.Microphone) case .Disabled: showDisabledAlert(.Microphone) case .Authorized: break } } // MARK: Camera public func statusCamera() -> PermissionStatus { let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestCamera() { switch statusCamera() { case .Unknown: AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) -> Void in self.detectAndCallback() }) case .Unauthorized: showDeniedAlert(.Camera) case .Disabled: showDisabledAlert(.Camera) case .Authorized: break } } // MARK: Photos public func statusPhotos() -> PermissionStatus { let status = PHPhotoLibrary.authorizationStatus() switch status { case .Authorized: return .Authorized case .Denied, .Restricted: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestPhotos() { switch statusPhotos() { case .Unknown: PHPhotoLibrary.requestAuthorization({ (status) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Photos) case .Disabled: showDisabledAlert(.Photos) case .Authorized: break } } // MARK: Reminders public func statusReminders() -> PermissionStatus { let status = EKEventStore.authorizationStatusForEntityType(.Reminder) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestReminders() { switch statusReminders() { case .Unknown: EKEventStore().requestAccessToEntityType(.Reminder, completion: { (granted, error) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Reminders) default: break } } // MARK: Events public func statusEvents() -> PermissionStatus { let status = EKEventStore.authorizationStatusForEntityType(.Event) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Unauthorized case .NotDetermined: return .Unknown } } public func requestEvents() { switch statusEvents() { case .Unknown: EKEventStore().requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.Events) default: break } } // MARK: Bluetooth private var askedBluetooth:Bool { get { return defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedBluetooth) } set { defaults.setBool(newValue, forKey: Constants.NSUserDefaultsKeys.requestedBluetooth) defaults.synchronize() } } private var waitingForBluetooth = false public func statusBluetooth() -> PermissionStatus { // if already asked for bluetooth before, do a request to get status, else wait for user to request if askedBluetooth{ triggerBluetoothStatusUpdate() } else { return .Unknown } switch (bluetoothManager.state, CBPeripheralManager.authorizationStatus()) { case (.Unsupported, _), (.PoweredOff, _), (_, .Restricted): return .Disabled case (.Unauthorized, _), (_, .Denied): return .Unauthorized case (.PoweredOn, .Authorized): return .Authorized default: return .Unknown } } public func requestBluetooth() { switch statusBluetooth() { case .Disabled: showDisabledAlert(.Bluetooth) case .Unauthorized: showDeniedAlert(.Bluetooth) case .Unknown: triggerBluetoothStatusUpdate() default: break } } private func triggerBluetoothStatusUpdate() { if !waitingForBluetooth && bluetoothManager.state == .Unknown { bluetoothManager.startAdvertising(nil) bluetoothManager.stopAdvertising() askedBluetooth = true waitingForBluetooth = true } } // MARK: CoreMotion public func statusMotion() -> PermissionStatus { if askedMotion{ triggerMotionStatusUpdate() } return motionPermissionStatus } public func requestMotion() { switch statusMotion() { case .Unauthorized: showDeniedAlert(.Motion) case .Unknown: triggerMotionStatusUpdate() default: break } } private func triggerMotionStatusUpdate() { let tmpMotionPermissionStatus = motionPermissionStatus defaults.setBool(true, forKey: Constants.NSUserDefaultsKeys.requestedMotion) defaults.synchronize() motionManager.queryActivityStartingFromDate(NSDate(), toDate: NSDate(), toQueue: NSOperationQueue.mainQueue(), withHandler: { (_: [CMMotionActivity]?, error:NSError?) -> Void in if (error != nil && error!.code == Int(CMErrorMotionActivityNotAuthorized.rawValue)) { self.motionPermissionStatus = .Unauthorized } else{ self.motionPermissionStatus = .Authorized } self.motionManager.stopActivityUpdates() if (tmpMotionPermissionStatus != self.motionPermissionStatus){ self.waitingForMotion = false self.detectAndCallback() } }) askedMotion = true waitingForMotion = true } private var askedMotion:Bool { get { return defaults.boolForKey(Constants.NSUserDefaultsKeys.requestedMotion) } set { defaults.setBool(newValue, forKey: Constants.NSUserDefaultsKeys.requestedMotion) defaults.synchronize() } } private var waitingForMotion = false // MARK: HealthKit public func statusHealthKit(typesToShare: Set<HKSampleType>?, typesToRead: Set<HKObjectType>?) -> PermissionStatus { guard HKHealthStore.isHealthDataAvailable() else { return .Disabled } var statusArray:[HKAuthorizationStatus] = [] typesToShare?.forEach({ (elem) -> () in statusArray.append(HKHealthStore().authorizationStatusForType(elem)) }) typesToRead?.forEach({ (elem) -> () in statusArray.append(HKHealthStore().authorizationStatusForType(elem)) }) // TODO: What to do? If there's 1 .Denied or ND then return such result ? // Only Auth if they are all Auth ? let typesAuthorized = statusArray .filter { $0 == .SharingAuthorized } let typesDenied = statusArray .filter { $0 == .SharingDenied } let typesNotDetermined = statusArray .filter { $0 == .NotDetermined } if typesNotDetermined.count == statusArray.count || statusArray.isEmpty { return .Unknown } else if !typesDenied.isEmpty { return .Unauthorized } else { return .Authorized } } func requestHealthKit() { guard let healthPermission = self.configuredPermissions .first({ $0.type == .HealthKit }) as? HealthPermissionConfig else { return } switch statusHealthKit(healthPermission.healthTypesToShare, typesToRead: healthPermission.healthTypesToRead) { case .Unknown: HKHealthStore().requestAuthorizationToShareTypes(healthPermission.healthTypesToShare, readTypes: healthPermission.healthTypesToRead, completion: { (granted, error) -> Void in if let error = error { print("error: ", error) } self.detectAndCallback() }) case .Unauthorized: self.showDeniedAlert(.HealthKit) case .Disabled: self.showDisabledAlert(.HealthKit) case .Authorized: break } } // MARK: CloudKit public func statusCloudKit(statusCallback: statusRequestClosure) { CKContainer.defaultContainer().statusForApplicationPermission(.UserDiscoverability) { (status, error) -> Void in switch status { case .InitialState: statusCallback(status: .Unknown) case .Granted: statusCallback(status: .Authorized) case .Denied: statusCallback(status: .Unauthorized) case .CouldNotComplete: // Error ocurred. print(error!.localizedDescription) // TODO: What should we return ? Use throws ? statusCallback(status: .Unknown) } } } public func requestCloudKit() { CKContainer.defaultContainer().accountStatusWithCompletionHandler { (status, error) -> Void in // log error? switch status { case .Available: CKContainer.defaultContainer().requestApplicationPermission(.UserDiscoverability, completionHandler: { (status2, error2) -> Void in self.detectAndCallback() }) case .Restricted, .NoAccount: self.showDisabledAlert(.CloudKit) case .CouldNotDetermine: // Ask user to login to iCloud break } } } // MARK: - UI @objc public func show(authChange: ((finished: Bool, results: [PermissionResult]) -> Void)? = nil, cancelled: ((results: [PermissionResult]) -> Void)? = nil) { assert(!configuredPermissions.isEmpty, "Please add at least one permission") authChangeClosure = authChange cancelClosure = cancelled dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { while self.waitingForBluetooth || self.waitingForMotion { } // call other methods that need to wait before show // no missing required perms? callback and do nothing self.requiredAuthorized({ (areAuthorized) -> Void in if areAuthorized { self.getResultsForConfig({ (results) -> Void in self.authChangeClosure?(true, results) }) } else { dispatch_async(dispatch_get_main_queue()) { self.showAlert() } } }) } } private func showAlert() { // add the backing views let window = UIApplication.sharedApplication().keyWindow! window.addSubview(view) view.frame = window.bounds baseView.frame = window.bounds for button in permissionButtons { button.removeFromSuperview() } permissionButtons = [] for label in permissionLabels { label.removeFromSuperview() } permissionLabels = [] // create the buttons for config in configuredPermissions { let button = permissionStyledButton(config.type) permissionButtons.append(button) contentView.addSubview(button) let label = permissionStyledLabel(config.message) permissionLabels.append(label) contentView.addSubview(label) } self.view.setNeedsLayout() // slide in the view self.baseView.frame.origin.y = self.view.bounds.origin.y - self.baseView.frame.size.height self.view.alpha = 0 UIView.animateWithDuration(0.2, delay: 0.0, options: [], animations: { self.baseView.center.y = window.center.y + 15 self.view.alpha = 1 }, completion: { finished in UIView.animateWithDuration(0.2, animations: { self.baseView.center = window.center }) }) } public func hide() { let window = UIApplication.sharedApplication().keyWindow! UIView.animateWithDuration(0.2, animations: { self.baseView.frame.origin.y = window.center.y + 400 self.view.alpha = 0 }, completion: { finished in self.view.removeFromSuperview() }) notificationTimer?.invalidate() notificationTimer = nil } // MARK: - Delegates // MARK: Gesture delegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // this prevents our tap gesture from firing for subviews of baseview if touch.view == baseView { return true } return false } // MARK: Location delegate public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { detectAndCallback() } // MARK: Bluetooth delegate public func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { waitingForBluetooth = false detectAndCallback() } // MARK: - UI Helpers func cancel() { self.hide() if let cancelClosure = cancelClosure { getResultsForConfig({ (results) -> Void in cancelClosure(results) }) } } func finish() { self.hide() if let authChangeClosure = authChangeClosure { getResultsForConfig({ (results) -> Void in authChangeClosure(true, results) }) } } func showDeniedAlert(permission: PermissionType) { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let disabledOrDeniedClosure = self.disabledOrDeniedClosure { self.getResultsForConfig({ (results) -> Void in disabledOrDeniedClosure(results) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in let alert = UIAlertController(title: "Permission for \(permission) was denied.", message: "Please enable access to \(permission) in the Settings app", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Show me", style: .Default, handler: { (action) -> Void in NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appForegroundedAfterSettings"), name: UIApplicationDidBecomeActiveNotification, object: nil) let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(settingsUrl!) })) self.viewControllerForAlerts?.presentViewController(alert, animated: true, completion: nil) } } func showDisabledAlert(permission: PermissionType) { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let disabledOrDeniedClosure = self.disabledOrDeniedClosure { self.getResultsForConfig({ (results) -> Void in disabledOrDeniedClosure(results) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in let alert = UIAlertController(title: "\(permission) is currently disabled.", message: "Please enable access to \(permission) in Settings", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.viewControllerForAlerts?.presentViewController(alert, animated: true, completion: nil) } } // MARK: Helpers func appForegroundedAfterSettings (){ NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) detectAndCallback() } func statusForPermission(type: PermissionType, completion: statusRequestClosure) { // :( switch type { case .LocationAlways: completion(status: statusLocationAlways()) case .LocationInUse: completion(status: statusLocationInUse()) case .Contacts: completion(status: statusContacts()) case .Notifications: completion(status: statusNotifications()) case .Microphone: completion(status: statusMicrophone()) case .Camera: completion(status: statusCamera()) case .Photos: completion(status: statusPhotos()) case .Reminders: completion(status: statusReminders()) case .Events: completion(status: statusEvents()) case .Bluetooth: completion(status: statusBluetooth()) case .Motion: completion(status: statusMotion()) case .HealthKit: completion(status: statusHealthKit(nil, typesToRead: nil)) case .CloudKit: statusCloudKit(completion) } } func detectAndCallback() { let group: dispatch_group_t = dispatch_group_create() dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // compile the results and pass them back if necessary if let authChangeClosure = self.authChangeClosure { self.getResultsForConfig({ (results) -> Void in self.allAuthorized({ (areAuthorized) -> Void in authChangeClosure(areAuthorized, results) }) }) } } dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in self.view.setNeedsLayout() // and hide if we've sucessfully got all permissions self.allAuthorized({ (areAuthorized) -> Void in if areAuthorized { self.hide() } }) } } typealias resultsForConfigClosure = ([PermissionResult]) -> Void func getResultsForConfig(completionBlock: resultsForConfigClosure) { var results: [PermissionResult] = [] let group: dispatch_group_t = dispatch_group_create() for config in configuredPermissions { dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in self.statusForPermission(config.type, completion: { (status) -> Void in let result = PermissionResult(type: config.type, status: status) results.append(result) }) } } // FIXME: Return after async calls were executed dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in completionBlock(results) } } }
// // RegularPlayer.swift // Pods // // Created by King, Gavin on 3/7/17. // // import UIKit import Foundation import AVFoundation import AVKit extension AVMediaSelectionOption: TextTrackMetadata { public var describesMusicAndSound: Bool { return self.hasMediaCharacteristic(.describesMusicAndSoundForAccessibility) } } /// A RegularPlayer is used to play regular videos. @objc open class RegularPlayer: NSObject, Player, ProvidesView { public struct Constants { public static let TimeUpdateInterval: TimeInterval = 0.1 } // MARK: Private Properties fileprivate var player = AVPlayer() // MARK: Public API /// Sets an AVAsset on the player. /// /// - Parameter asset: The AVAsset @objc open func set(_ asset: AVAsset) { // Prepare the old item for removal if let currentItem = self.player.currentItem { self.removePlayerItemObservers(fromPlayerItem: currentItem) } // Replace it with the new item let playerItem = AVPlayerItem(asset: asset) self.addPlayerItemObservers(toPlayerItem: playerItem) self.player.replaceCurrentItem(with: playerItem) } // MARK: ProvidesView private class RegularPlayerView: UIView { var playerLayer: AVPlayerLayer { return self.layer as! AVPlayerLayer } override class var layerClass: AnyClass { return AVPlayerLayer.self } func configureForPlayer(player: AVPlayer) { (self.layer as! AVPlayerLayer).player = player } } public let view: UIView = RegularPlayerView(frame: .zero) private var regularPlayerView: RegularPlayerView { return self.view as! RegularPlayerView } private var playerLayer: AVPlayerLayer { return self.regularPlayerView.playerLayer } // MARK: Player weak public var delegate: PlayerDelegate? public private(set) var state: PlayerState = .ready { didSet { self.delegate?.playerDidUpdateState(player: self, previousState: oldValue) } } public var duration: TimeInterval { return self.player.currentItem?.duration.timeInterval ?? 0 } public private(set) var time: TimeInterval = 0 { didSet { self.delegate?.playerDidUpdateTime(player: self) } } public private(set) var bufferedTime: TimeInterval = 0 { didSet { self.delegate?.playerDidUpdateBufferedTime(player: self) } } public var playing: Bool { return self.player.rate > 0 } public var error: NSError? { return self.player.errorForPlayerOrItem } public func seek(to time: TimeInterval) { let cmTime = CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)) self.player.seek(to: cmTime) self.time = time } public func play() { self.player.play() } public func pause() { self.player.pause() } // MARK: Lifecycle public override init() { super.init() self.addPlayerObservers() self.regularPlayerView.configureForPlayer(player: self.player) self.setupAirplay() } deinit { if let playerItem = self.player.currentItem { self.removePlayerItemObservers(fromPlayerItem: playerItem) } self.removePlayerObservers() } // MARK: Setup private func setupAirplay() { self.player.usesExternalPlaybackWhileExternalScreenIsActive = true } // MARK: Observers private struct KeyPath { struct Player { static let Rate = "rate" } struct PlayerItem { static let Status = "status" static let PlaybackLikelyToKeepUp = "playbackLikelyToKeepUp" static let LoadedTimeRanges = "loadedTimeRanges" } } private var playerTimeObserver: Any? private func addPlayerItemObservers(toPlayerItem playerItem: AVPlayerItem) { playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.Status, options: [.initial, .new], context: nil) playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.PlaybackLikelyToKeepUp, options: [.initial, .new], context: nil) playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.LoadedTimeRanges, options: [.initial, .new], context: nil) } private func removePlayerItemObservers(fromPlayerItem playerItem: AVPlayerItem) { playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.Status, context: nil) playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.PlaybackLikelyToKeepUp, context: nil) playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.LoadedTimeRanges, context: nil) } private func addPlayerObservers() { self.player.addObserver(self, forKeyPath: KeyPath.Player.Rate, options: [.initial, .new], context: nil) let interval = CMTimeMakeWithSeconds(Constants.TimeUpdateInterval, Int32(NSEC_PER_SEC)) self.playerTimeObserver = self.player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { [weak self] (cmTime) in if let strongSelf = self, let time = cmTime.timeInterval { strongSelf.time = time } }) } private func removePlayerObservers() { self.player.removeObserver(self, forKeyPath: KeyPath.Player.Rate, context: nil) if let playerTimeObserver = self.playerTimeObserver { self.player.removeTimeObserver(playerTimeObserver) self.playerTimeObserver = nil } } // MARK: Observation override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // Player Item Observers if keyPath == KeyPath.PlayerItem.Status { if let statusInt = change?[.newKey] as? Int, let status = AVPlayerItemStatus(rawValue: statusInt) { self.playerItemStatusDidChange(status: status) } } else if keyPath == KeyPath.PlayerItem.PlaybackLikelyToKeepUp { if let playbackLikelyToKeepUp = change?[.newKey] as? Bool { self.playerItemPlaybackLikelyToKeepUpDidChange(playbackLikelyToKeepUp: playbackLikelyToKeepUp) } } else if keyPath == KeyPath.PlayerItem.LoadedTimeRanges { if let loadedTimeRanges = change?[.newKey] as? [NSValue] { self.playerItemLoadedTimeRangesDidChange(loadedTimeRanges: loadedTimeRanges) } } // Player Observers else if keyPath == KeyPath.Player.Rate { if let rate = change?[.newKey] as? Float { self.playerRateDidChange(rate: rate) } } // Fall Through Observers else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // MARK: Observation Helpers private func playerItemStatusDidChange(status: AVPlayerItemStatus) { switch status { case .unknown: self.state = .loading case .readyToPlay: self.state = .ready case .failed: self.state = .failed } } private func playerRateDidChange(rate: Float) { self.delegate?.playerDidUpdatePlaying(player: self) } private func playerItemPlaybackLikelyToKeepUpDidChange(playbackLikelyToKeepUp: Bool) { let state: PlayerState = playbackLikelyToKeepUp ? .ready : .loading self.state = state } private func playerItemLoadedTimeRangesDidChange(loadedTimeRanges: [NSValue]) { guard let bufferedCMTime = loadedTimeRanges.first?.timeRangeValue.end, let bufferedTime = bufferedCMTime.timeInterval else { return } self.bufferedTime = bufferedTime } // MARK: Capability Protocol Helpers #if os(iOS) @available(iOS 9.0, *) fileprivate lazy var _pictureInPictureController: AVPictureInPictureController? = { AVPictureInPictureController(playerLayer: self.regularPlayerView.playerLayer) }() #endif } // MARK: Capability Protocols extension RegularPlayer: AirPlayCapable { public var isAirPlayEnabled: Bool { get { return self.player.allowsExternalPlayback } set { return self.player.allowsExternalPlayback = newValue } } } #if os(iOS) extension RegularPlayer: PictureInPictureCapable { @available(iOS 9.0, *) public var pictureInPictureController: AVPictureInPictureController? { return self._pictureInPictureController } } #endif extension RegularPlayer: VolumeCapable { public var volume: Float { get { return self.player.volume } set { self.player.volume = newValue } } } extension RegularPlayer: FillModeCapable { public var fillMode: FillMode { get { let gravity = (self.view.layer as! AVPlayerLayer).videoGravity return gravity == .resizeAspect ? .fit : .fill } set { let gravity: AVLayerVideoGravity switch newValue { case .fit: gravity = .resizeAspect case .fill: gravity = .resizeAspectFill } (self.view.layer as! AVPlayerLayer).videoGravity = gravity } } } extension RegularPlayer: TextTrackCapable { public var selectedTrack: TextTrackMetadata? { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return nil } return self.player.currentItem?.selectedMediaOption(in: group) } public func availableTextTracks() -> [TextTrackMetadata] { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return [] } return group.options } public func fetchAvailableTextTracks(completion: @escaping ([TextTrackMetadata]) -> Void) { self.player.currentItem?.asset.loadValuesAsynchronously(forKeys: [#keyPath(AVAsset.availableMediaCharacteristicsWithMediaSelectionOptions)]) { [weak self] in guard let strongSelf = self, let group = strongSelf.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { completion([]) return } completion(group.options) } } public func select(_ textTrack: TextTrackMetadata?) { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return } guard let track = textTrack else { self.player.currentItem?.select(nil, in: group) return } if let option = track as? AVMediaSelectionOption { self.player.currentItem?.select(option, in: group) } else { let optionPredicate: (AVMediaSelectionOption) -> Bool = { option in return option.locale == track.locale && (option.hasMediaCharacteristic(.describesMusicAndSoundForAccessibility) == track.describesMusicAndSound) } if let option = group.options.first(where: optionPredicate) { self.player.currentItem?.select(option, in: group) } } } } Remove deprecated API in newer versions // // RegularPlayer.swift // Pods // // Created by King, Gavin on 3/7/17. // // import UIKit import Foundation import AVFoundation import AVKit extension AVMediaSelectionOption: TextTrackMetadata { public var describesMusicAndSound: Bool { return self.hasMediaCharacteristic(.describesMusicAndSoundForAccessibility) } } /// A RegularPlayer is used to play regular videos. @objc open class RegularPlayer: NSObject, Player, ProvidesView { public struct Constants { public static let TimeUpdateInterval: TimeInterval = 0.1 } // MARK: Private Properties fileprivate var player = AVPlayer() // MARK: Public API /// Sets an AVAsset on the player. /// /// - Parameter asset: The AVAsset @objc open func set(_ asset: AVAsset) { // Prepare the old item for removal if let currentItem = self.player.currentItem { self.removePlayerItemObservers(fromPlayerItem: currentItem) } // Replace it with the new item let playerItem = AVPlayerItem(asset: asset) self.addPlayerItemObservers(toPlayerItem: playerItem) self.player.replaceCurrentItem(with: playerItem) } // MARK: ProvidesView private class RegularPlayerView: UIView { var playerLayer: AVPlayerLayer { return self.layer as! AVPlayerLayer } override class var layerClass: AnyClass { return AVPlayerLayer.self } func configureForPlayer(player: AVPlayer) { (self.layer as! AVPlayerLayer).player = player } } public let view: UIView = RegularPlayerView(frame: .zero) private var regularPlayerView: RegularPlayerView { return self.view as! RegularPlayerView } private var playerLayer: AVPlayerLayer { return self.regularPlayerView.playerLayer } // MARK: Player weak public var delegate: PlayerDelegate? public private(set) var state: PlayerState = .ready { didSet { self.delegate?.playerDidUpdateState(player: self, previousState: oldValue) } } public var duration: TimeInterval { return self.player.currentItem?.duration.timeInterval ?? 0 } public private(set) var time: TimeInterval = 0 { didSet { self.delegate?.playerDidUpdateTime(player: self) } } public private(set) var bufferedTime: TimeInterval = 0 { didSet { self.delegate?.playerDidUpdateBufferedTime(player: self) } } public var playing: Bool { return self.player.rate > 0 } public var error: NSError? { return self.player.errorForPlayerOrItem } public func seek(to time: TimeInterval) { let cmTime = CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)) self.player.seek(to: cmTime) self.time = time } public func play() { self.player.play() } public func pause() { self.player.pause() } // MARK: Lifecycle public override init() { super.init() self.addPlayerObservers() self.regularPlayerView.configureForPlayer(player: self.player) self.setupAirplay() } deinit { if let playerItem = self.player.currentItem { self.removePlayerItemObservers(fromPlayerItem: playerItem) } self.removePlayerObservers() } // MARK: Setup private func setupAirplay() { self.player.usesExternalPlaybackWhileExternalScreenIsActive = true } // MARK: Observers private struct KeyPath { struct Player { static let Rate = "rate" } struct PlayerItem { static let Status = "status" static let PlaybackLikelyToKeepUp = "playbackLikelyToKeepUp" static let LoadedTimeRanges = "loadedTimeRanges" } } private var playerTimeObserver: Any? private func addPlayerItemObservers(toPlayerItem playerItem: AVPlayerItem) { playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.Status, options: [.initial, .new], context: nil) playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.PlaybackLikelyToKeepUp, options: [.initial, .new], context: nil) playerItem.addObserver(self, forKeyPath: KeyPath.PlayerItem.LoadedTimeRanges, options: [.initial, .new], context: nil) } private func removePlayerItemObservers(fromPlayerItem playerItem: AVPlayerItem) { playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.Status, context: nil) playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.PlaybackLikelyToKeepUp, context: nil) playerItem.removeObserver(self, forKeyPath: KeyPath.PlayerItem.LoadedTimeRanges, context: nil) } private func addPlayerObservers() { self.player.addObserver(self, forKeyPath: KeyPath.Player.Rate, options: [.initial, .new], context: nil) let interval = CMTimeMakeWithSeconds(Constants.TimeUpdateInterval, Int32(NSEC_PER_SEC)) self.playerTimeObserver = self.player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { [weak self] (cmTime) in if let strongSelf = self, let time = cmTime.timeInterval { strongSelf.time = time } }) } private func removePlayerObservers() { self.player.removeObserver(self, forKeyPath: KeyPath.Player.Rate, context: nil) if let playerTimeObserver = self.playerTimeObserver { self.player.removeTimeObserver(playerTimeObserver) self.playerTimeObserver = nil } } // MARK: Observation override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // Player Item Observers if keyPath == KeyPath.PlayerItem.Status { if let statusInt = change?[.newKey] as? Int, let status = AVPlayerItemStatus(rawValue: statusInt) { self.playerItemStatusDidChange(status: status) } } else if keyPath == KeyPath.PlayerItem.PlaybackLikelyToKeepUp { if let playbackLikelyToKeepUp = change?[.newKey] as? Bool { self.playerItemPlaybackLikelyToKeepUpDidChange(playbackLikelyToKeepUp: playbackLikelyToKeepUp) } } else if keyPath == KeyPath.PlayerItem.LoadedTimeRanges { if let loadedTimeRanges = change?[.newKey] as? [NSValue] { self.playerItemLoadedTimeRangesDidChange(loadedTimeRanges: loadedTimeRanges) } } // Player Observers else if keyPath == KeyPath.Player.Rate { if let rate = change?[.newKey] as? Float { self.playerRateDidChange(rate: rate) } } // Fall Through Observers else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // MARK: Observation Helpers private func playerItemStatusDidChange(status: AVPlayerItemStatus) { switch status { case .unknown: self.state = .loading case .readyToPlay: self.state = .ready case .failed: self.state = .failed } } private func playerRateDidChange(rate: Float) { self.delegate?.playerDidUpdatePlaying(player: self) } private func playerItemPlaybackLikelyToKeepUpDidChange(playbackLikelyToKeepUp: Bool) { let state: PlayerState = playbackLikelyToKeepUp ? .ready : .loading self.state = state } private func playerItemLoadedTimeRangesDidChange(loadedTimeRanges: [NSValue]) { guard let bufferedCMTime = loadedTimeRanges.first?.timeRangeValue.end, let bufferedTime = bufferedCMTime.timeInterval else { return } self.bufferedTime = bufferedTime } // MARK: Capability Protocol Helpers #if os(iOS) @available(iOS 9.0, *) fileprivate lazy var _pictureInPictureController: AVPictureInPictureController? = { AVPictureInPictureController(playerLayer: self.regularPlayerView.playerLayer) }() #endif } // MARK: Capability Protocols extension RegularPlayer: AirPlayCapable { public var isAirPlayEnabled: Bool { get { return self.player.allowsExternalPlayback } set { return self.player.allowsExternalPlayback = newValue } } } #if os(iOS) extension RegularPlayer: PictureInPictureCapable { @available(iOS 9.0, *) public var pictureInPictureController: AVPictureInPictureController? { return self._pictureInPictureController } } #endif extension RegularPlayer: VolumeCapable { public var volume: Float { get { return self.player.volume } set { self.player.volume = newValue } } } extension RegularPlayer: FillModeCapable { public var fillMode: FillMode { get { let gravity = (self.view.layer as! AVPlayerLayer).videoGravity return gravity == .resizeAspect ? .fit : .fill } set { let gravity: AVLayerVideoGravity switch newValue { case .fit: gravity = .resizeAspect case .fill: gravity = .resizeAspectFill } (self.view.layer as! AVPlayerLayer).videoGravity = gravity } } } extension RegularPlayer: TextTrackCapable { public var selectedTrack: TextTrackMetadata? { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return nil } if #available(iOS 9.0, *) { return self.player.currentItem?.currentMediaSelection.selectedMediaOption(in: group) } else { return self.player.currentItem?.selectedMediaOption(in: group) } } public func availableTextTracks() -> [TextTrackMetadata] { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return [] } return group.options } public func fetchAvailableTextTracks(completion: @escaping ([TextTrackMetadata]) -> Void) { self.player.currentItem?.asset.loadValuesAsynchronously(forKeys: [#keyPath(AVAsset.availableMediaCharacteristicsWithMediaSelectionOptions)]) { [weak self] in guard let strongSelf = self, let group = strongSelf.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { completion([]) return } completion(group.options) } } public func select(_ textTrack: TextTrackMetadata?) { guard let group = self.player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) else { return } guard let track = textTrack else { self.player.currentItem?.select(nil, in: group) return } if let option = track as? AVMediaSelectionOption { self.player.currentItem?.select(option, in: group) } else { let optionPredicate: (AVMediaSelectionOption) -> Bool = { option in return option.locale == track.locale && (option.hasMediaCharacteristic(.describesMusicAndSoundForAccessibility) == track.describesMusicAndSound) } if let option = group.options.first(where: optionPredicate) { self.player.currentItem?.select(option, in: group) } } } }
// // JTAppleCalendarView.swift // JTAppleCalendar // // Created by Jay Thomas on 2016-03-01. // Copyright © 2016 OS-Tech. All rights reserved. // let cellReuseIdentifier = "JTDayCell" let NUMBER_OF_DAYS_IN_WEEK = 7 let MAX_NUMBER_OF_DAYS_IN_WEEK = 7 // Should not be changed let MIN_NUMBER_OF_DAYS_IN_WEEK = MAX_NUMBER_OF_DAYS_IN_WEEK // Should not be changed let MAX_NUMBER_OF_ROWS_PER_MONTH = 6 // Should not be changed let MIN_NUMBER_OF_ROWS_PER_MONTH = 1 // Should not be changed let FIRST_DAY_INDEX = 0 let OFFSET_CALC = 2 let NUMBER_OF_DAYS_INDEX = 1 let DATE_SELECTED_INDEX = 2 let TOTAL_DAYS_IN_MONTH = 3 let DATE_BOUNDRY = 4 /// Describes which month the cell belongs to /// - ThisMonth: Cell belongs to the current month /// - PreviousMonthWithinBoundary: Cell belongs to the previous month. Previous month is included in the date boundary you have set in your delegate /// - PreviousMonthOutsideBoundary: Cell belongs to the previous month. Previous month is not included in the date boundary you have set in your delegate /// - FollowingMonthWithinBoundary: Cell belongs to the following month. Following month is included in the date boundary you have set in your delegate /// - FollowingMonthOutsideBoundary: Cell belongs to the following month. Following month is not included in the date boundary you have set in your delegate /// /// You can use these cell states to configure how you want your date cells to look. Eg. you can have the colors belonging to the month be in color black, while the colors of previous months be in color gray. public struct CellState { public enum DateOwner: Int { /// Describes the state of a date-cell case ThisMonth = 0, PreviousMonthWithinBoundary, PreviousMonthOutsideBoundary, FollowingMonthWithinBoundary, FollowingMonthOutsideBoundary } public let isSelected: Bool public let text: String public let dateBelongsTo: DateOwner } /// Days of the week. By setting you calandar's first day of week, you can change which day is the first for the week. Sunday is by default. public enum DaysOfWeek: Int { /// Days of the week. case Sunday = 7, Monday = 6, Tuesday = 5, Wednesday = 4, Thursday = 10, Friday = 9, Saturday = 8 } protocol JTAppleCalendarDelegateProtocol: class { func numberOfRows() -> Int func numberOfColumns() -> Int func numberOfsectionsPermonth() -> Int func numberOfSections() -> Int } /// The JTAppleCalendarViewDataSource protocol is adopted by an object that mediates the application’™s data model for a JTAppleCalendarViewDataSource object. The data source provides the calendar-view object with the information it needs to construct and modify it self public protocol JTAppleCalendarViewDataSource { /// Asks the data source to return the start and end boundary dates as well as the calendar to use. You should properly configure your calendar at this point. /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - returns: /// - startDate: The *start* boundary date for your calendarView. /// - endDate: The *end* boundary date for your calendarView. /// - calendar: The *calendar* to be used by the calendarView. func configureCalendar(calendar: JTAppleCalendarView) -> (startDate: NSDate, endDate: NSDate, calendar: NSCalendar) } /// The delegate of a JTAppleCalendarView object must adopt the JTAppleCalendarViewDelegate protocol. /// Optional methods of the protocol allow the delegate to manage selections, and configure the cells. public protocol JTAppleCalendarViewDelegate { /// Asks the delegate if selecting the date-cell with a specified date is allowed /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. /// - cellState: The month the date-cell belongs to. /// - returns: A Bool value indicating if the operation can be done. func calendar(calendar : JTAppleCalendarView, canSelectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState) -> Bool /// Asks the delegate if de-selecting the date-cell with a specified date is allowed /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. /// - cellState: The month the date-cell belongs to. /// - returns: A Bool value indicating if the operation can be done. func calendar(calendar : JTAppleCalendarView, canDeselectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState) -> Bool /// Tells the delegate that a date-cell with a specified date was selected /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. This may be nil if the selected cell is off the screen /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, didSelectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) -> Void /// Tells the delegate that a date-cell with a specified date was de-selected /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. This may be nil if the selected cell is off the screen /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, didDeselectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) -> Void /// Tells the delegate that the JTAppleCalendar view scrolled to a segment beginning and ending with a particular date /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date at the start of the segment. /// - cell: The date at the end of the segment. func calendar(calendar : JTAppleCalendarView, didScrollToDateSegmentStartingWith date: NSDate?, endingWithDate: NSDate?) -> Void /// Tells the delegate that the JTAppleCalendar is about to display a date-cell. This is the point of customization for your date cells /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - cell: The date-cell that is about to be displayed. /// - date: The date attached to the cell. /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, isAboutToDisplayCell cell: JTAppleDayCellView, date:NSDate, cellState: CellState) -> Void } public extension JTAppleCalendarViewDelegate { func calendar(calendar : JTAppleCalendarView, canSelectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState)->Bool {return true} func calendar(calendar : JTAppleCalendarView, canDeselectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState)->Bool {return true} func calendar(calendar : JTAppleCalendarView, didSelectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) {} func calendar(calendar : JTAppleCalendarView, didDeselectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) {} func calendar(calendar : JTAppleCalendarView, didScrollToDateSegmentStartingWith date: NSDate?, endingWithDate: NSDate?) {} func calendar(calendar : JTAppleCalendarView, isAboutToDisplayCell cell: JTAppleDayCellView, date:NSDate, cellState: CellState) {} } /// An instance of JTAppleCalendarView (or simply, a calendar view) is a means for displaying and interacting with a gridstyle layout of date-cells public class JTAppleCalendarView: UIView { /// The amount of buffer space before the first row of date-cells public var bufferTop: CGFloat = 0.0 /// The amount of buffer space after the last row of date-cells public var bufferBottom: CGFloat = 0.0 /// Enables and disables animations when scrolling to and from date-cells public var animationsEnabled = true /// The scroll direction of the sections in JTAppleCalendar. public var direction : UICollectionViewScrollDirection = .Horizontal { didSet { let layout = generateNewLayout() calendarView.collectionViewLayout = layout reloadData(false) } } /// Enables/Disables multiple selection on JTAppleCalendar public var allowsMultipleSelection: Bool = false { didSet { self.calendarView.allowsMultipleSelection = allowsMultipleSelection } } /// First day of the week value for JTApleCalendar. You can set this to anyday public var firstDayOfWeek = DaysOfWeek.Sunday private var layoutNeedsUpdating = false /// Number of rows to be displayed per month. Allowed values are 1, 2, 3 & 6. /// After changing this value, you should reload your calendarView to show your change public var numberOfRowsPerMonth = 6 { didSet { if numberOfRowsPerMonth == 4 || numberOfRowsPerMonth == 5 || numberOfRowsPerMonth > 6 || numberOfRowsPerMonth < 0 {numberOfRowsPerMonth = 6} if cachedConfiguration != nil { layoutNeedsUpdating = true } } } /// The object that acts as the data source of the calendar view. public var dataSource : JTAppleCalendarViewDataSource? { didSet { if monthInfo.count < 1 { monthInfo = setupMonthInfoDataForStartAndEndDate() } reloadData(false) } } /// The object that acts as the delegate of the calendar view. public var delegate : JTAppleCalendarViewDelegate? private var scrollToDatePathOnRowChange: NSDate? private var delayedExecutionClosure: (()->Void)? private var currentSectionPage: Int { let cvbounds = self.calendarView.bounds var page : Int = 0 if self.direction == .Horizontal { page = Int(floor(self.calendarView.contentOffset.x / cvbounds.size.width)) } else { page = Int(floor(self.calendarView.contentOffset.y / cvbounds.size.height)) } let totalSections = monthInfo.count * numberOfSectionsPerMonth if page >= totalSections {return totalSections - 1} return page > 0 ? page : 0 } lazy private var startDateCache : NSDate? = { [weak self] in self!.cachedConfiguration?.startDate }() lazy private var endDateCache : NSDate? = { [weak self] in self!.cachedConfiguration?.startDate }() lazy private var calendar : NSCalendar? = { [weak self] in self!.cachedConfiguration?.calendar }() lazy private var cachedConfiguration : (startDate: NSDate, endDate: NSDate, calendar: NSCalendar)? = { [weak self] in print(self!.dataSource) if let config = self!.dataSource?.configureCalendar(self!) { return (startDate: config.startDate, endDate: config.endDate, calendar: config.calendar) } return nil }() lazy private var startOfMonthCache : NSDate = { [weak self] in let currentDate = NSDate() guard let validCachedConfig = self!.cachedConfiguration else { print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate } let dayOneComponents = validCachedConfig.calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: validCachedConfig.startDate) if let date = validCachedConfig.calendar.dateFromComponents(dayOneComponents) { return date } print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate }() lazy private var endOfMonthCache : NSDate = { [weak self] in // set last of month let currentDate = NSDate() guard let validCachedConfig = self!.cachedConfiguration else { print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate } let lastDayComponents = validCachedConfig.calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: validCachedConfig.endDate) lastDayComponents.month = lastDayComponents.month + 1 lastDayComponents.day = 0 if let returnDate = validCachedConfig.calendar.dateFromComponents(lastDayComponents) { return returnDate } print("Error: Date was not correctly generated for end of month. current date was used: \(currentDate)") return currentDate }() private(set) var selectedIndexPaths : [NSIndexPath] = [NSIndexPath]() public var selectedDates : [NSDate] = [NSDate]() lazy private var monthInfo : [[Int]] = { [weak self] in let newMonthInfo = self!.setupMonthInfoDataForStartAndEndDate() return newMonthInfo }() private var numberOfMonthSections: Int = 0 private var numberOfSectionsPerMonth: Int = 0 private var numberOfItemsPerSection: Int {return MAX_NUMBER_OF_DAYS_IN_WEEK * numberOfRowsPerMonth} /// Cell inset padding for the x and y axis of every date-cell on the calendar view. public var cellInset: CGPoint { get {return internalCellInset} set {internalCellInset = newValue} } /// Enable or disable paging when the calendar view is scrolled public var pagingEnabled: Bool = true { didSet { calendarView.pagingEnabled = pagingEnabled } } /// Enable or disable swipe scrolling of the calendar with this variable public var scrollEnabled: Bool = true { didSet { calendarView.scrollEnabled = scrollEnabled } } lazy private var calendarView : UICollectionView = { let layout = JTAppleCalendarHorizontalFlowLayout(withDelegate: self) layout.scrollDirection = self.direction layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) cv.dataSource = self cv.delegate = self cv.pagingEnabled = true cv.backgroundColor = UIColor.clearColor() cv.showsHorizontalScrollIndicator = false cv.showsVerticalScrollIndicator = false cv.allowsMultipleSelection = false return cv }() private func updateLayoutItemSize (layout: JTAppleCalendarLayoutProtocol) { layout.itemSize = CGSizeMake( self.calendarView.frame.size.width / CGFloat(MAX_NUMBER_OF_DAYS_IN_WEEK), (self.calendarView.frame.size.height - layout.headerReferenceSize.height) / CGFloat(numberOfRowsPerMonth) ) self.calendarView.collectionViewLayout = layout as! UICollectionViewLayout } /// The frame rectangle which defines the view's location and size in its superview coordinate system. override public var frame: CGRect { didSet { calendarView.frame = CGRect(x:0.0, y:bufferTop, width: self.frame.size.width, height:self.frame.size.height - bufferBottom) calendarView.collectionViewLayout.invalidateLayout() updateLayoutItemSize(self.calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol) } } override init(frame: CGRect) { super.init(frame : CGRectMake(0.0, 0.0, 200.0, 200.0)) self.initialSetup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file. override public func awakeFromNib() { self.initialSetup() } /// Lays out subviews. override public func layoutSubviews() { self.frame = super.frame } // MARK: Setup func initialSetup() { self.clipsToBounds = true self.calendarView.registerClass(JTAppleDayCell.self, forCellWithReuseIdentifier: cellReuseIdentifier) self.addSubview(self.calendarView) } /// Let's the calendar know which cell xib to use for the displaying of it's date-cells. /// - Parameter name: The name of the xib of your cell design public func registerCellViewXib(fileName name: String) { cellViewXibName = name } /// Reloads the data on the calendar view public func reloadData() { reloadData(true) } private func reloadData(checkDelegateDataSource: Bool) { if checkDelegateDataSource { self.checkDelegateDataSource() // Reload the datasource } // Delay on main thread. We want this to be called after the view is displayed ont he main run loop if self.layoutNeedsUpdating { delayRunOnMainThread(0.0, closure: { self.changeNumberOfRowsPerMonthTo(self.numberOfRowsPerMonth, withFocusDate: nil) }) } else { self.calendarView.reloadData() } } private func checkDelegateDataSource() { if let newDateBoundary = dataSource?.configureCalendar(self), oldDateBoundary = cachedConfiguration { // Jt101 do a check in each lazy var to see if user has bad star/end dates let newStartOfMonth = NSDate.startOfMonthForDate(newDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let newEndOfMonth = NSDate.endOfMonthForDate(newDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let oldStartOfMonth = NSDate.startOfMonthForDate(oldDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let oldEndOfMonth = NSDate.endOfMonthForDate(oldDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) if newStartOfMonth != oldStartOfMonth || newEndOfMonth != oldEndOfMonth || newDateBoundary.calendar != oldDateBoundary.calendar { startDateCache = newDateBoundary.startDate endDateCache = newDateBoundary.endDate calendar = newDateBoundary.calendar layoutNeedsUpdating = true } } } /// Change the number of rows per month on the calendar view. Once the row count is changed, the calendar view will auto-focus on the date provided. The calendarView will also reload its data. /// - Parameter number: The number of rows per month the calendar view should display. This is restricted to 1, 2, 3, & 6. 6 will be chosen as default. public func changeNumberOfRowsPerMonthTo(number: Int, withFocusDate date: NSDate?) { self.scrollToDatePathOnRowChange = date switch number { case 1, 2, 3: self.numberOfRowsPerMonth = number default: self.numberOfRowsPerMonth = 6 } self.configureChangeOfRows() } private func configureChangeOfRows() { selectedDates.removeAll() selectedIndexPaths.removeAll() monthInfo = setupMonthInfoDataForStartAndEndDate() let layout = calendarView.collectionViewLayout updateLayoutItemSize(layout as! JTAppleCalendarLayoutProtocol) self.calendarView.setCollectionViewLayout(layout, animated: true) self.calendarView.reloadData() layoutNeedsUpdating = false guard let dateToScrollTo = scrollToDatePathOnRowChange else { // If the date is invalid just scroll to the the first item on the view let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: position, animated: animationsEnabled) return } delayRunOnMainThread(0.0, closure: { () -> () in self.scrollToDate(dateToScrollTo) }) } func generateNewLayout() -> UICollectionViewLayout { if direction == .Horizontal { let layout = JTAppleCalendarHorizontalFlowLayout(withDelegate: self) layout.scrollDirection = direction return layout } else { let layout = JTAppleCalendarVerticalFlowLayout() layout.scrollDirection = direction layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 return layout } } private func setupMonthInfoDataForStartAndEndDate()-> [[Int]] { var retval: [[Int]] = [] if let validConfig = dataSource?.configureCalendar(self) { // check if the dates are in correct order if validConfig.calendar.compareDate(validConfig.startDate, toDate: validConfig.endDate, toUnitGranularity: NSCalendarUnit.Nanosecond) == NSComparisonResult.OrderedDescending { // print("No dates can be generated because your start date is greater than your end date.") return retval } cachedConfiguration = validConfig if let startMonth = NSDate.startOfMonthForDate(validConfig.startDate, usingCalendar: validConfig.calendar), endMonth = NSDate.endOfMonthForDate(validConfig.endDate, usingCalendar: validConfig.calendar) { startOfMonthCache = startMonth endOfMonthCache = endMonth let differenceComponents = validConfig.calendar.components( NSCalendarUnit.Month, fromDate: startOfMonthCache, toDate: endOfMonthCache, options: [] ) // Create boundary date let leftDate = validConfig.calendar.dateByAddingUnit(.Weekday, value: -1, toDate: startOfMonthCache, options: [])! let leftDateInt = validConfig.calendar.component(.Day, fromDate: leftDate) // Number of months numberOfMonthSections = differenceComponents.month + 1 // if we are for example on the same month and the difference is 0 we still need 1 to display it // Number of sections in each month numberOfSectionsPerMonth = Int(ceil(Float(MAX_NUMBER_OF_ROWS_PER_MONTH) / Float(numberOfRowsPerMonth))) // Section represents # of months. section is used as an offset to determine which month to calculate for numberOfMonthsIndex in 0 ... numberOfMonthSections - 1 { if let correctMonthForSectionDate = validConfig.calendar.dateByAddingUnit(.Month, value: numberOfMonthsIndex, toDate: startOfMonthCache, options: []) { let numberOfDaysInMonth = validConfig.calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: correctMonthForSectionDate).length var firstWeekdayOfMonthIndex = validConfig.calendar.component(.Weekday, fromDate: correctMonthForSectionDate) firstWeekdayOfMonthIndex -= 1 // firstWeekdayOfMonthIndex should be 0-Indexed firstWeekdayOfMonthIndex = (firstWeekdayOfMonthIndex + firstDayOfWeek.rawValue) % 7 // push it modularly so that we take it back one day so that the first day is Monday instead of Sunday which is the default // We have number of days in month, now lets see how these days will be allotted into the number of sections in the month // We will add the first segment manually to handle the fdIndex inset let aFullSection = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK) var numberOfDaysInFirstSection = aFullSection - firstWeekdayOfMonthIndex // If the number of days in first section is greater that the days of the month, then use days of month instead if numberOfDaysInFirstSection > numberOfDaysInMonth { numberOfDaysInFirstSection = numberOfDaysInMonth } let firstSectionDetail: [Int] = [firstWeekdayOfMonthIndex, numberOfDaysInFirstSection, 0, numberOfDaysInMonth] //fdIndex, numberofDaysInMonth, offset retval.append(firstSectionDetail) let numberOfSectionsLeft = numberOfSectionsPerMonth - 1 // Continue adding other segment details in loop if numberOfSectionsLeft < 1 {continue} // Continue if there are no more sections var numberOfDaysLeft = numberOfDaysInMonth - numberOfDaysInFirstSection for _ in 0 ... numberOfSectionsLeft - 1 { switch numberOfDaysLeft { case _ where numberOfDaysLeft <= aFullSection: // Partial rows let midSectionDetail: [Int] = [0, numberOfDaysLeft, firstWeekdayOfMonthIndex] retval.append(midSectionDetail) numberOfDaysLeft = 0 case _ where numberOfDaysLeft > aFullSection: // Full Rows let lastPopulatedSectionDetail: [Int] = [0, aFullSection, firstWeekdayOfMonthIndex] retval.append(lastPopulatedSectionDetail) numberOfDaysLeft -= aFullSection default: break } } } } retval[0].append(leftDateInt) } } return retval } /// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToNextSegment(animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage if page + 1 < monthInfo.count { let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection:page + 1), atScrollPosition: position, animated: animateScroll) } } /// Scrolls the calendar view to the previous section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToPreviousSegment(animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage if page - 1 > -1 { let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection:page - 1), atScrollPosition: position, animated: animateScroll) } } private func xibFileValid() -> Bool { guard let xibName = cellViewXibName else { // print("Did you remember to register your xib file to JTAppleCalendarView? call the registerCellViewXib method on it because xib filename is nil") return false } guard let viewObject = NSBundle.mainBundle().loadNibNamed(xibName, owner: self, options: [:]) where viewObject.count > 0 else { // print("your nib file name \(cellViewXibName) could not be loaded)") return false } guard let _ = viewObject[0] as? JTAppleDayCellView else { // print("xib file class does not conform to the protocol<JTAppleDayCellViewProtocol>") return false } return true } /// Scrolls the calendar view to the start of a section view containing a specified date. /// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToDate(date: NSDate, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { guard let validCachedCalendar = calendar else { return } let components = validCachedCalendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = validCachedCalendar.dateFromComponents(components)! if !(firstDayOfDate >= startOfMonthCache && firstDayOfDate <= endOfMonthCache) { return } let retrievedPathsFromDates = pathsFromDates([date]) if retrievedPathsFromDates.count > 0 { let sectionIndexPath = pathsFromDates([date])[0] delayedExecutionClosure = completionHandler let segmentToScrollTo = pagingEnabled ? NSIndexPath(forItem: 0, inSection: sectionIndexPath.section) : sectionIndexPath let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top delayRunOnMainThread(0.0, closure: { self.calendarView.scrollToItemAtIndexPath(segmentToScrollTo, atScrollPosition: position, animated: animateScroll) if !animateScroll { self.scrollViewDidEndScrollingAnimation(self.calendarView) } }) } } /// Select a date-cell if it is on screen /// - Parameter date: The date-cell with this date will be selected /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(dates: [NSDate], triggerSelectionDelegate: Bool = true) { delayRunOnMainThread(0.0) { guard let validCachedCalendar = self.calendar else { return } var allIndexPathsToReload: [NSIndexPath] = [] for date in dates { let components = validCachedCalendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = validCachedCalendar.dateFromComponents(components)! if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { // If the date is not within valid boundaries, then exit continue } let pathFromDates = self.pathsFromDates([date]) // If the date path youre searching for, doesnt exist, then return if pathFromDates.count < 0 { continue } let sectionIndexPath = pathFromDates[0] allIndexPathsToReload.append(sectionIndexPath) let selectTheDate = { if self.selectedIndexPaths.contains(sectionIndexPath) == false { // Can contain the value already if the user selected the same date twice. self.selectedDates.append(date) self.selectedIndexPaths.append(sectionIndexPath) } self.calendarView.selectItemAtIndexPath(sectionIndexPath, animated: false, scrollPosition: .None) // If triggereing is enabled, then let their delegate handle the reloading of view, else we will reload the data if triggerSelectionDelegate { self.collectionView(self.calendarView, didSelectItemAtIndexPath: sectionIndexPath) } } let deSelectTheDate = { (indexPath: NSIndexPath) -> Void in self.calendarView.deselectItemAtIndexPath(indexPath, animated: false) if self.selectedIndexPaths.contains(indexPath), let index = self.selectedIndexPaths.indexOf(indexPath) { self.selectedIndexPaths.removeAtIndex(index) self.selectedDates.removeAtIndex(index) } if triggerSelectionDelegate { self.collectionView(self.calendarView, didDeselectItemAtIndexPath: indexPath) } } // Remove old selections if self.calendarView.allowsMultipleSelection == false { // If single selection is ON for indexPath in self.selectedIndexPaths { if indexPath != sectionIndexPath { deSelectTheDate(indexPath) } } // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } else { // If multiple selection is on. Multiple selection behaves differently to singleselection. It behaves like a toggle. if self.selectedIndexPaths.contains(sectionIndexPath) { // If this cell is already selected, then deselect it deSelectTheDate(sectionIndexPath) } else { // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } } } if triggerSelectionDelegate == false { self.calendarView.reloadItemsAtIndexPaths(allIndexPathsToReload) // self.reloadData() } } } /// Reload the date of specified date-cells on the calendar-view /// - Parameter dates: Date-cells with these specified dates will be reloaded public func reloadDates(dates: [NSDate]) { let paths = pathsFromDates(dates) reloadPaths(paths) } func reloadPaths(indexPaths: [NSIndexPath]) { if indexPaths.count > 0 { calendarView.reloadItemsAtIndexPaths(indexPaths) } } private func pathsFromDates(dates:[NSDate])-> [NSIndexPath] { var returnPaths: [NSIndexPath] = [] guard let validCachedCalendar = calendar else { return returnPaths } for date in dates { if date >= startOfMonthCache && date <= endOfMonthCache { let periodApart = validCachedCalendar.components(.Month, fromDate: startOfMonthCache, toDate: date, options: []) let monthSectionIndex = periodApart.month let startSectionIndex = monthSectionIndex * numberOfSectionsPerMonth let sectionIndex = startMonthSectionForSection(startSectionIndex) // Get the section within the month // Get the section Information let currentMonthInfo = monthInfo[sectionIndex] let dayIndex = validCachedCalendar.components(.Day, fromDate: date).day // Given the following, find the index Path let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let cellIndex = dayIndex + fdIndex - 1 let updatedSection = cellIndex / numberOfItemsPerSection let adjustedSection = sectionIndex + updatedSection let adjustedCellIndex = cellIndex - (numberOfItemsPerSection * (cellIndex / numberOfItemsPerSection)) returnPaths.append(NSIndexPath(forItem: adjustedCellIndex, inSection: adjustedSection)) } } return returnPaths } /// Returns the calendar view's current section boundary dates. /// - returns: /// - startDate: The start date of the current section /// - endDate: The end date of the current section public func currentCalendarSegment() -> (startDate: NSDate, endDate: NSDate)? { if monthInfo.count < 1 { return nil } let section = currentSectionPage let monthData = monthInfo[section] let itemLength = monthData[NUMBER_OF_DAYS_INDEX] let fdIndex = monthData[FIRST_DAY_INDEX] let startIndex = NSIndexPath(forItem: fdIndex, inSection: section) let endIndex = NSIndexPath(forItem: fdIndex + itemLength - 1, inSection: section) if let theStartDate = dateFromPath(startIndex), theEndDate = dateFromPath(endIndex) { return (theStartDate, theEndDate) } return nil } // MARK: Helper functions func cellWasNotDisabledByTheUser(cell: JTAppleDayCell) -> Bool { return cell.cellView.hidden == false && cell.cellView.userInteractionEnabled == true } } // MARK: scrollViewDelegates extension JTAppleCalendarView: UIScrollViewDelegate { /// Tells the delegate when a scrolling animation in the scroll view concludes. public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { scrollViewDidEndDecelerating(scrollView) delayedExecutionClosure?() delayedExecutionClosure = nil } /// Tells the delegate that the scroll view has ended decelerating the scrolling movement. public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // Determing the section from the scrollView direction let section = currentSectionPage // When ever the month/section is switched, let the flowlayout know which page it is on. This is needed in the event user switches orientatoin, we can use the index to snap back to correct position (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).pathForFocusItem = NSIndexPath(forItem: 0, inSection: section) if let currentSegmentDates = currentCalendarSegment() { self.delegate?.calendar(self, didScrollToDateSegmentStartingWith: currentSegmentDates.startDate, endingWithDate: currentSegmentDates.endDate) } } } extension JTAppleCalendarView { private func cellStateFromIndexPath(indexPath: NSIndexPath)->CellState { let itemIndex = indexPath.item let itemSection = indexPath.section let currentMonthInfo = monthInfo[itemSection] let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let nDays = currentMonthInfo[NUMBER_OF_DAYS_INDEX] let offSet = currentMonthInfo[OFFSET_CALC] var cellText: String = "" var dateBelongsTo: CellState.DateOwner = .ThisMonth if itemIndex >= fdIndex && itemIndex < fdIndex + nDays { let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - fdIndex - offSet + 1 cellText = String(cellDate) dateBelongsTo = .ThisMonth } else if itemIndex < fdIndex && itemSection - 1 > -1 { // Prior month is available let startOfMonthSection = startMonthSectionForSection(itemSection - 1) let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - offSet + 1 let dateToAdd = monthInfo[startOfMonthSection][TOTAL_DAYS_IN_MONTH] let dateInt = cellDate + dateToAdd - monthInfo[itemSection][FIRST_DAY_INDEX] cellText = String(dateInt) dateBelongsTo = .PreviousMonthWithinBoundary } else if itemIndex >= fdIndex + nDays && itemSection + 1 < monthInfo.count { // Following months let startOfMonthSection = startMonthSectionForSection(itemSection) let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - offSet + 1 let dateToSubtract = monthInfo[startOfMonthSection][TOTAL_DAYS_IN_MONTH] let dateInt = cellDate - dateToSubtract - monthInfo[itemSection][FIRST_DAY_INDEX] cellText = String(dateInt) dateBelongsTo = .FollowingMonthWithinBoundary } else if itemIndex < fdIndex { // Pre from the start let cellDate = monthInfo[0][DATE_BOUNDRY] - monthInfo[0][FIRST_DAY_INDEX] + itemIndex + 1 cellText = String(cellDate ) dateBelongsTo = .PreviousMonthOutsideBoundary } else { // Post from the end let c = calendar!.component(.Day, fromDate: dateFromPath(indexPath)!) cellText = String(c) dateBelongsTo = .FollowingMonthOutsideBoundary } let cellState = CellState( isSelected: selectedIndexPaths.contains(indexPath), text: cellText, dateBelongsTo: dateBelongsTo ) return cellState } private func startMonthSectionForSection(aSection: Int)->Int { let monthIndexWeAreOn = aSection / numberOfSectionsPerMonth let nextSection = numberOfSectionsPerMonth * monthIndexWeAreOn return nextSection } private func dateFromPath(indexPath: NSIndexPath)-> NSDate? { // Returns nil if date is out of scope guard let validCachedCalendar = calendar else { return nil } let itemIndex = indexPath.item let itemSection = indexPath.section let monthIndexWeAreOn = itemSection / numberOfSectionsPerMonth let currentMonthInfo = monthInfo[itemSection] let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let offSet = currentMonthInfo[OFFSET_CALC] let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - fdIndex - offSet + 1 let offsetComponents = NSDateComponents() offsetComponents.month = monthIndexWeAreOn offsetComponents.weekday = cellDate - 1 return validCachedCalendar.dateByAddingComponents(offsetComponents, toDate: startOfMonthCache, options: []) } private func delayRunOnMainThread(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } private func delayRunOnGlobalThread(delay:Double, qos: qos_class_t,closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_global_queue(qos, 0), closure) } } // MARK: CollectionView delegates extension JTAppleCalendarView: UICollectionViewDataSource, UICollectionViewDelegate { /// Asks your data source object for the cell that corresponds to the specified item in the collection view. public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if selectedIndexPaths.contains(indexPath) { collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) } else { collectionView.deselectItemAtIndexPath(indexPath, animated: false) } let dayCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! JTAppleDayCell let cellState = cellStateFromIndexPath(indexPath) let date = dateFromPath(indexPath)! delegate?.calendar(self, isAboutToDisplayCell: dayCell.cellView, date: date, cellState: cellState) return dayCell } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { if !xibFileValid() { return 0 } if monthInfo.count > 0 { self.scrollViewDidEndDecelerating(self.calendarView) } return monthInfo.count } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return MAX_NUMBER_OF_DAYS_IN_WEEK * numberOfRowsPerMonth } public func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { if let dateUserSelected = dateFromPath(indexPath), delegate = self.delegate, cell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell { if cellWasNotDisabledByTheUser(cell) { let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, canSelectDate: dateUserSelected, cell: cell.cellView, cellState: cellState) return true } } return false // if date is out of scope } public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if let delegate = self.delegate, dateSelectedByUser = dateFromPath(indexPath) { // Update model if let index = selectedIndexPaths.indexOf(indexPath) { selectedIndexPaths.removeAtIndex(index) selectedDates.removeAtIndex(index) } let selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell // Cell may be nil if user switches month sections let cellState = cellStateFromIndexPath(indexPath) // Although the cell may be nil, we still want to return the cellstate delegate.calendar(self, didDeselectDate: dateSelectedByUser, cell: selectedCell?.cellView, cellState: cellState) } } public func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool { if let dateUserSelected = dateFromPath(indexPath), delegate = self.delegate, cell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell { let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, canDeselectDate: dateUserSelected, cell: cell.cellView, cellState: cellState) return true } return false } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let delegate = self.delegate, dateSelectedByUser = dateFromPath(indexPath) { // Update model if selectedIndexPaths.contains(indexPath) == false { // wrapping in IF statement handles both multiple select scenarios AND singleselection scenarios selectedIndexPaths.append(indexPath) selectedDates.append(dateSelectedByUser) } let selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, didSelectDate: dateSelectedByUser, cell: selectedCell?.cellView, cellState: cellState) } } } extension JTAppleCalendarView: JTAppleCalendarDelegateProtocol { func numberOfRows() -> Int { return numberOfRowsPerMonth } func numberOfColumns() -> Int { return MAX_NUMBER_OF_DAYS_IN_WEEK } func numberOfsectionsPermonth() -> Int { return numberOfSectionsPerMonth } func numberOfSections() -> Int { return numberOfMonthSections } } public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs === rhs || lhs.compare(rhs) == .OrderedSame } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } extension NSDate: Comparable { } private extension NSDate { class func numberOfDaysDifferenceBetweenFirstDate(firstDate: NSDate, secondDate: NSDate, usingCalendar calendar: NSCalendar)->Int { let date1 = calendar.startOfDayForDate(firstDate) let date2 = calendar.startOfDayForDate(secondDate) let flags = NSCalendarUnit.Day let components = calendar.components(flags, fromDate: date1, toDate: date2, options: .WrapComponents) return abs(components.day) } class func startOfMonthForDate(date: NSDate, usingCalendar calendar:NSCalendar) -> NSDate? { let dayOneComponents = calendar.components([.Era, .Year, .Month], fromDate: date) return calendar.dateFromComponents(dayOneComponents) } class func endOfMonthForDate(date: NSDate, usingCalendar calendar:NSCalendar) -> NSDate? { let lastDayComponents = calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: date) lastDayComponents.month = lastDayComponents.month + 1 lastDayComponents.day = 0 return calendar.dateFromComponents(lastDayComponents) } } Updated 1. Added missing Documentation 2. Cells now snap to position when in free flowing mode // // JTAppleCalendarView.swift // JTAppleCalendar // // Created by Jay Thomas on 2016-03-01. // Copyright © 2016 OS-Tech. All rights reserved. // let cellReuseIdentifier = "JTDayCell" let NUMBER_OF_DAYS_IN_WEEK = 7 let MAX_NUMBER_OF_DAYS_IN_WEEK = 7 // Should not be changed let MIN_NUMBER_OF_DAYS_IN_WEEK = MAX_NUMBER_OF_DAYS_IN_WEEK // Should not be changed let MAX_NUMBER_OF_ROWS_PER_MONTH = 6 // Should not be changed let MIN_NUMBER_OF_ROWS_PER_MONTH = 1 // Should not be changed let FIRST_DAY_INDEX = 0 let OFFSET_CALC = 2 let NUMBER_OF_DAYS_INDEX = 1 let DATE_SELECTED_INDEX = 2 let TOTAL_DAYS_IN_MONTH = 3 let DATE_BOUNDRY = 4 /// Describes which month the cell belongs to /// - ThisMonth: Cell belongs to the current month /// - PreviousMonthWithinBoundary: Cell belongs to the previous month. Previous month is included in the date boundary you have set in your delegate /// - PreviousMonthOutsideBoundary: Cell belongs to the previous month. Previous month is not included in the date boundary you have set in your delegate /// - FollowingMonthWithinBoundary: Cell belongs to the following month. Following month is included in the date boundary you have set in your delegate /// - FollowingMonthOutsideBoundary: Cell belongs to the following month. Following month is not included in the date boundary you have set in your delegate /// /// You can use these cell states to configure how you want your date cells to look. Eg. you can have the colors belonging to the month be in color black, while the colors of previous months be in color gray. public struct CellState { /// Describes which month owns the date public enum DateOwner: Int { /// Describes which month owns the date case ThisMonth = 0, PreviousMonthWithinBoundary, PreviousMonthOutsideBoundary, FollowingMonthWithinBoundary, FollowingMonthOutsideBoundary } /// returns true if a cell is selected public let isSelected: Bool /// returns the date as a string public let text: String /// returns the a description of which month owns the date public let dateBelongsTo: DateOwner } /// Days of the week. By setting you calandar's first day of week, you can change which day is the first for the week. Sunday is by default. public enum DaysOfWeek: Int { /// Days of the week. case Sunday = 7, Monday = 6, Tuesday = 5, Wednesday = 4, Thursday = 10, Friday = 9, Saturday = 8 } protocol JTAppleCalendarDelegateProtocol: class { func numberOfRows() -> Int func numberOfColumns() -> Int func numberOfsectionsPermonth() -> Int func numberOfSections() -> Int } /// The JTAppleCalendarViewDataSource protocol is adopted by an object that mediates the application’™s data model for a JTAppleCalendarViewDataSource object. The data source provides the calendar-view object with the information it needs to construct and modify it self public protocol JTAppleCalendarViewDataSource { /// Asks the data source to return the start and end boundary dates as well as the calendar to use. You should properly configure your calendar at this point. /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - returns: /// - startDate: The *start* boundary date for your calendarView. /// - endDate: The *end* boundary date for your calendarView. /// - calendar: The *calendar* to be used by the calendarView. func configureCalendar(calendar: JTAppleCalendarView) -> (startDate: NSDate, endDate: NSDate, calendar: NSCalendar) } /// The delegate of a JTAppleCalendarView object must adopt the JTAppleCalendarViewDelegate protocol. /// Optional methods of the protocol allow the delegate to manage selections, and configure the cells. public protocol JTAppleCalendarViewDelegate { /// Asks the delegate if selecting the date-cell with a specified date is allowed /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. /// - cellState: The month the date-cell belongs to. /// - returns: A Bool value indicating if the operation can be done. func calendar(calendar : JTAppleCalendarView, canSelectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState) -> Bool /// Asks the delegate if de-selecting the date-cell with a specified date is allowed /// - Parameters: /// - calendar: The JTAppleCalendar view requesting this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. /// - cellState: The month the date-cell belongs to. /// - returns: A Bool value indicating if the operation can be done. func calendar(calendar : JTAppleCalendarView, canDeselectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState) -> Bool /// Tells the delegate that a date-cell with a specified date was selected /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. This may be nil if the selected cell is off the screen /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, didSelectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) -> Void /// Tells the delegate that a date-cell with a specified date was de-selected /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date attached to the date-cell. /// - cell: The date-cell view. This can be customized at this point. This may be nil if the selected cell is off the screen /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, didDeselectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) -> Void /// Tells the delegate that the JTAppleCalendar view scrolled to a segment beginning and ending with a particular date /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - date: The date at the start of the segment. /// - cell: The date at the end of the segment. func calendar(calendar : JTAppleCalendarView, didScrollToDateSegmentStartingWith date: NSDate?, endingWithDate: NSDate?) -> Void /// Tells the delegate that the JTAppleCalendar is about to display a date-cell. This is the point of customization for your date cells /// - Parameters: /// - calendar: The JTAppleCalendar view giving this information. /// - cell: The date-cell that is about to be displayed. /// - date: The date attached to the cell. /// - cellState: The month the date-cell belongs to. func calendar(calendar : JTAppleCalendarView, isAboutToDisplayCell cell: JTAppleDayCellView, date:NSDate, cellState: CellState) -> Void } /// Default delegate functions public extension JTAppleCalendarViewDelegate { func calendar(calendar : JTAppleCalendarView, canSelectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState)->Bool {return true} func calendar(calendar : JTAppleCalendarView, canDeselectDate date : NSDate, cell: JTAppleDayCellView, cellState: CellState)->Bool {return true} func calendar(calendar : JTAppleCalendarView, didSelectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) {} func calendar(calendar : JTAppleCalendarView, didDeselectDate date : NSDate, cell: JTAppleDayCellView?, cellState: CellState) {} func calendar(calendar : JTAppleCalendarView, didScrollToDateSegmentStartingWith date: NSDate?, endingWithDate: NSDate?) {} func calendar(calendar : JTAppleCalendarView, isAboutToDisplayCell cell: JTAppleDayCellView, date:NSDate, cellState: CellState) {} } /// An instance of JTAppleCalendarView (or simply, a calendar view) is a means for displaying and interacting with a gridstyle layout of date-cells public class JTAppleCalendarView: UIView { /// The amount of buffer space before the first row of date-cells public var bufferTop: CGFloat = 0.0 /// The amount of buffer space after the last row of date-cells public var bufferBottom: CGFloat = 0.0 /// Enables and disables animations when scrolling to and from date-cells public var animationsEnabled = true /// The scroll direction of the sections in JTAppleCalendar. public var direction : UICollectionViewScrollDirection = .Horizontal { didSet { let layout = generateNewLayout() calendarView.collectionViewLayout = layout reloadData(false) } } /// Enables/Disables multiple selection on JTAppleCalendar public var allowsMultipleSelection: Bool = false { didSet { self.calendarView.allowsMultipleSelection = allowsMultipleSelection } } /// First day of the week value for JTApleCalendar. You can set this to anyday public var firstDayOfWeek = DaysOfWeek.Sunday private var layoutNeedsUpdating = false /// Number of rows to be displayed per month. Allowed values are 1, 2, 3 & 6. /// After changing this value, you should reload your calendarView to show your change public var numberOfRowsPerMonth = 6 { didSet { if numberOfRowsPerMonth == 4 || numberOfRowsPerMonth == 5 || numberOfRowsPerMonth > 6 || numberOfRowsPerMonth < 0 {numberOfRowsPerMonth = 6} if cachedConfiguration != nil { layoutNeedsUpdating = true } } } /// The object that acts as the data source of the calendar view. public var dataSource : JTAppleCalendarViewDataSource? { didSet { if monthInfo.count < 1 { monthInfo = setupMonthInfoDataForStartAndEndDate() } reloadData(false) } } /// The object that acts as the delegate of the calendar view. public var delegate : JTAppleCalendarViewDelegate? private var scrollToDatePathOnRowChange: NSDate? private var delayedExecutionClosure: (()->Void)? private var currentSectionPage: Int { let cvbounds = self.calendarView.bounds var page : Int = 0 if self.direction == .Horizontal { page = Int(floor(self.calendarView.contentOffset.x / cvbounds.size.width)) } else { page = Int(floor(self.calendarView.contentOffset.y / cvbounds.size.height)) } let totalSections = monthInfo.count * numberOfSectionsPerMonth if page >= totalSections {return totalSections - 1} return page > 0 ? page : 0 } lazy private var startDateCache : NSDate? = { [weak self] in self!.cachedConfiguration?.startDate }() lazy private var endDateCache : NSDate? = { [weak self] in self!.cachedConfiguration?.startDate }() lazy private var calendar : NSCalendar? = { [weak self] in self!.cachedConfiguration?.calendar }() lazy private var cachedConfiguration : (startDate: NSDate, endDate: NSDate, calendar: NSCalendar)? = { [weak self] in print(self!.dataSource) if let config = self!.dataSource?.configureCalendar(self!) { return (startDate: config.startDate, endDate: config.endDate, calendar: config.calendar) } return nil }() lazy private var startOfMonthCache : NSDate = { [weak self] in let currentDate = NSDate() guard let validCachedConfig = self!.cachedConfiguration else { print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate } let dayOneComponents = validCachedConfig.calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: validCachedConfig.startDate) if let date = validCachedConfig.calendar.dateFromComponents(dayOneComponents) { return date } print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate }() lazy private var endOfMonthCache : NSDate = { [weak self] in // set last of month let currentDate = NSDate() guard let validCachedConfig = self!.cachedConfiguration else { print("Error: Date was not correctly generated for start of month. current date was used: \(currentDate)") return currentDate } let lastDayComponents = validCachedConfig.calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: validCachedConfig.endDate) lastDayComponents.month = lastDayComponents.month + 1 lastDayComponents.day = 0 if let returnDate = validCachedConfig.calendar.dateFromComponents(lastDayComponents) { return returnDate } print("Error: Date was not correctly generated for end of month. current date was used: \(currentDate)") return currentDate }() private(set) var selectedIndexPaths : [NSIndexPath] = [NSIndexPath]() /// Returns all selected dates public var selectedDates : [NSDate] = [NSDate]() lazy private var monthInfo : [[Int]] = { [weak self] in let newMonthInfo = self!.setupMonthInfoDataForStartAndEndDate() return newMonthInfo }() private var numberOfMonthSections: Int = 0 private var numberOfSectionsPerMonth: Int = 0 private var numberOfItemsPerSection: Int {return MAX_NUMBER_OF_DAYS_IN_WEEK * numberOfRowsPerMonth} /// Cell inset padding for the x and y axis of every date-cell on the calendar view. public var cellInset: CGPoint { get {return internalCellInset} set {internalCellInset = newValue} } /// Enable or disable paging when the calendar view is scrolled public var pagingEnabled: Bool = true { didSet { calendarView.pagingEnabled = pagingEnabled } } /// Enable or disable swipe scrolling of the calendar with this variable public var scrollEnabled: Bool = true { didSet { calendarView.scrollEnabled = scrollEnabled } } /// This is only applicable when calendar view paging is not enabled. Use this variable to decelerate the scroll movement to make it more 'sticky' or more fluid scrolling public var scrollResistance: CGFloat = 0.75 lazy private var calendarView : UICollectionView = { let layout = JTAppleCalendarHorizontalFlowLayout(withDelegate: self) layout.scrollDirection = self.direction layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) cv.dataSource = self cv.delegate = self cv.pagingEnabled = true cv.backgroundColor = UIColor.clearColor() cv.showsHorizontalScrollIndicator = false cv.showsVerticalScrollIndicator = false cv.allowsMultipleSelection = false return cv }() private func updateLayoutItemSize (layout: JTAppleCalendarLayoutProtocol) { layout.itemSize = CGSizeMake( self.calendarView.frame.size.width / CGFloat(MAX_NUMBER_OF_DAYS_IN_WEEK), (self.calendarView.frame.size.height - layout.headerReferenceSize.height) / CGFloat(numberOfRowsPerMonth) ) self.calendarView.collectionViewLayout = layout as! UICollectionViewLayout } /// The frame rectangle which defines the view's location and size in its superview coordinate system. override public var frame: CGRect { didSet { calendarView.frame = CGRect(x:0.0, y:bufferTop, width: self.frame.size.width, height:self.frame.size.height - bufferBottom) calendarView.collectionViewLayout.invalidateLayout() updateLayoutItemSize(self.calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol) } } override init(frame: CGRect) { super.init(frame : CGRectMake(0.0, 0.0, 200.0, 200.0)) self.initialSetup() } /// Returns an object initialized from data in a given unarchiver. self, initialized using the data in decoder. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file. override public func awakeFromNib() { self.initialSetup() } /// Lays out subviews. override public func layoutSubviews() { self.frame = super.frame } // MARK: Setup func initialSetup() { self.clipsToBounds = true self.calendarView.registerClass(JTAppleDayCell.self, forCellWithReuseIdentifier: cellReuseIdentifier) self.addSubview(self.calendarView) } /// Let's the calendar know which cell xib to use for the displaying of it's date-cells. /// - Parameter name: The name of the xib of your cell design public func registerCellViewXib(fileName name: String) { cellViewXibName = name } /// Reloads the data on the calendar view public func reloadData() { reloadData(true) } private func reloadData(checkDelegateDataSource: Bool) { if checkDelegateDataSource { self.checkDelegateDataSource() // Reload the datasource } // Delay on main thread. We want this to be called after the view is displayed ont he main run loop if self.layoutNeedsUpdating { delayRunOnMainThread(0.0, closure: { self.changeNumberOfRowsPerMonthTo(self.numberOfRowsPerMonth, withFocusDate: nil) }) } else { self.calendarView.reloadData() } } private func checkDelegateDataSource() { if let newDateBoundary = dataSource?.configureCalendar(self), oldDateBoundary = cachedConfiguration { // Jt101 do a check in each lazy var to see if user has bad star/end dates let newStartOfMonth = NSDate.startOfMonthForDate(newDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let newEndOfMonth = NSDate.endOfMonthForDate(newDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let oldStartOfMonth = NSDate.startOfMonthForDate(oldDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) let oldEndOfMonth = NSDate.endOfMonthForDate(oldDateBoundary.startDate, usingCalendar: oldDateBoundary.calendar) if newStartOfMonth != oldStartOfMonth || newEndOfMonth != oldEndOfMonth || newDateBoundary.calendar != oldDateBoundary.calendar { startDateCache = newDateBoundary.startDate endDateCache = newDateBoundary.endDate calendar = newDateBoundary.calendar layoutNeedsUpdating = true } } } /// Change the number of rows per month on the calendar view. Once the row count is changed, the calendar view will auto-focus on the date provided. The calendarView will also reload its data. /// - Parameter number: The number of rows per month the calendar view should display. This is restricted to 1, 2, 3, & 6. 6 will be chosen as default. public func changeNumberOfRowsPerMonthTo(number: Int, withFocusDate date: NSDate?) { self.scrollToDatePathOnRowChange = date switch number { case 1, 2, 3: self.numberOfRowsPerMonth = number default: self.numberOfRowsPerMonth = 6 } self.configureChangeOfRows() } private func configureChangeOfRows() { selectedDates.removeAll() selectedIndexPaths.removeAll() monthInfo = setupMonthInfoDataForStartAndEndDate() let layout = calendarView.collectionViewLayout updateLayoutItemSize(layout as! JTAppleCalendarLayoutProtocol) self.calendarView.setCollectionViewLayout(layout, animated: true) self.calendarView.reloadData() layoutNeedsUpdating = false guard let dateToScrollTo = scrollToDatePathOnRowChange else { // If the date is invalid just scroll to the the first item on the view let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: position, animated: animationsEnabled) return } delayRunOnMainThread(0.0, closure: { () -> () in self.scrollToDate(dateToScrollTo) }) } func generateNewLayout() -> UICollectionViewLayout { if direction == .Horizontal { let layout = JTAppleCalendarHorizontalFlowLayout(withDelegate: self) layout.scrollDirection = direction return layout } else { let layout = JTAppleCalendarVerticalFlowLayout() layout.scrollDirection = direction layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 return layout } } private func setupMonthInfoDataForStartAndEndDate()-> [[Int]] { var retval: [[Int]] = [] if let validConfig = dataSource?.configureCalendar(self) { // check if the dates are in correct order if validConfig.calendar.compareDate(validConfig.startDate, toDate: validConfig.endDate, toUnitGranularity: NSCalendarUnit.Nanosecond) == NSComparisonResult.OrderedDescending { // print("No dates can be generated because your start date is greater than your end date.") return retval } cachedConfiguration = validConfig if let startMonth = NSDate.startOfMonthForDate(validConfig.startDate, usingCalendar: validConfig.calendar), endMonth = NSDate.endOfMonthForDate(validConfig.endDate, usingCalendar: validConfig.calendar) { startOfMonthCache = startMonth endOfMonthCache = endMonth let differenceComponents = validConfig.calendar.components( NSCalendarUnit.Month, fromDate: startOfMonthCache, toDate: endOfMonthCache, options: [] ) // Create boundary date let leftDate = validConfig.calendar.dateByAddingUnit(.Weekday, value: -1, toDate: startOfMonthCache, options: [])! let leftDateInt = validConfig.calendar.component(.Day, fromDate: leftDate) // Number of months numberOfMonthSections = differenceComponents.month + 1 // if we are for example on the same month and the difference is 0 we still need 1 to display it // Number of sections in each month numberOfSectionsPerMonth = Int(ceil(Float(MAX_NUMBER_OF_ROWS_PER_MONTH) / Float(numberOfRowsPerMonth))) // Section represents # of months. section is used as an offset to determine which month to calculate for numberOfMonthsIndex in 0 ... numberOfMonthSections - 1 { if let correctMonthForSectionDate = validConfig.calendar.dateByAddingUnit(.Month, value: numberOfMonthsIndex, toDate: startOfMonthCache, options: []) { let numberOfDaysInMonth = validConfig.calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: correctMonthForSectionDate).length var firstWeekdayOfMonthIndex = validConfig.calendar.component(.Weekday, fromDate: correctMonthForSectionDate) firstWeekdayOfMonthIndex -= 1 // firstWeekdayOfMonthIndex should be 0-Indexed firstWeekdayOfMonthIndex = (firstWeekdayOfMonthIndex + firstDayOfWeek.rawValue) % 7 // push it modularly so that we take it back one day so that the first day is Monday instead of Sunday which is the default // We have number of days in month, now lets see how these days will be allotted into the number of sections in the month // We will add the first segment manually to handle the fdIndex inset let aFullSection = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK) var numberOfDaysInFirstSection = aFullSection - firstWeekdayOfMonthIndex // If the number of days in first section is greater that the days of the month, then use days of month instead if numberOfDaysInFirstSection > numberOfDaysInMonth { numberOfDaysInFirstSection = numberOfDaysInMonth } let firstSectionDetail: [Int] = [firstWeekdayOfMonthIndex, numberOfDaysInFirstSection, 0, numberOfDaysInMonth] //fdIndex, numberofDaysInMonth, offset retval.append(firstSectionDetail) let numberOfSectionsLeft = numberOfSectionsPerMonth - 1 // Continue adding other segment details in loop if numberOfSectionsLeft < 1 {continue} // Continue if there are no more sections var numberOfDaysLeft = numberOfDaysInMonth - numberOfDaysInFirstSection for _ in 0 ... numberOfSectionsLeft - 1 { switch numberOfDaysLeft { case _ where numberOfDaysLeft <= aFullSection: // Partial rows let midSectionDetail: [Int] = [0, numberOfDaysLeft, firstWeekdayOfMonthIndex] retval.append(midSectionDetail) numberOfDaysLeft = 0 case _ where numberOfDaysLeft > aFullSection: // Full Rows let lastPopulatedSectionDetail: [Int] = [0, aFullSection, firstWeekdayOfMonthIndex] retval.append(lastPopulatedSectionDetail) numberOfDaysLeft -= aFullSection default: break } } } } retval[0].append(leftDateInt) } } return retval } /// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToNextSegment(animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage if page + 1 < monthInfo.count { let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection:page + 1), atScrollPosition: position, animated: animateScroll) } } /// Scrolls the calendar view to the previous section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToPreviousSegment(animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { let page = currentSectionPage if page - 1 > -1 { let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top calendarView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection:page - 1), atScrollPosition: position, animated: animateScroll) } } private func xibFileValid() -> Bool { guard let xibName = cellViewXibName else { // print("Did you remember to register your xib file to JTAppleCalendarView? call the registerCellViewXib method on it because xib filename is nil") return false } guard let viewObject = NSBundle.mainBundle().loadNibNamed(xibName, owner: self, options: [:]) where viewObject.count > 0 else { // print("your nib file name \(cellViewXibName) could not be loaded)") return false } guard let _ = viewObject[0] as? JTAppleDayCellView else { // print("xib file class does not conform to the protocol<JTAppleDayCellViewProtocol>") return false } return true } /// Scrolls the calendar view to the start of a section view containing a specified date. /// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToDate(date: NSDate, animateScroll: Bool = true, completionHandler:(()->Void)? = nil) { guard let validCachedCalendar = calendar else { return } let components = validCachedCalendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = validCachedCalendar.dateFromComponents(components)! if !(firstDayOfDate >= startOfMonthCache && firstDayOfDate <= endOfMonthCache) { return } let retrievedPathsFromDates = pathsFromDates([date]) if retrievedPathsFromDates.count > 0 { let sectionIndexPath = pathsFromDates([date])[0] delayedExecutionClosure = completionHandler let segmentToScrollTo = pagingEnabled ? NSIndexPath(forItem: 0, inSection: sectionIndexPath.section) : sectionIndexPath let position: UICollectionViewScrollPosition = self.direction == .Horizontal ? .Left : .Top delayRunOnMainThread(0.0, closure: { self.calendarView.scrollToItemAtIndexPath(segmentToScrollTo, atScrollPosition: position, animated: animateScroll) if !animateScroll { self.scrollViewDidEndScrollingAnimation(self.calendarView) } }) } } /// Select a date-cell if it is on screen /// - Parameter date: The date-cell with this date will be selected /// - Parameter triggerDidSelectDelegate: Triggers the delegate function only if the value is set to true. Sometimes it is necessary to setup some dates without triggereing the delegate e.g. For instance, when youre initally setting up data in your viewDidLoad public func selectDates(dates: [NSDate], triggerSelectionDelegate: Bool = true) { delayRunOnMainThread(0.0) { guard let validCachedCalendar = self.calendar else { return } var allIndexPathsToReload: [NSIndexPath] = [] for date in dates { let components = validCachedCalendar.components([.Year, .Month, .Day], fromDate: date) let firstDayOfDate = validCachedCalendar.dateFromComponents(components)! if !(firstDayOfDate >= self.startOfMonthCache && firstDayOfDate <= self.endOfMonthCache) { // If the date is not within valid boundaries, then exit continue } let pathFromDates = self.pathsFromDates([date]) // If the date path youre searching for, doesnt exist, then return if pathFromDates.count < 0 { continue } let sectionIndexPath = pathFromDates[0] allIndexPathsToReload.append(sectionIndexPath) let selectTheDate = { if self.selectedIndexPaths.contains(sectionIndexPath) == false { // Can contain the value already if the user selected the same date twice. self.selectedDates.append(date) self.selectedIndexPaths.append(sectionIndexPath) } self.calendarView.selectItemAtIndexPath(sectionIndexPath, animated: false, scrollPosition: .None) // If triggereing is enabled, then let their delegate handle the reloading of view, else we will reload the data if triggerSelectionDelegate { self.collectionView(self.calendarView, didSelectItemAtIndexPath: sectionIndexPath) } } let deSelectTheDate = { (indexPath: NSIndexPath) -> Void in self.calendarView.deselectItemAtIndexPath(indexPath, animated: false) if self.selectedIndexPaths.contains(indexPath), let index = self.selectedIndexPaths.indexOf(indexPath) { self.selectedIndexPaths.removeAtIndex(index) self.selectedDates.removeAtIndex(index) } if triggerSelectionDelegate { self.collectionView(self.calendarView, didDeselectItemAtIndexPath: indexPath) } } // Remove old selections if self.calendarView.allowsMultipleSelection == false { // If single selection is ON for indexPath in self.selectedIndexPaths { if indexPath != sectionIndexPath { deSelectTheDate(indexPath) } } // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } else { // If multiple selection is on. Multiple selection behaves differently to singleselection. It behaves like a toggle. if self.selectedIndexPaths.contains(sectionIndexPath) { // If this cell is already selected, then deselect it deSelectTheDate(sectionIndexPath) } else { // Add new selections // Must be added here. If added in delegate didSelectItemAtIndexPath selectTheDate() } } } if triggerSelectionDelegate == false { self.calendarView.reloadItemsAtIndexPaths(allIndexPathsToReload) // self.reloadData() } } } /// Reload the date of specified date-cells on the calendar-view /// - Parameter dates: Date-cells with these specified dates will be reloaded public func reloadDates(dates: [NSDate]) { let paths = pathsFromDates(dates) reloadPaths(paths) } func reloadPaths(indexPaths: [NSIndexPath]) { if indexPaths.count > 0 { calendarView.reloadItemsAtIndexPaths(indexPaths) } } private func pathsFromDates(dates:[NSDate])-> [NSIndexPath] { var returnPaths: [NSIndexPath] = [] guard let validCachedCalendar = calendar else { return returnPaths } for date in dates { if date >= startOfMonthCache && date <= endOfMonthCache { let periodApart = validCachedCalendar.components(.Month, fromDate: startOfMonthCache, toDate: date, options: []) let monthSectionIndex = periodApart.month let startSectionIndex = monthSectionIndex * numberOfSectionsPerMonth let sectionIndex = startMonthSectionForSection(startSectionIndex) // Get the section within the month // Get the section Information let currentMonthInfo = monthInfo[sectionIndex] let dayIndex = validCachedCalendar.components(.Day, fromDate: date).day // Given the following, find the index Path let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let cellIndex = dayIndex + fdIndex - 1 let updatedSection = cellIndex / numberOfItemsPerSection let adjustedSection = sectionIndex + updatedSection let adjustedCellIndex = cellIndex - (numberOfItemsPerSection * (cellIndex / numberOfItemsPerSection)) returnPaths.append(NSIndexPath(forItem: adjustedCellIndex, inSection: adjustedSection)) } } return returnPaths } /// Returns the calendar view's current section boundary dates. /// - returns: /// - startDate: The start date of the current section /// - endDate: The end date of the current section public func currentCalendarSegment() -> (startDate: NSDate, endDate: NSDate)? { if monthInfo.count < 1 { return nil } let section = currentSectionPage let monthData = monthInfo[section] let itemLength = monthData[NUMBER_OF_DAYS_INDEX] let fdIndex = monthData[FIRST_DAY_INDEX] let startIndex = NSIndexPath(forItem: fdIndex, inSection: section) let endIndex = NSIndexPath(forItem: fdIndex + itemLength - 1, inSection: section) if let theStartDate = dateFromPath(startIndex), theEndDate = dateFromPath(endIndex) { return (theStartDate, theEndDate) } return nil } // MARK: Helper functions func cellWasNotDisabledByTheUser(cell: JTAppleDayCell) -> Bool { return cell.cellView.hidden == false && cell.cellView.userInteractionEnabled == true } } // MARK: scrollViewDelegates extension JTAppleCalendarView: UIScrollViewDelegate { /// Tells the delegate when the user finishes scrolling the content. public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if pagingEnabled { return } let cellDragInterval: CGFloat = (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).itemSize.width var contentOffset: CGFloat = 0, theTargetContentOffset: CGFloat = 0, directionVelocity: CGFloat = 0, contentInset: CGFloat = 0 if direction == .Horizontal { contentOffset = scrollView.contentOffset.x theTargetContentOffset = targetContentOffset.memory.x directionVelocity = velocity.x contentInset = calendarView.contentInset.left } else { contentOffset = scrollView.contentOffset.y theTargetContentOffset = targetContentOffset.memory.y directionVelocity = velocity.y contentInset = calendarView.contentInset.top } var nextIndex: CGFloat = 0 var diff = abs(theTargetContentOffset - contentOffset) if (directionVelocity == 0) { calendarView.collectionViewLayout.collectionViewContentSize().width nextIndex = round(theTargetContentOffset / cellDragInterval) targetContentOffset.memory = CGPointMake(0, nextIndex * cellDragInterval) } else if (directionVelocity > 0) { nextIndex = ceil((theTargetContentOffset - (diff * scrollResistance)) / cellDragInterval) } else { nextIndex = floor((theTargetContentOffset + (diff * scrollResistance)) / cellDragInterval) } if direction == .Horizontal { targetContentOffset.memory = CGPointMake(max(nextIndex * cellDragInterval, contentInset), 0) } else { targetContentOffset.memory = CGPointMake(0, max(nextIndex * cellDragInterval, contentInset)) } } /// Tells the delegate when a scrolling animation in the scroll view concludes. public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { scrollViewDidEndDecelerating(scrollView) delayedExecutionClosure?() delayedExecutionClosure = nil } /// Tells the delegate that the scroll view has ended decelerating the scrolling movement. public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // Determing the section from the scrollView direction let section = currentSectionPage // When ever the month/section is switched, let the flowlayout know which page it is on. This is needed in the event user switches orientatoin, we can use the index to snap back to correct position (calendarView.collectionViewLayout as! JTAppleCalendarLayoutProtocol).pathForFocusItem = NSIndexPath(forItem: 0, inSection: section) if let currentSegmentDates = currentCalendarSegment() { self.delegate?.calendar(self, didScrollToDateSegmentStartingWith: currentSegmentDates.startDate, endingWithDate: currentSegmentDates.endDate) } } } extension JTAppleCalendarView { private func cellStateFromIndexPath(indexPath: NSIndexPath)->CellState { let itemIndex = indexPath.item let itemSection = indexPath.section let currentMonthInfo = monthInfo[itemSection] let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let nDays = currentMonthInfo[NUMBER_OF_DAYS_INDEX] let offSet = currentMonthInfo[OFFSET_CALC] var cellText: String = "" var dateBelongsTo: CellState.DateOwner = .ThisMonth if itemIndex >= fdIndex && itemIndex < fdIndex + nDays { let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - fdIndex - offSet + 1 cellText = String(cellDate) dateBelongsTo = .ThisMonth } else if itemIndex < fdIndex && itemSection - 1 > -1 { // Prior month is available let startOfMonthSection = startMonthSectionForSection(itemSection - 1) let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - offSet + 1 let dateToAdd = monthInfo[startOfMonthSection][TOTAL_DAYS_IN_MONTH] let dateInt = cellDate + dateToAdd - monthInfo[itemSection][FIRST_DAY_INDEX] cellText = String(dateInt) dateBelongsTo = .PreviousMonthWithinBoundary } else if itemIndex >= fdIndex + nDays && itemSection + 1 < monthInfo.count { // Following months let startOfMonthSection = startMonthSectionForSection(itemSection) let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - offSet + 1 let dateToSubtract = monthInfo[startOfMonthSection][TOTAL_DAYS_IN_MONTH] let dateInt = cellDate - dateToSubtract - monthInfo[itemSection][FIRST_DAY_INDEX] cellText = String(dateInt) dateBelongsTo = .FollowingMonthWithinBoundary } else if itemIndex < fdIndex { // Pre from the start let cellDate = monthInfo[0][DATE_BOUNDRY] - monthInfo[0][FIRST_DAY_INDEX] + itemIndex + 1 cellText = String(cellDate ) dateBelongsTo = .PreviousMonthOutsideBoundary } else { // Post from the end let c = calendar!.component(.Day, fromDate: dateFromPath(indexPath)!) cellText = String(c) dateBelongsTo = .FollowingMonthOutsideBoundary } let cellState = CellState( isSelected: selectedIndexPaths.contains(indexPath), text: cellText, dateBelongsTo: dateBelongsTo ) return cellState } private func startMonthSectionForSection(aSection: Int)->Int { let monthIndexWeAreOn = aSection / numberOfSectionsPerMonth let nextSection = numberOfSectionsPerMonth * monthIndexWeAreOn return nextSection } private func dateFromPath(indexPath: NSIndexPath)-> NSDate? { // Returns nil if date is out of scope guard let validCachedCalendar = calendar else { return nil } let itemIndex = indexPath.item let itemSection = indexPath.section let monthIndexWeAreOn = itemSection / numberOfSectionsPerMonth let currentMonthInfo = monthInfo[itemSection] let fdIndex = currentMonthInfo[FIRST_DAY_INDEX] let offSet = currentMonthInfo[OFFSET_CALC] let cellDate = (numberOfRowsPerMonth * MAX_NUMBER_OF_DAYS_IN_WEEK * (itemSection % numberOfSectionsPerMonth)) + itemIndex - fdIndex - offSet + 1 let offsetComponents = NSDateComponents() offsetComponents.month = monthIndexWeAreOn offsetComponents.weekday = cellDate - 1 return validCachedCalendar.dateByAddingComponents(offsetComponents, toDate: startOfMonthCache, options: []) } private func delayRunOnMainThread(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } private func delayRunOnGlobalThread(delay:Double, qos: qos_class_t,closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_global_queue(qos, 0), closure) } } // MARK: CollectionView delegates extension JTAppleCalendarView: UICollectionViewDataSource, UICollectionViewDelegate { /// Asks your data source object for the cell that corresponds to the specified item in the collection view. public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if selectedIndexPaths.contains(indexPath) { collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) } else { collectionView.deselectItemAtIndexPath(indexPath, animated: false) } let dayCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! JTAppleDayCell let cellState = cellStateFromIndexPath(indexPath) let date = dateFromPath(indexPath)! delegate?.calendar(self, isAboutToDisplayCell: dayCell.cellView, date: date, cellState: cellState) return dayCell } /// Asks your data source object for the number of sections in the collection view. The number of sections in collectionView. public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { if !xibFileValid() { return 0 } if monthInfo.count > 0 { self.scrollViewDidEndDecelerating(self.calendarView) } return monthInfo.count } /// Asks your data source object for the number of items in the specified section. The number of rows in section. public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return MAX_NUMBER_OF_DAYS_IN_WEEK * numberOfRowsPerMonth } /// Asks the delegate if the specified item should be selected. true if the item should be selected or false if it should not. public func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { if let dateUserSelected = dateFromPath(indexPath), delegate = self.delegate, cell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell { if cellWasNotDisabledByTheUser(cell) { let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, canSelectDate: dateUserSelected, cell: cell.cellView, cellState: cellState) return true } } return false // if date is out of scope } /// Tells the delegate that the item at the specified path was deselected. The collection view calls this method when the user successfully deselects an item in the collection view. It does not call this method when you programmatically deselect items. public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if let delegate = self.delegate, dateSelectedByUser = dateFromPath(indexPath) { // Update model if let index = selectedIndexPaths.indexOf(indexPath) { selectedIndexPaths.removeAtIndex(index) selectedDates.removeAtIndex(index) } let selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell // Cell may be nil if user switches month sections let cellState = cellStateFromIndexPath(indexPath) // Although the cell may be nil, we still want to return the cellstate delegate.calendar(self, didDeselectDate: dateSelectedByUser, cell: selectedCell?.cellView, cellState: cellState) } } /// Asks the delegate if the specified item should be deselected. true if the item should be deselected or false if it should not. public func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool { if let dateUserSelected = dateFromPath(indexPath), delegate = self.delegate, cell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell { let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, canDeselectDate: dateUserSelected, cell: cell.cellView, cellState: cellState) return true } return false } /// Tells the delegate that the item at the specified index path was selected. The collection view calls this method when the user successfully selects an item in the collection view. It does not call this method when you programmatically set the selection. public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let delegate = self.delegate, dateSelectedByUser = dateFromPath(indexPath) { // Update model if selectedIndexPaths.contains(indexPath) == false { // wrapping in IF statement handles both multiple select scenarios AND singleselection scenarios selectedIndexPaths.append(indexPath) selectedDates.append(dateSelectedByUser) } let selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as? JTAppleDayCell let cellState = cellStateFromIndexPath(indexPath) delegate.calendar(self, didSelectDate: dateSelectedByUser, cell: selectedCell?.cellView, cellState: cellState) } } } extension JTAppleCalendarView: JTAppleCalendarDelegateProtocol { func numberOfRows() -> Int { return numberOfRowsPerMonth } func numberOfColumns() -> Int { return MAX_NUMBER_OF_DAYS_IN_WEEK } func numberOfsectionsPermonth() -> Int { return numberOfSectionsPerMonth } func numberOfSections() -> Int { return numberOfMonthSections } } /// NSDates can be compared with the == and != operators public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs === rhs || lhs.compare(rhs) == .OrderedSame } /// NSDates can be compared with the > and < operators public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } extension NSDate: Comparable { } private extension NSDate { class func numberOfDaysDifferenceBetweenFirstDate(firstDate: NSDate, secondDate: NSDate, usingCalendar calendar: NSCalendar)->Int { let date1 = calendar.startOfDayForDate(firstDate) let date2 = calendar.startOfDayForDate(secondDate) let flags = NSCalendarUnit.Day let components = calendar.components(flags, fromDate: date1, toDate: date2, options: .WrapComponents) return abs(components.day) } class func startOfMonthForDate(date: NSDate, usingCalendar calendar:NSCalendar) -> NSDate? { let dayOneComponents = calendar.components([.Era, .Year, .Month], fromDate: date) return calendar.dateFromComponents(dayOneComponents) } class func endOfMonthForDate(date: NSDate, usingCalendar calendar:NSCalendar) -> NSDate? { let lastDayComponents = calendar.components([NSCalendarUnit.Era, NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: date) lastDayComponents.month = lastDayComponents.month + 1 lastDayComponents.day = 0 return calendar.dateFromComponents(lastDayComponents) } }
/* 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 FirebaseRemoteConfig protocol EventsProviderDelegate: class { func eventsProvider(_ eventsProvider: EventsProvider, didUpdateEvents: [Event]) func eventsProvider(_ eventsProvider: EventsProvider, didError error: Error) } class EventsProvider { lazy var eventsDatabase: EventsDatabase = FirebaseEventsDatabase() private lazy var radius: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventSearchRadiusInKm) }() private lazy var eventStartNotificationInterval: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventStartNotificationInterval) * 60 }() private lazy var eventStartPlaceInterval: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventStartPlaceInterval) * 60 }() func getEventsForNotifications(forLocation location: CLLocation, completion: @escaping (([Event]?, Error?) -> Void)) { return eventsDatabase.getEvents(forLocation: location, withRadius: radius).upon { results in let events = results.flatMap { $0.successResult() }.filter { self.shouldShowEventForNotifications(event: $0, forLocation: location) } DispatchQueue.main.async { completion(events, nil) } } } func getEventsWithPlaces(forLocation location: CLLocation, usingPlacesDatabase placesDatabase: PlacesDatabase, completion: @escaping ([Place]) -> ()) { eventsDatabase.getPlacesWithEvents(forLocation: location, withRadius: radius, withPlacesDatabase: placesDatabase, filterEventsUsing: self.shouldShowEventForPlaces).upon { results in let places = results.flatMap { $0.successResult() } completion(places) } } private func shouldShowEventForNotifications(event: Event, forLocation location: CLLocation) -> Bool { return doesEvent(event: event, startAtCorrectTimeIntervalFromNow: eventStartNotificationInterval) } private func shouldShowEventForPlaces(event: Event, forLocation location: CLLocation) -> Bool { return isEventToday(event: event) && isEventYetToHappen(event: event) } private func doesEvent(event: Event, startAtCorrectTimeIntervalFromNow timeInterval: TimeInterval) -> Bool { // event must start in 1 hour let maxStartTime = Date().addingTimeInterval(timeInterval) return event.startTime <= maxStartTime } private func isEventToday(event: Event) -> Bool { return Calendar.current.isDateInToday(event.startTime) } private func isEventYetToHappen(event: Event) -> Bool { return Date() < event.startTime } } Fix time interval for calculating a future event /* 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 FirebaseRemoteConfig protocol EventsProviderDelegate: class { func eventsProvider(_ eventsProvider: EventsProvider, didUpdateEvents: [Event]) func eventsProvider(_ eventsProvider: EventsProvider, didError error: Error) } class EventsProvider { lazy var eventsDatabase: EventsDatabase = FirebaseEventsDatabase() private lazy var radius: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventSearchRadiusInKm) }() private lazy var eventStartNotificationInterval: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventStartNotificationInterval) * 60 }() private lazy var eventStartPlaceInterval: Double = { return RemoteConfigKeys.getDouble(forKey: RemoteConfigKeys.eventStartPlaceInterval) * 60 }() func getEventsForNotifications(forLocation location: CLLocation, completion: @escaping (([Event]?, Error?) -> Void)) { return eventsDatabase.getEvents(forLocation: location, withRadius: radius).upon { results in let events = results.flatMap { $0.successResult() }.filter { self.shouldShowEventForNotifications(event: $0, forLocation: location) } DispatchQueue.main.async { completion(events, nil) } } } func getEventsWithPlaces(forLocation location: CLLocation, usingPlacesDatabase placesDatabase: PlacesDatabase, completion: @escaping ([Place]) -> ()) { eventsDatabase.getPlacesWithEvents(forLocation: location, withRadius: radius, withPlacesDatabase: placesDatabase, filterEventsUsing: self.shouldShowEventForPlaces).upon { results in let places = results.flatMap { $0.successResult() } completion(places) } } private func shouldShowEventForNotifications(event: Event, forLocation location: CLLocation) -> Bool { return doesEvent(event: event, startAtCorrectTimeIntervalFromNow: eventStartNotificationInterval) } private func shouldShowEventForPlaces(event: Event, forLocation location: CLLocation) -> Bool { return isEventToday(event: event) && isEventYetToHappen(event: event) } private func doesEvent(event: Event, startAtCorrectTimeIntervalFromNow timeInterval: TimeInterval) -> Bool { // event must start in 1 hour let now = Date() let maxStartTime = now.addingTimeInterval(timeInterval) return event.startTime > now && event.startTime <= maxStartTime } private func isEventToday(event: Event) -> Bool { return Calendar.current.isDateInToday(event.startTime) } private func isEventYetToHappen(event: Event) -> Bool { return Date() < event.startTime } }
// // Nib.swift // R.swift // // Created by Mathijs Kadijk on 10-12-15. // Copyright © 2015 Mathijs Kadijk. All rights reserved. // import Foundation private let Ordinals = [ (number: 1, word: "first"), (number: 2, word: "second"), (number: 3, word: "third"), (number: 4, word: "fourth"), (number: 5, word: "fifth"), (number: 6, word: "sixth"), (number: 7, word: "seventh"), (number: 8, word: "eighth"), (number: 9, word: "ninth"), (number: 10, word: "tenth"), (number: 11, word: "eleventh"), (number: 12, word: "twelfth"), (number: 13, word: "thirteenth"), (number: 14, word: "fourteenth"), (number: 15, word: "fifteenth"), (number: 16, word: "sixteenth"), (number: 17, word: "seventeenth"), (number: 18, word: "eighteenth"), (number: 19, word: "nineteenth"), (number: 20, word: "twentieth"), ] struct NibGenerator: Generator { let externalStruct: Struct? let internalStruct: Struct? init(nibs: [Nib]) { let groupedNibs = nibs.groupUniquesAndDuplicates { sanitizedSwiftName($0.name) } for duplicate in groupedNibs.duplicates { let names = duplicate.map { $0.name }.sort().joinWithSeparator(", ") warn("Skipping \(duplicate.count) xibs because symbol '\(sanitizedSwiftName(duplicate.first!.name))' would be generated for all of these xibs: \(names)") } internalStruct = Struct( type: Type(module: .Host, name: "nib"), implements: [], typealiasses: [], properties: [], functions: [], structs: groupedNibs .uniques .map(NibGenerator.nibStructForNib) ) externalStruct = Struct( type: Type(module: .Host, name: "nib"), implements: [], typealiasses: [], properties: groupedNibs .uniques .map(NibGenerator.nibVarForNib), functions: groupedNibs .uniques .map(NibGenerator.nibFuncForNib), structs: [] ) } private static func nibFuncForNib(nib: Nib) -> Function { return Function( isStatic: true, name: nib.name, generics: nil, parameters: [ Function.Parameter(name: "_", type: Type._Void) ], doesThrow: false, returnType: Type._UINib, body: "return UINib(resource: R.nib.\(sanitizedSwiftName(nib.name)))" ) } private static func nibVarForNib(nib: Nib) -> Let { let nibStructName = sanitizedSwiftName("_\(nib.name)") let structType = Type(module: .Host, name: "_R.nib.\(nibStructName)") return Let(isStatic: true, name: nib.name, typeDefinition: .Inferred(structType), value: "\(structType)()") } private static func nibStructForNib(nib: Nib) -> Struct { let instantiateParameters = [ Function.Parameter(name: "owner", localName: "ownerOrNil", type: Type._AnyObject.asOptional()), Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(module: .StdLib, name: "[NSObject : AnyObject]", optional: true), defaultValue: "nil") ] let bundleLet: Property = Let( isStatic: false, name: "bundle", typeDefinition: .Inferred(Type._NSBundle), value: "_R.hostingBundle" ) let nameVar: Property = Let( isStatic: false, name: "name", typeDefinition: .Inferred(Type._String), value: "\"\(nib.name)\"" ) let viewFuncs = zip(nib.rootViews, Ordinals) .map { (view: $0.0, ordinal: $0.1) } .map { Function( isStatic: false, name: "\($0.ordinal.word)View", generics: nil, parameters: instantiateParameters, doesThrow: false, returnType: $0.view.asOptional(), body: "return instantiateWithOwner(ownerOrNil, options: optionsOrNil)[\($0.ordinal.number - 1)] as? \($0.view)" ) } let reuseIdentifierProperties: [Property] let reuseProtocols: [Type] let reuseTypealiasses: [Typealias] if let reusable = nib.reusables.first where nib.rootViews.count == 1 && nib.reusables.count == 1 { reuseIdentifierProperties = [Let( isStatic: false, name: "identifier", typeDefinition: .Inferred(Type._String), value: "\"\(reusable.identifier)\"" )] reuseTypealiasses = [Typealias(alias: "ReusableType", type: reusable.type)] reuseProtocols = [Type.ReuseIdentifierType] } else { reuseIdentifierProperties = [] reuseTypealiasses = [] reuseProtocols = [] } let sanitizedName = sanitizedSwiftName(nib.name, lowercaseFirstCharacter: false) return Struct( type: Type(module: .Host, name: "_\(sanitizedName)"), implements: ([Type.NibResourceType] + reuseProtocols).map(TypePrinter.init), typealiasses: reuseTypealiasses, properties: [bundleLet, nameVar] + reuseIdentifierProperties, functions: viewFuncs, structs: [] ) } } Improve compile time by about 7 seconds // // Nib.swift // R.swift // // Created by Mathijs Kadijk on 10-12-15. // Copyright © 2015 Mathijs Kadijk. All rights reserved. // import Foundation private let Ordinals = [ (number: 1, word: "first"), (number: 2, word: "second"), (number: 3, word: "third"), (number: 4, word: "fourth"), (number: 5, word: "fifth"), (number: 6, word: "sixth"), (number: 7, word: "seventh"), (number: 8, word: "eighth"), (number: 9, word: "ninth"), (number: 10, word: "tenth"), (number: 11, word: "eleventh"), (number: 12, word: "twelfth"), (number: 13, word: "thirteenth"), (number: 14, word: "fourteenth"), (number: 15, word: "fifteenth"), (number: 16, word: "sixteenth"), (number: 17, word: "seventeenth"), (number: 18, word: "eighteenth"), (number: 19, word: "nineteenth"), (number: 20, word: "twentieth"), ] struct NibGenerator: Generator { let externalStruct: Struct? let internalStruct: Struct? init(nibs: [Nib]) { let groupedNibs = nibs.groupUniquesAndDuplicates { sanitizedSwiftName($0.name) } for duplicate in groupedNibs.duplicates { let names = duplicate.map { $0.name }.sort().joinWithSeparator(", ") warn("Skipping \(duplicate.count) xibs because symbol '\(sanitizedSwiftName(duplicate.first!.name))' would be generated for all of these xibs: \(names)") } internalStruct = Struct( type: Type(module: .Host, name: "nib"), implements: [], typealiasses: [], properties: [], functions: [], structs: groupedNibs .uniques .map(NibGenerator.nibStructForNib) ) externalStruct = Struct( type: Type(module: .Host, name: "nib"), implements: [], typealiasses: [], properties: groupedNibs .uniques .map(NibGenerator.nibVarForNib), functions: groupedNibs .uniques .map(NibGenerator.nibFuncForNib), structs: [] ) } private static func nibFuncForNib(nib: Nib) -> Function { return Function( isStatic: true, name: nib.name, generics: nil, parameters: [ Function.Parameter(name: "_", type: Type._Void) ], doesThrow: false, returnType: Type._UINib, body: "return UINib(resource: R.nib.\(sanitizedSwiftName(nib.name)))" ) } private static func nibVarForNib(nib: Nib) -> Let { let nibStructName = sanitizedSwiftName("_\(nib.name)") let structType = Type(module: .Host, name: "_R.nib.\(nibStructName)") return Let(isStatic: true, name: nib.name, typeDefinition: .Inferred(structType), value: "\(structType)()") } private static func nibStructForNib(nib: Nib) -> Struct { let instantiateParameters = [ Function.Parameter(name: "owner", localName: "ownerOrNil", type: Type._AnyObject.asOptional()), Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(module: .StdLib, name: "[NSObject : AnyObject]", optional: true), defaultValue: "nil") ] let bundleLet: Property = Let( isStatic: false, name: "bundle", typeDefinition: .Inferred(Type._NSBundle), value: "_R.hostingBundle" ) let nameVar: Property = Let( isStatic: false, name: "name", typeDefinition: .Inferred(Type._String), value: "\"\(nib.name)\"" ) let viewFuncs = zip(nib.rootViews, Ordinals) .map { (view: $0.0, ordinal: $0.1) } .map { viewInfo -> Function in let viewIndex = viewInfo.ordinal.number - 1 let viewTypeString = viewInfo.view.description return Function( isStatic: false, name: "\(viewInfo.ordinal.word)View", generics: nil, parameters: instantiateParameters, doesThrow: false, returnType: viewInfo.view.asOptional(), body: "return instantiateWithOwner(ownerOrNil, options: optionsOrNil)[\(viewIndex)] as? \(viewTypeString)" ) } let reuseIdentifierProperties: [Property] let reuseProtocols: [Type] let reuseTypealiasses: [Typealias] if let reusable = nib.reusables.first where nib.rootViews.count == 1 && nib.reusables.count == 1 { reuseIdentifierProperties = [Let( isStatic: false, name: "identifier", typeDefinition: .Inferred(Type._String), value: "\"\(reusable.identifier)\"" )] reuseTypealiasses = [Typealias(alias: "ReusableType", type: reusable.type)] reuseProtocols = [Type.ReuseIdentifierType] } else { reuseIdentifierProperties = [] reuseTypealiasses = [] reuseProtocols = [] } let sanitizedName = sanitizedSwiftName(nib.name, lowercaseFirstCharacter: false) return Struct( type: Type(module: .Host, name: "_\(sanitizedName)"), implements: ([Type.NibResourceType] + reuseProtocols).map(TypePrinter.init), typealiasses: reuseTypealiasses, properties: [bundleLet, nameVar] + reuseIdentifierProperties, functions: viewFuncs, structs: [] ) } }
// // RuntimeChannelSpec.swift // Runtime // // Created by Paul Young on 24/08/2014. // Copyright (c) 2014 CocoaFlow. All rights reserved. // import Quick import Nimble import Runtime import JSONLib class RuntimeChannelSpec: QuickSpec { override func spec() { describe("Runtime channel") { describe("when receiving a message") { context("with an invalid topic") { it("should raise an exception") { let transport = FakeTransport() let runtime = Runtime(transport) expect { runtime.receive("runtime", "invalid", [:]) }.to(raiseException(named: "Invalid topic in message on runtime channel")) } } context("with a topic of getruntime") { it("should send a message to the transport with information about the runtime") { var messageChannel: String! var messageTopic: String! var messagePayload: JSON! let transport = FakeTransport { (channel, topic, payload) in messageChannel = channel messageTopic = topic messagePayload = payload } let runtime = Runtime(transport) runtime.receive("runtime", "getruntime", [:]) let expectedPayload: JSON = [ "type": "CocoaFlow", "version": 0.4, "capabilities": [], "id": "FIXME", "label": "Flow-based programming for Mac and iOS.", "graph": nil ] expect(messageChannel).to(equal("runtime")) expect(messageTopic).to(equal("runtime")) expect(messagePayload).to(equal(expectedPayload)) } } } } } } Fix expectation in spec. // // RuntimeChannelSpec.swift // Runtime // // Created by Paul Young on 24/08/2014. // Copyright (c) 2014 CocoaFlow. All rights reserved. // import Quick import Nimble import Runtime import JSONLib class RuntimeChannelSpec: QuickSpec { override func spec() { describe("Runtime channel") { describe("when receiving a message") { context("with an invalid topic") { it("should raise an exception") { let transport = FakeTransport() let runtime = Runtime(transport) expect { runtime.receive("runtime", "invalid", [:]) }.to(raiseException(named: "Invalid topic in message on runtime channel")) } } context("with a topic of getruntime") { it("should send a message to the transport with information about the runtime") { var messageChannel: String! var messageTopic: String! var messagePayload: JSON! let transport = FakeTransport { (channel, topic, payload) in messageChannel = channel messageTopic = topic messagePayload = payload } let runtime = Runtime(transport) runtime.receive("runtime", "getruntime", [:]) let expectedPayload: JSON = [ "type": "CocoaFlow", "version": 0.4, "capabilities": [], "id": "FIXME", "label": "Flow-based programming on Mac and iOS.", "graph": nil ] expect(messageChannel).to(equal("runtime")) expect(messageTopic).to(equal("runtime")) expect(messagePayload).to(equal(expectedPayload)) } } } } } }
// // EasyTipView.swift // // Copyright (c) 2015 Teodor Patraş // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if canImport(UIKit) import UIKit public protocol EasyTipViewDelegate : class { func easyTipViewDidTap(_ tipView: EasyTipView) func easyTipViewDidDismiss(_ tipView : EasyTipView) } // MARK: - Public methods extension public extension EasyTipView { // MARK:- Class methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: text, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, contentView: contentView, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(contentView: contentView, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview containing attributed text. - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter attributedText: The attributed text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, attributedText: NSAttributedString, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: attributedText, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } // MARK:- Instance methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forItem item: UIBarItem, withinSuperView superview: UIView? = nil) { if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil) { #if TARGET_APP_EXTENSIONS precondition(superview != nil, "The supplied superview parameter cannot be nil for app extensions.") let superview = superview! #else precondition(superview == nil || view.hasSuperview(superview!), "The supplied superview <\(superview!)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip within the main window, ignore the superview parameter.") let superview = superview ?? UIApplication.shared.windows.first! #endif let initialTransform = preferences.animating.showInitialTransform let finalTransform = preferences.animating.showFinalTransform let initialAlpha = preferences.animating.showInitialAlpha let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity presentingView = view arrange(withinSuperview: superview) transform = initialTransform alpha = initialAlpha let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) addGestureRecognizer(tap) superview.addSubview(self) let animations : () -> () = { self.transform = finalTransform self.alpha = 1 } if animated { UIView.animate(withDuration: preferences.animating.showDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: animations, completion: nil) }else{ animations() } } /** Dismisses the EasyTipView - parameter completion: Completion block to be executed after the EasyTipView is dismissed. */ func dismiss(withCompletion completion: (() -> ())? = nil){ let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity UIView.animate(withDuration: preferences.animating.dismissDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: { self.transform = self.preferences.animating.dismissTransform self.alpha = self.preferences.animating.dismissFinalAlpha }) { (finished) -> Void in completion?() self.delegate?.easyTipViewDidDismiss(self) self.removeFromSuperview() self.transform = CGAffineTransform.identity } } } // MARK: - EasyTipView class implementation - open class EasyTipView: UIView { // MARK:- Nested types - public enum ArrowPosition { case any case top case bottom case right case left static let allValues = [top, bottom, right, left] } public struct Preferences { public struct Drawing { public var cornerRadius = CGFloat(5) public var arrowHeight = CGFloat(5) public var arrowWidth = CGFloat(10) public var foregroundColor = UIColor.white public var backgroundColor = UIColor.red public var arrowPosition = ArrowPosition.any public var textAlignment = NSTextAlignment.center public var borderWidth = CGFloat(0) public var borderColor = UIColor.clear public var font = UIFont.systemFont(ofSize: 15) public var shadowColor = UIColor.clear public var shadowOffset = CGSize(width: 0.0, height: 0.0) public var shadowRadius = CGFloat(0) public var shadowOpacity = CGFloat(0) } public struct Positioning { public var bubbleHInset = CGFloat(1) public var bubbleVInset = CGFloat(1) public var contentHInset = CGFloat(10) public var contentVInset = CGFloat(10) public var maxWidth = CGFloat(200) } public struct Animating { public var dismissTransform = CGAffineTransform(scaleX: 0.1, y: 0.1) public var showInitialTransform = CGAffineTransform(scaleX: 0, y: 0) public var showFinalTransform = CGAffineTransform.identity public var springDamping = CGFloat(0.7) public var springVelocity = CGFloat(0.7) public var showInitialAlpha = CGFloat(0) public var dismissFinalAlpha = CGFloat(0) public var showDuration = 0.7 public var dismissDuration = 0.7 public var dismissOnTap = true } public var drawing = Drawing() public var positioning = Positioning() public var animating = Animating() public var hasBorder : Bool { return drawing.borderWidth > 0 && drawing.borderColor != UIColor.clear } public var hasShadow : Bool { return drawing.shadowOpacity > 0 && drawing.shadowColor != UIColor.clear } public init() {} } public enum Content: CustomStringConvertible { case text(String) case attributedText(NSAttributedString) case view(UIView) public var description: String { switch self { case .text(let text): return "text : '\(text)'" case .attributedText(let text): return "attributed text : '\(text)'" case .view(let contentView): return "view : \(contentView)" } } } // MARK:- Variables - override open var backgroundColor: UIColor? { didSet { guard let color = backgroundColor , color != UIColor.clear else {return} preferences.drawing.backgroundColor = color backgroundColor = UIColor.clear } } override open var description: String { let type = "'\(String(reflecting: Swift.type(of: self)))'".components(separatedBy: ".").last! return "<< \(type) with \(content) >>" } fileprivate weak var presentingView: UIView? fileprivate weak var delegate: EasyTipViewDelegate? fileprivate var arrowTip = CGPoint.zero fileprivate(set) open var preferences: Preferences private let content: Content // MARK: - Lazy variables - fileprivate lazy var contentSize: CGSize = { [unowned self] in switch content { case .text(let text): #if swift(>=4.2) var attributes = [NSAttributedString.Key.font : self.preferences.drawing.font] #else var attributes = [NSAttributedStringKey.font : self.preferences.drawing.font] #endif var textSize = text.boundingRect(with: CGSize(width: self.preferences.positioning.maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize case .attributedText(let text): var textSize = text.boundingRect(with: CGSize(width: self.preferences.positioning.maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize case .view(let contentView): return contentView.frame.size } }() fileprivate lazy var tipViewSize: CGSize = { [unowned self] in var tipViewSize = CGSize(width: self.contentSize.width + self.preferences.positioning.contentHInset * 2 + self.preferences.positioning.bubbleHInset * 2, height: self.contentSize.height + self.preferences.positioning.contentVInset * 2 + self.preferences.positioning.bubbleVInset * 2 + self.preferences.drawing.arrowHeight) return tipViewSize }() // MARK: - Static variables - public static var globalPreferences = Preferences() // MARK:- Initializer - public convenience init (text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .text(text), preferences: preferences, delegate: delegate) self.isAccessibilityElement = true self.accessibilityTraits = UIAccessibilityTraits.staticText self.accessibilityLabel = text } public convenience init (contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .view(contentView), preferences: preferences, delegate: delegate) } public convenience init (text: NSAttributedString, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .attributedText(text), preferences: preferences, delegate: delegate) } public init (content: Content, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.content = content self.preferences = preferences self.delegate = delegate super.init(frame: CGRect.zero) self.backgroundColor = UIColor.clear #if swift(>=4.2) let notificationName = UIDevice.orientationDidChangeNotification #else let notificationName = NSNotification.Name.UIDeviceOrientationDidChange #endif NotificationCenter.default.addObserver(self, selector: #selector(handleRotation), name: notificationName, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required public init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK: - Rotation support - @objc func handleRotation() { guard let sview = superview , presentingView != nil else { return } UIView.animate(withDuration: 0.3) { self.arrange(withinSuperview: sview) self.setNeedsDisplay() } } // MARK: - Private methods - fileprivate func computeFrame(arrowPosition position: ArrowPosition, refViewFrame: CGRect, superviewFrame: CGRect) -> CGRect { var xOrigin: CGFloat = 0 var yOrigin: CGFloat = 0 switch position { case .top, .any: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y + refViewFrame.height case .bottom: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y - tipViewSize.height case .right: xOrigin = refViewFrame.x - tipViewSize.width yOrigin = refViewFrame.center.y - tipViewSize.height / 2 case .left: xOrigin = refViewFrame.x + refViewFrame.width yOrigin = refViewFrame.center.y - tipViewSize.height / 2 } var frame = CGRect(x: xOrigin, y: yOrigin, width: tipViewSize.width, height: tipViewSize.height) adjustFrame(&frame, forSuperviewFrame: superviewFrame) return frame } fileprivate func adjustFrame(_ frame: inout CGRect, forSuperviewFrame superviewFrame: CGRect) { // adjust horizontally if frame.x < 0 { frame.x = 0 } else if frame.maxX > superviewFrame.width { frame.x = superviewFrame.width - frame.width } //adjust vertically if frame.y < 0 { frame.y = 0 } else if frame.maxY > superviewFrame.maxY { frame.y = superviewFrame.height - frame.height } } fileprivate func isFrameValid(_ frame: CGRect, forRefViewFrame: CGRect, withinSuperviewFrame: CGRect) -> Bool { return !frame.intersects(forRefViewFrame) } fileprivate func arrange(withinSuperview superview: UIView) { var position = preferences.drawing.arrowPosition let refViewFrame = presentingView!.convert(presentingView!.bounds, to: superview); let superviewFrame: CGRect if let scrollview = superview as? UIScrollView { superviewFrame = CGRect(origin: scrollview.frame.origin, size: scrollview.contentSize) } else { superviewFrame = superview.frame } var frame = computeFrame(arrowPosition: position, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if !isFrameValid(frame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { for value in ArrowPosition.allValues where value != position { let newFrame = computeFrame(arrowPosition: value, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if isFrameValid(newFrame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { if position != .any { print("[EasyTipView - Info] The arrow position you chose <\(position)> could not be applied. Instead, position <\(value)> has been applied! Please specify position <\(ArrowPosition.any)> if you want EasyTipView to choose a position for you.") } frame = newFrame position = value preferences.drawing.arrowPosition = value break } } } var arrowTipXOrigin: CGFloat switch position { case .bottom, .top, .any: if frame.width < refViewFrame.width { arrowTipXOrigin = tipViewSize.width / 2 } else { arrowTipXOrigin = abs(frame.x - refViewFrame.x) + refViewFrame.width / 2 } arrowTip = CGPoint(x: arrowTipXOrigin, y: position == .bottom ? tipViewSize.height - preferences.positioning.bubbleVInset : preferences.positioning.bubbleVInset) case .right, .left: if frame.height < refViewFrame.height { arrowTipXOrigin = tipViewSize.height / 2 } else { arrowTipXOrigin = abs(frame.y - refViewFrame.y) + refViewFrame.height / 2 } arrowTip = CGPoint(x: preferences.drawing.arrowPosition == .left ? preferences.positioning.bubbleVInset : tipViewSize.width - preferences.positioning.bubbleVInset, y: arrowTipXOrigin) } if case .view(let contentView) = content { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.frame = getContentRect(from: getBubbleFrame()) } self.frame = frame } // MARK:- Callbacks - @objc func handleTap() { self.delegate?.easyTipViewDidTap(self) guard preferences.animating.dismissOnTap else { return } dismiss() } // MARK:- Drawing - fileprivate func drawBubble(_ bubbleFrame: CGRect, arrowPosition: ArrowPosition, context: CGContext) { let arrowWidth = preferences.drawing.arrowWidth let arrowHeight = preferences.drawing.arrowHeight let cornerRadius = preferences.drawing.cornerRadius let contourPath = CGMutablePath() contourPath.move(to: CGPoint(x: arrowTip.x, y: arrowTip.y)) switch arrowPosition { case .bottom, .top, .any: contourPath.addLine(to: CGPoint(x: arrowTip.x - arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) if arrowPosition == .bottom { drawBubbleBottomShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleTopShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) case .right, .left: contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y - arrowWidth / 2)) if arrowPosition == .right { drawBubbleRightShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleLeftShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y + arrowWidth / 2)) } contourPath.closeSubpath() context.addPath(contourPath) context.clip() paintBubble(context) if preferences.hasBorder { drawBorder(contourPath, context: context) } } fileprivate func drawBubbleBottomShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) } fileprivate func drawBubbleTopShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func drawBubbleRightShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.height), radius: cornerRadius) } fileprivate func drawBubbleLeftShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func paintBubble(_ context: CGContext) { context.setFillColor(preferences.drawing.backgroundColor.cgColor) context.fill(bounds) } fileprivate func drawBorder(_ borderPath: CGPath, context: CGContext) { context.addPath(borderPath) context.setStrokeColor(preferences.drawing.borderColor.cgColor) context.setLineWidth(preferences.drawing.borderWidth) context.strokePath() } fileprivate func drawText(_ bubbleFrame: CGRect, context : CGContext) { guard case .text(let text) = content else { return } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = preferences.drawing.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping let textRect = getContentRect(from: bubbleFrame) #if swift(>=4.2) let attributes = [NSAttributedString.Key.font : preferences.drawing.font, NSAttributedString.Key.foregroundColor : preferences.drawing.foregroundColor, NSAttributedString.Key.paragraphStyle : paragraphStyle] #else let attributes = [NSAttributedStringKey.font : preferences.drawing.font, NSAttributedStringKey.foregroundColor : preferences.drawing.foregroundColor, NSAttributedStringKey.paragraphStyle : paragraphStyle] #endif text.draw(in: textRect, withAttributes: attributes) } fileprivate func drawAttributedText(_ bubbleFrame: CGRect, context : CGContext) { guard case .attributedText(let text) = content else { return } let textRect = getContentRect(from: bubbleFrame) text.draw(with: textRect, options: .usesLineFragmentOrigin, context: .none) } fileprivate func drawShadow() { if preferences.hasShadow { self.layer.masksToBounds = false self.layer.shadowColor = preferences.drawing.shadowColor.cgColor self.layer.shadowOffset = preferences.drawing.shadowOffset self.layer.shadowRadius = preferences.drawing.shadowRadius self.layer.shadowOpacity = Float(preferences.drawing.shadowOpacity) } } override open func draw(_ rect: CGRect) { let bubbleFrame = getBubbleFrame() let context = UIGraphicsGetCurrentContext()! context.saveGState () drawBubble(bubbleFrame, arrowPosition: preferences.drawing.arrowPosition, context: context) switch content { case .text: drawText(bubbleFrame, context: context) case .attributedText: drawAttributedText(bubbleFrame, context: context) case .view (let view): addSubview(view) } drawShadow() context.restoreGState() } private func getBubbleFrame() -> CGRect { let arrowPosition = preferences.drawing.arrowPosition let bubbleWidth: CGFloat let bubbleHeight: CGFloat let bubbleXOrigin: CGFloat let bubbleYOrigin: CGFloat switch arrowPosition { case .bottom, .top, .any: bubbleWidth = tipViewSize.width - 2 * preferences.positioning.bubbleHInset bubbleHeight = tipViewSize.height - 2 * preferences.positioning.bubbleVInset - preferences.drawing.arrowHeight bubbleXOrigin = preferences.positioning.bubbleHInset bubbleYOrigin = arrowPosition == .bottom ? preferences.positioning.bubbleVInset : preferences.positioning.bubbleVInset + preferences.drawing.arrowHeight case .left, .right: bubbleWidth = tipViewSize.width - 2 * preferences.positioning.bubbleHInset - preferences.drawing.arrowHeight bubbleHeight = tipViewSize.height - 2 * preferences.positioning.bubbleVInset bubbleXOrigin = arrowPosition == .right ? preferences.positioning.bubbleHInset : preferences.positioning.bubbleHInset + preferences.drawing.arrowHeight bubbleYOrigin = preferences.positioning.bubbleVInset } return CGRect(x: bubbleXOrigin, y: bubbleYOrigin, width: bubbleWidth, height: bubbleHeight) } private func getContentRect(from bubbleFrame: CGRect) -> CGRect { return CGRect(x: bubbleFrame.origin.x + (bubbleFrame.size.width - contentSize.width) / 2, y: bubbleFrame.origin.y + (bubbleFrame.size.height - contentSize.height) / 2, width: contentSize.width, height: contentSize.height) } } #endif Use UIEdgeInsets to set bubble/content insets (cherry picked from commit f7a00c58b1e61037310f60a037d443617c0b6118) // // EasyTipView.swift // // Copyright (c) 2015 Teodor Patraş // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if canImport(UIKit) import UIKit public protocol EasyTipViewDelegate : class { func easyTipViewDidTap(_ tipView: EasyTipView) func easyTipViewDidDismiss(_ tipView : EasyTipView) } // MARK: - Public methods extension public extension EasyTipView { // MARK:- Class methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: text, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, contentView: contentView, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(contentView: contentView, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview containing attributed text. - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter attributedText: The attributed text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, attributedText: NSAttributedString, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: attributedText, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } // MARK:- Instance methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forItem item: UIBarItem, withinSuperView superview: UIView? = nil) { if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil) { #if TARGET_APP_EXTENSIONS precondition(superview != nil, "The supplied superview parameter cannot be nil for app extensions.") let superview = superview! #else precondition(superview == nil || view.hasSuperview(superview!), "The supplied superview <\(superview!)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip within the main window, ignore the superview parameter.") let superview = superview ?? UIApplication.shared.windows.first! #endif let initialTransform = preferences.animating.showInitialTransform let finalTransform = preferences.animating.showFinalTransform let initialAlpha = preferences.animating.showInitialAlpha let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity presentingView = view arrange(withinSuperview: superview) transform = initialTransform alpha = initialAlpha let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) addGestureRecognizer(tap) superview.addSubview(self) let animations : () -> () = { self.transform = finalTransform self.alpha = 1 } if animated { UIView.animate(withDuration: preferences.animating.showDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: animations, completion: nil) }else{ animations() } } /** Dismisses the EasyTipView - parameter completion: Completion block to be executed after the EasyTipView is dismissed. */ func dismiss(withCompletion completion: (() -> ())? = nil){ let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity UIView.animate(withDuration: preferences.animating.dismissDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: { self.transform = self.preferences.animating.dismissTransform self.alpha = self.preferences.animating.dismissFinalAlpha }) { (finished) -> Void in completion?() self.delegate?.easyTipViewDidDismiss(self) self.removeFromSuperview() self.transform = CGAffineTransform.identity } } } // MARK: - EasyTipView class implementation - open class EasyTipView: UIView { // MARK:- Nested types - public enum ArrowPosition { case any case top case bottom case right case left static let allValues = [top, bottom, right, left] } public struct Preferences { public struct Drawing { public var cornerRadius = CGFloat(5) public var arrowHeight = CGFloat(5) public var arrowWidth = CGFloat(10) public var foregroundColor = UIColor.white public var backgroundColor = UIColor.red public var arrowPosition = ArrowPosition.any public var textAlignment = NSTextAlignment.center public var borderWidth = CGFloat(0) public var borderColor = UIColor.clear public var font = UIFont.systemFont(ofSize: 15) public var shadowColor = UIColor.clear public var shadowOffset = CGSize(width: 0.0, height: 0.0) public var shadowRadius = CGFloat(0) public var shadowOpacity = CGFloat(0) } public struct Positioning { public var bubbleInsets = UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0) public var contentInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) public var maxWidth = CGFloat(200) } public struct Animating { public var dismissTransform = CGAffineTransform(scaleX: 0.1, y: 0.1) public var showInitialTransform = CGAffineTransform(scaleX: 0, y: 0) public var showFinalTransform = CGAffineTransform.identity public var springDamping = CGFloat(0.7) public var springVelocity = CGFloat(0.7) public var showInitialAlpha = CGFloat(0) public var dismissFinalAlpha = CGFloat(0) public var showDuration = 0.7 public var dismissDuration = 0.7 public var dismissOnTap = true } public var drawing = Drawing() public var positioning = Positioning() public var animating = Animating() public var hasBorder : Bool { return drawing.borderWidth > 0 && drawing.borderColor != UIColor.clear } public var hasShadow : Bool { return drawing.shadowOpacity > 0 && drawing.shadowColor != UIColor.clear } public init() {} } public enum Content: CustomStringConvertible { case text(String) case attributedText(NSAttributedString) case view(UIView) public var description: String { switch self { case .text(let text): return "text : '\(text)'" case .attributedText(let text): return "attributed text : '\(text)'" case .view(let contentView): return "view : \(contentView)" } } } // MARK:- Variables - override open var backgroundColor: UIColor? { didSet { guard let color = backgroundColor , color != UIColor.clear else {return} preferences.drawing.backgroundColor = color backgroundColor = UIColor.clear } } override open var description: String { let type = "'\(String(reflecting: Swift.type(of: self)))'".components(separatedBy: ".").last! return "<< \(type) with \(content) >>" } fileprivate weak var presentingView: UIView? fileprivate weak var delegate: EasyTipViewDelegate? fileprivate var arrowTip = CGPoint.zero fileprivate(set) open var preferences: Preferences private let content: Content // MARK: - Lazy variables - fileprivate lazy var contentSize: CGSize = { [unowned self] in switch content { case .text(let text): #if swift(>=4.2) var attributes = [NSAttributedString.Key.font : self.preferences.drawing.font] #else var attributes = [NSAttributedStringKey.font : self.preferences.drawing.font] #endif var textSize = text.boundingRect(with: CGSize(width: self.preferences.positioning.maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize case .attributedText(let text): var textSize = text.boundingRect(with: CGSize(width: self.preferences.positioning.maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize case .view(let contentView): return contentView.frame.size } }() fileprivate lazy var tipViewSize: CGSize = { [unowned self] in let contentHInset = self.preferences.positioning.contentInsets.left + self.preferences.positioning.contentInsets.right let contentVInset = self.preferences.positioning.contentInsets.top + self.preferences.positioning.contentInsets.bottom let bubbleHInset = self.preferences.positioning.bubbleInsets.left + self.preferences.positioning.bubbleInsets.right let bubbleVInset = self.preferences.positioning.bubbleInsets.top + self.preferences.positioning.bubbleInsets.bottom var tipViewSize = CGSize(width: self.contentSize.width + contentHInset + bubbleHInset, height: self.contentSize.height + contentVInset + bubbleVInset + self.preferences.drawing.arrowHeight) return tipViewSize }() // MARK: - Static variables - public static var globalPreferences = Preferences() // MARK:- Initializer - public convenience init (text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .text(text), preferences: preferences, delegate: delegate) self.isAccessibilityElement = true self.accessibilityTraits = UIAccessibilityTraits.staticText self.accessibilityLabel = text } public convenience init (contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .view(contentView), preferences: preferences, delegate: delegate) } public convenience init (text: NSAttributedString, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .attributedText(text), preferences: preferences, delegate: delegate) } public init (content: Content, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.content = content self.preferences = preferences self.delegate = delegate super.init(frame: CGRect.zero) self.backgroundColor = UIColor.clear #if swift(>=4.2) let notificationName = UIDevice.orientationDidChangeNotification #else let notificationName = NSNotification.Name.UIDeviceOrientationDidChange #endif NotificationCenter.default.addObserver(self, selector: #selector(handleRotation), name: notificationName, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required public init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK: - Rotation support - @objc func handleRotation() { guard let sview = superview , presentingView != nil else { return } UIView.animate(withDuration: 0.3) { self.arrange(withinSuperview: sview) self.setNeedsDisplay() } } // MARK: - Private methods - fileprivate func computeFrame(arrowPosition position: ArrowPosition, refViewFrame: CGRect, superviewFrame: CGRect) -> CGRect { var xOrigin: CGFloat = 0 var yOrigin: CGFloat = 0 switch position { case .top, .any: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y + refViewFrame.height case .bottom: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y - tipViewSize.height case .right: xOrigin = refViewFrame.x - tipViewSize.width yOrigin = refViewFrame.center.y - tipViewSize.height / 2 case .left: xOrigin = refViewFrame.x + refViewFrame.width yOrigin = refViewFrame.center.y - tipViewSize.height / 2 } var frame = CGRect(x: xOrigin, y: yOrigin, width: tipViewSize.width, height: tipViewSize.height) adjustFrame(&frame, forSuperviewFrame: superviewFrame) return frame } fileprivate func adjustFrame(_ frame: inout CGRect, forSuperviewFrame superviewFrame: CGRect) { // adjust horizontally if frame.x < 0 { frame.x = 0 } else if frame.maxX > superviewFrame.width { frame.x = superviewFrame.width - frame.width } //adjust vertically if frame.y < 0 { frame.y = 0 } else if frame.maxY > superviewFrame.maxY { frame.y = superviewFrame.height - frame.height } } fileprivate func isFrameValid(_ frame: CGRect, forRefViewFrame: CGRect, withinSuperviewFrame: CGRect) -> Bool { return !frame.intersects(forRefViewFrame) } fileprivate func arrange(withinSuperview superview: UIView) { var position = preferences.drawing.arrowPosition let refViewFrame = presentingView!.convert(presentingView!.bounds, to: superview); let superviewFrame: CGRect if let scrollview = superview as? UIScrollView { superviewFrame = CGRect(origin: scrollview.frame.origin, size: scrollview.contentSize) } else { superviewFrame = superview.frame } var frame = computeFrame(arrowPosition: position, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if !isFrameValid(frame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { for value in ArrowPosition.allValues where value != position { let newFrame = computeFrame(arrowPosition: value, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if isFrameValid(newFrame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { if position != .any { print("[EasyTipView - Info] The arrow position you chose <\(position)> could not be applied. Instead, position <\(value)> has been applied! Please specify position <\(ArrowPosition.any)> if you want EasyTipView to choose a position for you.") } frame = newFrame position = value preferences.drawing.arrowPosition = value break } } } switch position { case .bottom, .top, .any: var arrowTipXOrigin: CGFloat if frame.width < refViewFrame.width { arrowTipXOrigin = tipViewSize.width / 2 } else { arrowTipXOrigin = abs(frame.x - refViewFrame.x) + refViewFrame.width / 2 } arrowTip = CGPoint(x: arrowTipXOrigin, y: position == .bottom ? tipViewSize.height - preferences.positioning.bubbleInsets.bottom : preferences.positioning.bubbleInsets.top) case .right, .left: var arrowTipYOrigin: CGFloat if frame.height < refViewFrame.height { arrowTipYOrigin = tipViewSize.height / 2 } else { arrowTipYOrigin = abs(frame.y - refViewFrame.y) + refViewFrame.height / 2 } arrowTip = CGPoint(x: preferences.drawing.arrowPosition == .left ? preferences.positioning.bubbleInsets.left : tipViewSize.width - preferences.positioning.bubbleInsets.right, y: arrowTipYOrigin) } if case .view(let contentView) = content { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.frame = getContentRect(from: getBubbleFrame()) } self.frame = frame } // MARK:- Callbacks - @objc func handleTap() { self.delegate?.easyTipViewDidTap(self) guard preferences.animating.dismissOnTap else { return } dismiss() } // MARK:- Drawing - fileprivate func drawBubble(_ bubbleFrame: CGRect, arrowPosition: ArrowPosition, context: CGContext) { let arrowWidth = preferences.drawing.arrowWidth let arrowHeight = preferences.drawing.arrowHeight let cornerRadius = preferences.drawing.cornerRadius let contourPath = CGMutablePath() contourPath.move(to: CGPoint(x: arrowTip.x, y: arrowTip.y)) switch arrowPosition { case .bottom, .top, .any: contourPath.addLine(to: CGPoint(x: arrowTip.x - arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) if arrowPosition == .bottom { drawBubbleBottomShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleTopShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) case .right, .left: contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y - arrowWidth / 2)) if arrowPosition == .right { drawBubbleRightShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleLeftShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y + arrowWidth / 2)) } contourPath.closeSubpath() context.addPath(contourPath) context.clip() paintBubble(context) if preferences.hasBorder { drawBorder(contourPath, context: context) } } fileprivate func drawBubbleBottomShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) } fileprivate func drawBubbleTopShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func drawBubbleRightShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.height), radius: cornerRadius) } fileprivate func drawBubbleLeftShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func paintBubble(_ context: CGContext) { context.setFillColor(preferences.drawing.backgroundColor.cgColor) context.fill(bounds) } fileprivate func drawBorder(_ borderPath: CGPath, context: CGContext) { context.addPath(borderPath) context.setStrokeColor(preferences.drawing.borderColor.cgColor) context.setLineWidth(preferences.drawing.borderWidth) context.strokePath() } fileprivate func drawText(_ bubbleFrame: CGRect, context : CGContext) { guard case .text(let text) = content else { return } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = preferences.drawing.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping let textRect = getContentRect(from: bubbleFrame) #if swift(>=4.2) let attributes = [NSAttributedString.Key.font : preferences.drawing.font, NSAttributedString.Key.foregroundColor : preferences.drawing.foregroundColor, NSAttributedString.Key.paragraphStyle : paragraphStyle] #else let attributes = [NSAttributedStringKey.font : preferences.drawing.font, NSAttributedStringKey.foregroundColor : preferences.drawing.foregroundColor, NSAttributedStringKey.paragraphStyle : paragraphStyle] #endif text.draw(in: textRect, withAttributes: attributes) } fileprivate func drawAttributedText(_ bubbleFrame: CGRect, context : CGContext) { guard case .attributedText(let text) = content else { return } let textRect = getContentRect(from: bubbleFrame) text.draw(with: textRect, options: .usesLineFragmentOrigin, context: .none) } fileprivate func drawShadow() { if preferences.hasShadow { self.layer.masksToBounds = false self.layer.shadowColor = preferences.drawing.shadowColor.cgColor self.layer.shadowOffset = preferences.drawing.shadowOffset self.layer.shadowRadius = preferences.drawing.shadowRadius self.layer.shadowOpacity = Float(preferences.drawing.shadowOpacity) } } override open func draw(_ rect: CGRect) { let bubbleFrame = getBubbleFrame() let context = UIGraphicsGetCurrentContext()! context.saveGState () drawBubble(bubbleFrame, arrowPosition: preferences.drawing.arrowPosition, context: context) switch content { case .text: drawText(bubbleFrame, context: context) case .attributedText: drawAttributedText(bubbleFrame, context: context) case .view (let view): addSubview(view) } drawShadow() context.restoreGState() } private func getBubbleFrame() -> CGRect { let arrowPosition = preferences.drawing.arrowPosition let bubbleWidth: CGFloat let bubbleHeight: CGFloat let bubbleXOrigin: CGFloat let bubbleYOrigin: CGFloat switch arrowPosition { case .bottom, .top, .any: bubbleWidth = tipViewSize.width - preferences.positioning.bubbleInsets.left - preferences.positioning.bubbleInsets.right bubbleHeight = tipViewSize.height - preferences.positioning.bubbleInsets.top - preferences.positioning.bubbleInsets.bottom - preferences.drawing.arrowHeight bubbleXOrigin = preferences.positioning.bubbleInsets.left bubbleYOrigin = arrowPosition == .bottom ? preferences.positioning.bubbleInsets.top : preferences.positioning.bubbleInsets.top + preferences.drawing.arrowHeight case .left, .right: bubbleWidth = tipViewSize.width - preferences.positioning.bubbleInsets.left - preferences.positioning.bubbleInsets.right - preferences.drawing.arrowHeight bubbleHeight = tipViewSize.height - preferences.positioning.bubbleInsets.top - preferences.positioning.bubbleInsets.left bubbleXOrigin = arrowPosition == .right ? preferences.positioning.bubbleInsets.left : preferences.positioning.bubbleInsets.left + preferences.drawing.arrowHeight bubbleYOrigin = preferences.positioning.bubbleInsets.top } return CGRect(x: bubbleXOrigin, y: bubbleYOrigin, width: bubbleWidth, height: bubbleHeight) } private func getContentRect(from bubbleFrame: CGRect) -> CGRect { return CGRect(x: bubbleFrame.origin.x + (bubbleFrame.size.width - contentSize.width) / 2, y: bubbleFrame.origin.y + (bubbleFrame.size.height - contentSize.height) / 2, width: contentSize.width, height: contentSize.height) } } #endif
// // MustacheParser3.swift // Noze.io // // Created by Helge Heß on 6/1/16. // Copyright © 2016-2021 ZeeZide GmbH. All rights reserved. // public struct MustacheParser { public init() {} enum MustacheToken { case Text(String) case Tag(String) case UnescapedTag(String) case SectionStart(String) case InvertedSectionStart(String) case SectionEnd(String) case Partial(String) } private var start : UnsafePointer<CChar>? = nil private var p : UnsafePointer<CChar>? = nil private var cStart : CChar = 123 // { private var cEnd : CChar = 125 // } private let sStart : CChar = 35 // # private let isStart : CChar = 94 // ^ private let sEnd : CChar = 47 // / private let ueStart : CChar = 38 // & private let pStart : CChar = 62 // > public var openCharacter : Character { set { let s = String(newValue).unicodeScalars cStart = CChar(s[s.startIndex].value) } get { return Character(UnicodeScalar(UInt32(cStart))!) } } public var closeCharacter : Character { set { let s = String(newValue).unicodeScalars cEnd = CChar(s[s.startIndex].value) } get { return Character(UnicodeScalar(UInt32(cEnd))!) } } // MARK: - Client Funcs @inlinable public mutating func parse(string s: String) -> MustacheNode { return s.withCString { cs in parse(cstr: cs) } } public mutating func parse(cstr cs: UnsafePointer<CChar>) -> MustacheNode { if cs.pointee == 0 { return .empty } start = cs p = start guard let nodes = parseNodes() else { return .empty } return .global(nodes) } // MARK: - Parsing private mutating func parseNodes(section s: String? = nil) -> [ MustacheNode ]? { if p != nil && p!.pointee == 0 { return nil } var nodes = [ MustacheNode ]() while let node = parseNode(sectionEnd: s) { switch node { case .empty: continue default: break } nodes.append(node) } return nodes } private mutating func parseNode(sectionEnd se: String? = nil) -> MustacheNode? { guard let token = parseTagOrText() else { return nil } switch token { case .Text (let s): return .text(s) case .Tag (let s): return .tag(s) case .UnescapedTag(let s): return .unescapedTag(s) case .Partial (let s): return .partial(s) case .SectionStart(let s): guard let children = parseNodes(section: s) else { return .empty } return .section(s, children) case .InvertedSectionStart(let s): guard let children = parseNodes(section: s) else { return .empty } return .invertedSection(s, children) case .SectionEnd(let s): if !s.isEmpty && s != se { print("section tags not balanced: \(s) expected \(se as Optional)") } return nil } } // MARK: - Lexing mutating private func parseTagOrText() -> MustacheToken? { guard p != nil && p!.pointee != 0 else { return nil } if p!.pointee == cStart && la1 == cStart { return parseTag() } else { return .Text(parseText()) } } mutating private func parseTag() -> MustacheToken { guard p != nil else { return .Text("") } guard p!.pointee == cStart && la1 == cStart else { return .Text("") } let isUnescaped = la2 == cStart let start = p! p = p! + (isUnescaped ? 3 : 2) // skip {{ let marker = p! while p!.pointee != 0 { if p!.pointee == cEnd && la1 == cEnd && (!isUnescaped || la2 == cEnd) { // found end let len = p! - marker if isUnescaped { p = p! + 3 // skip }}} let s = String.fromCString(marker, length: len)! return .UnescapedTag(s) } p = p! + 2 // skip }} let typec = marker.pointee switch typec { case sStart: // # let s = String.fromCString(marker + 1, length: len - 1)! return .SectionStart(s) case isStart: // ^ let s = String.fromCString(marker + 1, length: len - 1)! return .InvertedSectionStart(s) case sEnd: // / let s = String.fromCString(marker + 1, length: len - 1)! return .SectionEnd(s) case pStart: // > var n = marker + 1 // skip > while n.pointee == 32 { n += 1 } // skip spaces let len = p! - n - 2 let s = String.fromCString(n, length: len)! return .Partial(s) case ueStart /* & */: if (marker + 1).pointee == 32 { let s = String.fromCString(marker + 2, length: len - 2)! return .UnescapedTag(s) } fallthrough default: let s = String.fromCString(marker, length: len)! return .Tag(s) } } p = p! + 1 } return .Text(String(cString: start)) } mutating private func parseText() -> String { assert(p != nil) let start = p! while p!.pointee != 0 { if p!.pointee == cStart && la1 == cStart { return String.fromCString(start, length: p! - start)! } p = p! + 1 } return String(cString: start) } private var la0 : CChar { return p != nil ? p!.pointee : 0 } private var la1 : CChar { return la0 != 0 ? (p! + 1).pointee : 0 } private var la2 : CChar { return la1 != 0 ? (p! + 2).pointee : 0 } } #if os(Linux) import func Glibc.memcpy #else import func Darwin.memcpy #endif fileprivate extension String { static func fromCString(_ cs: UnsafePointer<CChar>, length olength: Int?) -> String? { guard let length = olength else { // no length given, use \0 std imp return String(validatingUTF8: cs) } let buflen = length + 1 let buf = UnsafeMutablePointer<CChar>.allocate(capacity: buflen) memcpy(buf, cs, length) buf[length] = 0 // zero terminate let s = String(validatingUTF8: buf) #if swift(>=4.1) buf.deallocate() #else buf.deallocate(capacity: buflen) #endif return s } } Lowercase cases in internal token enum ... // // MustacheParser3.swift // Noze.io // // Created by Helge Heß on 6/1/16. // Copyright © 2016-2021 ZeeZide GmbH. All rights reserved. // public struct MustacheParser { public init() {} private enum MustacheToken { case text (String) case tag (String) case unescapedTag (String) case sectionStart (String) case invertedSectionStart(String) case sectionEnd (String) case partial (String) } private var start : UnsafePointer<CChar>? = nil private var p : UnsafePointer<CChar>? = nil private var cStart : CChar = 123 // { private var cEnd : CChar = 125 // } private let sStart : CChar = 35 // # private let isStart : CChar = 94 // ^ private let sEnd : CChar = 47 // / private let ueStart : CChar = 38 // & private let pStart : CChar = 62 // > public var openCharacter : Character { set { let s = String(newValue).unicodeScalars cStart = CChar(s[s.startIndex].value) } get { return Character(UnicodeScalar(UInt32(cStart))!) } } public var closeCharacter : Character { set { let s = String(newValue).unicodeScalars cEnd = CChar(s[s.startIndex].value) } get { return Character(UnicodeScalar(UInt32(cEnd))!) } } // MARK: - Client Funcs @inlinable public mutating func parse(string s: String) -> MustacheNode { return s.withCString { cs in parse(cstr: cs) } } public mutating func parse(cstr cs: UnsafePointer<CChar>) -> MustacheNode { if cs.pointee == 0 { return .empty } start = cs p = start guard let nodes = parseNodes() else { return .empty } return .global(nodes) } // MARK: - Parsing private mutating func parseNodes(section s: String? = nil) -> [ MustacheNode ]? { if p != nil && p!.pointee == 0 { return nil } var nodes = [ MustacheNode ]() while let node = parseNode(sectionEnd: s) { switch node { case .empty: continue default: break } nodes.append(node) } return nodes } private mutating func parseNode(sectionEnd se: String? = nil) -> MustacheNode? { guard let token = parseTagOrText() else { return nil } switch token { case .text (let s): return .text(s) case .tag (let s): return .tag(s) case .unescapedTag(let s): return .unescapedTag(s) case .partial (let s): return .partial(s) case .sectionStart(let s): guard let children = parseNodes(section: s) else { return .empty } return .section(s, children) case .invertedSectionStart(let s): guard let children = parseNodes(section: s) else { return .empty } return .invertedSection(s, children) case .sectionEnd(let s): if !s.isEmpty && s != se { print("section tags not balanced: \(s) expected \(se as Optional)") } return nil } } // MARK: - Lexing mutating private func parseTagOrText() -> MustacheToken? { guard p != nil && p!.pointee != 0 else { return nil } if p!.pointee == cStart && la1 == cStart { return parseTag() } else { return .text(parseText()) } } mutating private func parseTag() -> MustacheToken { guard p != nil else { return .text("") } guard p!.pointee == cStart && la1 == cStart else { return .text("") } let isUnescaped = la2 == cStart let start = p! p = p! + (isUnescaped ? 3 : 2) // skip {{ let marker = p! while p!.pointee != 0 { if p!.pointee == cEnd && la1 == cEnd && (!isUnescaped || la2 == cEnd) { // found end let len = p! - marker if isUnescaped { p = p! + 3 // skip }}} let s = String.fromCString(marker, length: len)! return .unescapedTag(s) } p = p! + 2 // skip }} let typec = marker.pointee switch typec { case sStart: // # let s = String.fromCString(marker + 1, length: len - 1)! return .sectionStart(s) case isStart: // ^ let s = String.fromCString(marker + 1, length: len - 1)! return .invertedSectionStart(s) case sEnd: // / let s = String.fromCString(marker + 1, length: len - 1)! return .sectionEnd(s) case pStart: // > var n = marker + 1 // skip > while n.pointee == 32 { n += 1 } // skip spaces let len = p! - n - 2 let s = String.fromCString(n, length: len)! return .partial(s) case ueStart /* & */: if (marker + 1).pointee == 32 { let s = String.fromCString(marker + 2, length: len - 2)! return .unescapedTag(s) } fallthrough default: let s = String.fromCString(marker, length: len)! return .tag(s) } } p = p! + 1 } return .text(String(cString: start)) } mutating private func parseText() -> String { assert(p != nil) let start = p! while p!.pointee != 0 { if p!.pointee == cStart && la1 == cStart { return String.fromCString(start, length: p! - start)! } p = p! + 1 } return String(cString: start) } private var la0 : CChar { return p != nil ? p!.pointee : 0 } private var la1 : CChar { return la0 != 0 ? (p! + 1).pointee : 0 } private var la2 : CChar { return la1 != 0 ? (p! + 2).pointee : 0 } } #if os(Linux) import func Glibc.memcpy #else import func Darwin.memcpy #endif fileprivate extension String { static func fromCString(_ cs: UnsafePointer<CChar>, length olength: Int?) -> String? { guard let length = olength else { // no length given, use \0 std imp return String(validatingUTF8: cs) } let buflen = length + 1 let buf = UnsafeMutablePointer<CChar>.allocate(capacity: buflen) memcpy(buf, cs, length) buf[length] = 0 // zero terminate let s = String(validatingUTF8: buf) #if swift(>=4.1) buf.deallocate() #else buf.deallocate(capacity: buflen) #endif return s } }
// Scraped from http://www.freeformatter.com/mime-types-list.html let mediaTypes = [ "aw": "application/applixware", // Applixware Vistasource "atom": "application/atom+xml", // Atom Syndication Format RFC 4287 "atomcat": "application/atomcat+xml", // Atom Publishing Protocol RFC 5023 "atomsvc": "application/atomsvc+xml", // Atom Publishing Protocol Service Document RFC 5023 "ccxml": "application/ccxml+xml", // Voice Browser Call Control Voice Browser Call Control: CCXML Version 1.0 "cdmia": "application/cdmi-capability", // Cloud Data Management Interface (CDMI) - Capability RFC 6208 "cdmic": "application/cdmi-container", // Cloud Data Management Interface (CDMI) - Contaimer RFC 6209 "cdmid": "application/cdmi-domain", // Cloud Data Management Interface (CDMI) - Domain RFC 6210 "cdmio": "application/cdmi-object", // Cloud Data Management Interface (CDMI) - Object RFC 6211 "cdmiq": "application/cdmi-queue", // Cloud Data Management Interface (CDMI) - Queue RFC 6212 "cu": "application/cu-seeme", // CU-SeeMe White Pine "davmount": "application/davmount+xml", // Web Distributed Authoring and Versioning RFC 4918 "dssc": "application/dssc+der", // Data Structure for the Security Suitability of Cryptographic Algorithms RFC 5698 "xdssc": "application/dssc+xml", // Data Structure for the Security Suitability of Cryptographic Algorithms RFC 5698 "es": "application/ecmascript", // ECMAScript ECMA-357 "emma": "application/emma+xml", // Extensible MultiModal Annotation EMMA: Extensible MultiModal Annotation markup languageWikipedia: EPUB "exi": "application/exi", // Efficient XML Interchange Efficient XML Interchange (EXI) Best Practices "pfr": "application/font-tdpfr", // Portable Font Resource RFC 3073 "stk": "application/hyperstudio", // Hyperstudio IANA - Hyperstudio "ipfix": "application/ipfix", // Internet Protocol Flow Information Export RFC 3917 "jar": "application/java-archive", // Java Archive Wikipedia: JAR file format "ser": "application/java-serialized-object", // Java Serialized Object Java Serialization API "class": "application/java-vm", // Java Bytecode File Wikipedia: Java Bytecode "js": "application/javascript", // JavaScript JavaScript "json": "application/json", // JavaScript Object Notation (JSON) Wikipedia: JSON "hqx": "application/mac-binhex40", // Macintosh BinHex 4.0 MacMIME "cpt": "application/mac-compactpro", // Compact Pro Compact Pro "mads": "application/mads+xml", // Metadata Authority Description Schema RFC 6207 "mrc": "application/marc", // MARC Formats RFC 2220 "mrcx": "application/marcxml+xml", // MARC21 XML Schema RFC 6207 "ma": "application/mathematica", // Mathematica Notebooks IANA - Mathematica "mathml": "application/mathml+xml", // Mathematical Markup Language W3C Math Home "mbox": "application/mbox", // Mbox database files RFC 4155 "mscml": "application/mediaservercontrol+xml", // Media Server Control Markup Language RFC 5022 "meta4": "application/metalink4+xml", // Metalink Wikipedia: Metalink "mets": "application/mets+xml", // Metadata Encoding and Transmission Standard RFC 6207 "mods": "application/mods+xml", // Metadata Object Description Schema RFC 6207 "m21": "application/mp21", // MPEG-21 Wikipedia: MPEG-21 "doc": "application/msword", // Microsoft Word Wikipedia: Microsoft Word "mxf": "application/mxf", // Material Exchange Format RFC 4539 "bin": "application/octet-stream", // Binary Data "oda": "application/oda", // Office Document Architecture RFC 2161 "opf": "application/oebps-package+xml", // Open eBook Publication Structure Wikipedia: Open eBook "ogx": "application/ogg", // Ogg Wikipedia: Ogg "onetoc": "application/onenote", // Microsoft OneNote MS OneNote 2010 "xer": "application/patch-ops-error+xml", // XML Patch Framework RFC 5261 "pdf": "application/pdf", // Adobe Portable Document Format Adobe PDF "pgp": "application/pgp-signature", // Pretty Good Privacy - Signature RFC 2015 "prf": "application/pics-rules", // PICSRules W3C PICSRules "p10": "application/pkcs10", // PKCS #10 - Certification Request Standard RFC 2986 "p7m": "application/pkcs7-mime", // PKCS #7 - Cryptographic Message Syntax Standard RFC 2315 "p7s": "application/pkcs7-signature", // PKCS #7 - Cryptographic Message Syntax Standard RFC 2315 "p8": "application/pkcs8", // PKCS #8 - Private-Key Information Syntax Standard RFC 5208 "ac": "application/pkix-attr-cert", // Attribute Certificate RFC 5877 "cer": "application/pkix-cert", // Internet Public Key Infrastructure - Certificate RFC 2585 "crl": "application/pkix-crl", // Internet Public Key Infrastructure - Certificate Revocation Lists RFC 2585 "pkipath": "application/pkix-pkipath", // Internet Public Key Infrastructure - Certification Path RFC 2585 "pki": "application/pkixcmp", // Internet Public Key Infrastructure - Certificate Management Protocole RFC 2585 "pls": "application/pls+xml", // Pronunciation Lexicon Specification RFC 4267 "ai": "application/postscript", // PostScript Wikipedia: PostScript "cww": "application/prs.cww", // CU-Writer "pskcxml": "application/pskc+xml", // Portable Symmetric Key Container RFC 6030 "rdf": "application/rdf+xml", // Resource Description Framework RFC 3870 "rif": "application/reginfo+xml", // IMS Networks "rnc": "application/relax-ng-compact-syntax", // Relax NG Compact Syntax Relax NG "rl": "application/resource-lists+xml", // XML Resource Lists RFC 4826 "rld": "application/resource-lists-diff+xml", // XML Resource Lists Diff RFC 4826 "rs": "application/rls-services+xml", // XML Resource Lists RFC 4826 "rsd": "application/rsd+xml", // Really Simple Discovery Wikipedia: Really Simple Discovery "rss, .xml": "application/rss+xml", // RSS - Really Simple Syndication Wikipedia: RSS "rtf": "application/rtf", // Rich Text Format Wikipedia: Rich Text Format "sbml": "application/sbml+xml", // Systems Biology Markup Language RFC 3823 "scq": "application/scvp-cv-request", // Server-Based Certificate Validation Protocol - Validation Request RFC 5055 "scs": "application/scvp-cv-response", // Server-Based Certificate Validation Protocol - Validation Response RFC 5055 "spq": "application/scvp-vp-request", // Server-Based Certificate Validation Protocol - Validation Policies - Request RFC 5055 "spp": "application/scvp-vp-response", // Server-Based Certificate Validation Protocol - Validation Policies - Response RFC 5055 "sdp": "application/sdp", // Session Description Protocol RFC 2327 "setpay": "application/set-payment-initiation", // Secure Electronic Transaction - Payment IANA: SET PaymentIANA: SET "shf": "application/shf+xml", // S Hexdump Format RFC 4194 "smi": "application/smil+xml", // Synchronized Multimedia Integration Language RFC 4536 "rq": "application/sparql-query", // SPARQL - Query W3C SPARQL "srx": "application/sparql-results+xml", // SPARQL - Results W3C SPARQL "gram": "application/srgs", // Speech Recognition Grammar Specification W3C Speech Grammar "grxml": "application/srgs+xml", // Speech Recognition Grammar Specification - XML W3C Speech Grammar "sru": "application/sru+xml", // Search/Retrieve via URL Response Format RFC 6207 "ssml": "application/ssml+xml", // Speech Synthesis Markup Language W3C Speech Synthesis "tei": "application/tei+xml", // Text Encoding and Interchange RFC 6129 "tfi": "application/thraud+xml", // Sharing Transaction Fraud Data RFC 5941 "tsd": "application/timestamped-data", // Time Stamped Data Envelope RFC 5955 "plb": "application/vnd.3gpp.pic-bw-large", // 3rd Generation Partnership Project - Pic Large 3GPP "psb": "application/vnd.3gpp.pic-bw-small", // 3rd Generation Partnership Project - Pic Small 3GPP "pvb": "application/vnd.3gpp.pic-bw-var", // 3rd Generation Partnership Project - Pic Var 3GPP "tcap": "application/vnd.3gpp2.tcap", // 3rd Generation Partnership Project - Transaction Capabilities Application Part 3GPP "pwn": "application/vnd.3m.post-it-notes", // 3M Post It Notes IANA: 3M Post It NotesIANA: Simply AccountingIANA: Simply AccountingIANA: ACU Cobol "atc": "application/vnd.acucorp", // ACU Cobol IANA: ACU Cobol "air": "application/vnd.adobe.air-application-installer-package+zip", // Adobe AIR Application Building AIR Applications "fxp": "application/vnd.adobe.fxp", // Adobe Flex Project IANA: Adobe Flex Project "xdp": "application/vnd.adobe.xdp+xml", // Adobe XML Data Package Wikipedia: XML Data Package "xfdf": "application/vnd.adobe.xfdf", // Adobe XML Forms Data Format Wikipedia: XML Portable Document Format "ahead": "application/vnd.ahead.space", // Ahead AIR Application IANA: Ahead AIR ApplicationIANA: AirZip "azs": "application/vnd.airzip.filesecure.azs", // AirZip FileSECURE IANA: AirZip "azw": "application/vnd.amazon.ebook", // Amazon Kindle eBook format Kindle Direct Publishing "acc": "application/vnd.americandynamics.acc", // Active Content Compression IANA: Active Content "ami": "application/vnd.amiga.ami", // AmigaDE IANA: Amiga "apk": "application/vnd.android.package-archive", // Android Package Archive Wikipedia: APK File Format "cii": "application/vnd.anser-web-certificate-issue-initiation", // ANSER-WEB Terminal Client - Certificate Issue IANA: "fti": "application/vnd.anser-web-funds-transfer-initiation", // ANSER-WEB Terminal Client - Web Funds Transfer IANA: "atx": "application/vnd.antix.game-component", // Antix Game Player IANA: Antix Game "mpkg": "application/vnd.apple.installer+xml", // Apple Installer Package IANA: Apple InstallerWikipedia: M3U "swi": "application/vnd.aristanetworks.swi", // Arista Networks Software Image IANA: Arista Networks "aep": "application/vnd.audiograph", // Audiograph IANA: Audiograph "mpm": "application/vnd.blueice.multipass", // Blueice Research Multipass IANA: "bmi": "application/vnd.bmi", // BMI Drawing Data Interchange IANA: BMI "rep": "application/vnd.businessobjects", // BusinessObjects IANA: BusinessObjects "cdxml": "application/vnd.chemdraw+xml", // CambridgeSoft Chem Draw IANA: Chem Draw "mmd": "application/vnd.chipnuts.karaoke-mmd", // Karaoke on Chipnuts Chipsets IANA: Chipnuts KaraokeIANA: Cinderella "cla": "application/vnd.claymore", // Claymore Data Files IANA: Claymore "rp9": "application/vnd.cloanto.rp9", // RetroPlatform Player IANA: RetroPlatform PlayerIANA: Clonk "c11amc": "application/vnd.cluetrust.cartomobile-config", // ClueTrust CartoMobile - Config IANA: "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", // ClueTrust CartoMobile - Config Package IANA: "csp": "application/vnd.commonspace", // Sixth Floor Media - CommonSpace IANA: CommonSpace "cdbcmsg": "application/vnd.contact.cmsg", // CIM Database IANA: CIM Database "cmc": "application/vnd.cosmocaller", // CosmoCaller IANA: CosmoCaller "clkx": "application/vnd.crick.clicker", // CrickSoftware - Clicker IANA: Clicker "clkk": "application/vnd.crick.clicker.keyboard", // CrickSoftware - Clicker - Keyboard IANA: Clicker "clkp": "application/vnd.crick.clicker.palette", // CrickSoftware - Clicker - Palette IANA: Clicker "clkt": "application/vnd.crick.clicker.template", // CrickSoftware - Clicker - Template IANA: Clicker "clkw": "application/vnd.crick.clicker.wordbank", // CrickSoftware - Clicker - Wordbank IANA: Clicker "wbs": "application/vnd.criticaltools.wbs+xml", // Critical Tools - PERT Chart EXPERT IANA: Critical ToolsIANA: PosML "ppd": "application/vnd.cups-ppd", // Adobe PostScript Printer Description File Format IANA: Cups "car": "application/vnd.curl.car", // CURL Applet IANA: CURL Applet "pcurl": "application/vnd.curl.pcurl", // CURL Applet IANA: CURL Applet "rdz": "application/vnd.data-vision.rdz", // RemoteDocs R-Viewer IANA: Data-Vision "fe_launch": "application/vnd.denovo.fcselayout-link", // FCS Express Layout Link IANA: FCS "dna": "application/vnd.dna", // New Moon Liftoff/DNA IANA: New Moon Liftoff/DNA "mlp": "application/vnd.dolby.mlp", // Dolby Meridian Lossless Packing IANA: Dolby Meridian Lossless "dpg": "application/vnd.dpgraph", // DPGraph IANA: DPGraph "dfac": "application/vnd.dreamfactory", // DreamFactory IANA: DreamFactory "ait": "application/vnd.dvb.ait", // Digital Video Broadcasting IANA: Digital Video BroadcastingIANA: Digital Video BroadcastingIANA: DynaGeo "mag": "application/vnd.ecowin.chart", // EcoWin Chart IANA: EcoWin Chart "nml": "application/vnd.enliven", // Enliven Viewer IANA: Enliven Viewer "esf": "application/vnd.epson.esf", // QUASS Stream Player IANA: QUASS Stream Player "msf": "application/vnd.epson.msf", // QUASS Stream Player IANA: QUASS Stream Player "qam": "application/vnd.epson.quickanime", // QuickAnime Player IANA: QuickAnime PlayerIANA: SimpleAnimeLite PlayerIANA: QUASS Stream Player "es3": "application/vnd.eszigno3+xml", // MICROSEC e-Szign¢ IANA: MICROSEC e-Szign¢ "ez2": "application/vnd.ezpix-album", // EZPix Secure Photo Album IANA: EZPix Secure Photo AlbumIANA: EZPix Secure Photo AlbumIANA: Forms Data Format "seed": "application/vnd.fdsn.seed", // Digital Siesmograph Networks - SEED Datafiles IANA: SEED "gph": "application/vnd.flographit", // NpGraphIt IANA: FloGraphIt "ftc": "application/vnd.fluxtime.clip", // FluxTime Clip IANA: FluxTime Clip "fm": "application/vnd.framemaker", // FrameMaker Normal Format IANA: FrameMaker "fnc": "application/vnd.frogans.fnc", // Frogans Player IANA: Frogans Player "ltf": "application/vnd.frogans.ltf", // Frogans Player IANA: Frogans Player "fsc": "application/vnd.fsc.weblaunch", // Friendly Software Corporation IANA: Friendly Software "oas": "application/vnd.fujitsu.oasys", // Fujitsu Oasys IANA: Fujitsu Oasys "oa2": "application/vnd.fujitsu.oasys2", // Fujitsu Oasys IANA: Fujitsu Oasys "oa3": "application/vnd.fujitsu.oasys3", // Fujitsu Oasys IANA: Fujitsu Oasys "fg5": "application/vnd.fujitsu.oasysgp", // Fujitsu Oasys IANA: Fujitsu Oasys "bh2": "application/vnd.fujitsu.oasysprs", // Fujitsu Oasys IANA: Fujitsu Oasys "ddd": "application/vnd.fujixerox.ddd", // Fujitsu - Xerox 2D CAD Data IANA: Fujitsu DDD "xdw": "application/vnd.fujixerox.docuworks", // Fujitsu - Xerox DocuWorks IANA: Docuworks "xbd": "application/vnd.fujixerox.docuworks.binder", // Fujitsu - Xerox DocuWorks Binder IANA: Docuworks "fzs": "application/vnd.fuzzysheet", // FuzzySheet IANA: FuzySheet "txd": "application/vnd.genomatix.tuxedo", // Genomatix Tuxedo Framework IANA: Genomatix Tuxedo "ggb": "application/vnd.geogebra.file", // GeoGebra IANA: GeoGebra "ggt": "application/vnd.geogebra.tool", // GeoGebra IANA: GeoGebra "gex": "application/vnd.geometry-explorer", // GeoMetry Explorer IANA: GeoMetry ExplorerIANA: GEONExT and JSXGraph "g2w": "application/vnd.geoplan", // GeoplanW IANA: GeoplanW "g3w": "application/vnd.geospace", // GeospacW IANA: GeospacW "gmx": "application/vnd.gmx", // GameMaker ActiveX IANA: GameMaker ActiveX "kml": "application/vnd.google-earth.kml+xml", // Google Earth - KML IANA: Google EarthIANA: Google Earth "gqf": "application/vnd.grafeq", // GrafEq IANA: GrafEq "gac": "application/vnd.groove-account", // Groove - Account IANA: Groove "ghf": "application/vnd.groove-help", // Groove - Help IANA: Groove "gim": "application/vnd.groove-identity-message", // Groove - Identity Message IANA: Groove "grv": "application/vnd.groove-injector", // Groove - Injector IANA: Groove "gtm": "application/vnd.groove-tool-message", // Groove - Tool Message IANA: Groove "tpl": "application/vnd.groove-tool-template", // Groove - Tool Template IANA: Groove "vcg": "application/vnd.groove-vcard", // Groove - Vcard IANA: Groove "hal": "application/vnd.hal+xml", // Hypertext Application Language IANA: HAL "zmm": "application/vnd.handheld-entertainment+xml", // ZVUE Media Manager IANA: ZVUE Media "hbci": "application/vnd.hbci", // Homebanking Computer Interface (HBCI) IANA: HBCI "les": "application/vnd.hhe.lesson-player", // Archipelago Lesson Player IANA: Archipelago Lesson "hpgl": "application/vnd.hp-hpgl", // HP-GL/2 and HP RTL IANA: HP-GL/2 and HP RTL "hpid": "application/vnd.hp-hpid", // Hewlett Packard Instant Delivery IANA: Hewlett Packard Instant "hps": "application/vnd.hp-hps", // Hewlett-Packard's WebPrintSmart IANA: Hewlett-Packard's WebPrintSmartIANA: HP Job Layout Language "pcl": "application/vnd.hp-pcl", // HP Printer Command Language IANA: HP Printer Command LanguageIANA: HP PCL XL "sfd-hdstx": "application/vnd.hydrostatix.sof-data", // Hydrostatix Master Suite IANA: Hydrostatix "x3d": "application/vnd.hzn-3d-crossword", // 3D Crossword Plugin IANA: 3D Crossword PluginIANA: MiniPay "afp": "application/vnd.ibm.modcap", // MO: "DCA-P IANA: MO: "DCA-P "irm": "application/vnd.ibm.rights-management", // IBM DB2 Rights Manager IANA: IBM DB2 Rights "sc": "application/vnd.ibm.secure-container", // IBM Electronic Media Management System - Secure Container IANA: EMMS "icc": "application/vnd.iccprofile", // ICC profile IANA: ICC profile "igl": "application/vnd.igloader", // igLoader IANA: igLoader "ivp": "application/vnd.immervision-ivp", // ImmerVision PURE Players IANA: ImmerVision PURE "ivu": "application/vnd.immervision-ivu", // ImmerVision PURE Players IANA: ImmerVision PURE "igm": "application/vnd.insors.igm", // IOCOM Visimeet IANA: IOCOM Visimeet "xpw": "application/vnd.intercon.formnet", // Intercon FormNet IANA: Intercon FormNetIANA: Interactive Geometry SoftwareIANA: Open Financial ExchangeIANA: Quicken "rcprofile": "application/vnd.ipunplugged.rcprofile", // IP Unplugged Roaming Client IANA: IP "irp": "application/vnd.irepository.package+xml", // iRepository / Lucidoc Editor IANA: iRepository / "xpr": "application/vnd.is-xpr", // Express by Infoseek IANA: Express by Infoseek "fcs": "application/vnd.isac.fcs", // International Society for Advancement of Cytometry IANA: International Society for "jam": "application/vnd.jam", // Lightspeed Audio Lab IANA: Lightspeed Audio Lab "rms": "application/vnd.jcp.javame.midlet-rms", // Mobile Information Device Profile IANA: Mobile "jisp": "application/vnd.jisp", // RhymBox IANA: RhymBox "joda": "application/vnd.joost.joda-archive", // Joda Archive IANA: Joda ArchiveIANA: Kahootz "karbon": "application/vnd.kde.karbon", // KDE KOffice Office Suite - Karbon IANA "kia": "application/vnd.kidspiration", // Kidspiration IANA: Kidspiration "kne": "application/vnd.kinar", // Kinar Applications IANA: Kina Applications "skp": "application/vnd.koan", // SSEYO Koan Play File IANA: SSEYO Koan Play File "sse": "application/vnd.kodak-descriptor", // Kodak Storyshare IANA: Kodak StoryshareIANA: Laser app EnterpriseIANA: Life "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", // Life Balance - Exchange Format IANA: "123": "application/vnd.lotus-1-2-3", // Lotus 1-2-3 IANA: Lotus 1-2-3 "apr": "application/vnd.lotus-approach", // Lotus Approach IANA: Lotus Approach "pre": "application/vnd.lotus-freelance", // Lotus Freelance IANA: Lotus Freelance "nsf": "application/vnd.lotus-notes", // Lotus Notes IANA: Lotus Notes "org": "application/vnd.lotus-organizer", // Lotus Organizer IANA: Lotus Organizer "scm": "application/vnd.lotus-screencam", // Lotus Screencam IANA: Lotus Screencam "lwp": "application/vnd.lotus-wordpro", // Lotus Wordpro IANA: Lotus Wordpro "portpkg": "application/vnd.macports.portpkg", // MacPorts Port System IANA: MacPorts Port "mcd": "application/vnd.mcd", // Micro CADAM Helix D&D IANA: Micro CADAM Helix D&D "mc1": "application/vnd.medcalcdata", // MedCalc IANA: MedCalc "cdkey": "application/vnd.mediastation.cdkey", // MediaRemote IANA: MediaRemoteIANA: Medical Waveform Encoding FormatIANA: Melody Format for Mobile PlatformIANA: Micrografx "igx": "application/vnd.micrografx.igx", // Micrografx iGrafx Professional IANA: Micrografx "mif": "application/vnd.mif", // FrameMaker Interchange Format IANA: FrameMaker Interchange FormatIANA: Mobius Management Systems "mpc": "application/vnd.mophun.certificate", // Mophun Certificate IANA: Mophun CertificateIANA: XUL "cil": "application/vnd.ms-artgalry", // Microsoft Artgalry IANA: MS Artgalry "cab": "application/vnd.ms-cab-compressed", // Microsoft Cabinet File IANA: MS Cabinet FileIANA: MS Excel "xlam": "application/vnd.ms-excel.addin.macroenabled.12", // Microsoft Excel - Add-In File IANA: MS "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", // Microsoft Excel - Binary Workbook IANA: "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", // Microsoft Excel - Macro-Enabled Workbook IANA: MS "xltm": "application/vnd.ms-excel.template.macroenabled.12", // Microsoft Excel - Macro-Enabled Template File IANA: MS "eot": "application/vnd.ms-fontobject", // Microsoft Embedded OpenType IANA: MS Embedded OpenTypeIANA: "MS Html Help File "ims": "application/vnd.ms-ims", // Microsoft Class Server IANA: MS Class Server "lrm": "application/vnd.ms-lrm", // Microsoft Learning Resource Module IANA: MS Learning Resource ModuleIANA: MS Office System "cat": "application/vnd.ms-pki.seccat", // Microsoft Trust UI Provider - Security Catalog IANA: MS Trust UI ProviderIANA: MS Trust UI Provider "ppt": "application/vnd.ms-powerpoint", // Microsoft PowerPoint IANA: MS PowerPoint "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", // Microsoft PowerPoint - Add-in file IANA: MS "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Presentation File "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Open XML Slide IANA: MS "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Slide Show File "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", // Micosoft PowerPoint - Macro-Enabled Template File IANA: "mpp": "application/vnd.ms-project", // Microsoft Project IANA: MS PowerPoint "docm": "application/vnd.ms-word.document.macroenabled.12", // Micosoft Word - Macro-Enabled Document IANA: MS "dotm": "application/vnd.ms-word.template.macroenabled.12", // Micosoft Word - Macro-Enabled Template IANA: MS "wps": "application/vnd.ms-works", // Microsoft Works IANA: MS Works "wpl": "application/vnd.ms-wpl", // Microsoft Windows Media Player Playlist IANA: MS Windows Media Player PlaylistIANA: MS XML Paper "mseq": "application/vnd.mseq", // 3GPP MSEQ File IANA: 3GPP MSEQ File "mus": "application/vnd.musician", // MUsical Score Interpreted Code Invented for the ASCII designation of Notation IANA: MUSICIAN "msty": "application/vnd.muvee.style", // Muvee Automatic Video Editing IANA: Muvee "nlu": "application/vnd.neurolanguage.nlu", // neuroLanguage IANA: neuroLanguage "nnd": "application/vnd.noblenet-directory", // NobleNet Directory IANA: NobleNet DirectoryIANA: NobleNet Sealer "nnw": "application/vnd.noblenet-web", // NobleNet Web IANA: NobleNet Web "ngdat": "application/vnd.nokia.n-gage.data", // N-Gage Game Data IANA: N-Gage Game DataIANA: N-Gage "rpst": "application/vnd.nokia.radio-preset", // Nokia Radio Application - Preset IANA: Nokia Radio "rpss": "application/vnd.nokia.radio-presets", // Nokia Radio Application - Preset IANA: Nokia Radio "edm": "application/vnd.novadigm.edm", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "edx": "application/vnd.novadigm.edx", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "ext": "application/vnd.novadigm.ext", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "odc": "application/vnd.oasis.opendocument.chart", // OpenDocument Chart IANA: OpenDocument "otc": "application/vnd.oasis.opendocument.chart-template", // OpenDocument Chart Template IANA: "odb": "application/vnd.oasis.opendocument.database", // OpenDocument Database IANA: "odf": "application/vnd.oasis.opendocument.formula", // OpenDocument Formula IANA: OpenDocument "odft": "application/vnd.oasis.opendocument.formula-template", // OpenDocument Formula Template IANA: "odg": "application/vnd.oasis.opendocument.graphics", // OpenDocument Graphics IANA: "otg": "application/vnd.oasis.opendocument.graphics-template", // OpenDocument Graphics Template IANA: "odi": "application/vnd.oasis.opendocument.image", // OpenDocument Image IANA: OpenDocument "oti": "application/vnd.oasis.opendocument.image-template", // OpenDocument Image Template IANA: "odp": "application/vnd.oasis.opendocument.presentation", // OpenDocument Presentation IANA: "otp": "application/vnd.oasis.opendocument.presentation-template", // OpenDocument Presentation Template "ods": "application/vnd.oasis.opendocument.spreadsheet", // OpenDocument Spreadsheet IANA: "ots": "application/vnd.oasis.opendocument.spreadsheet-template", // OpenDocument Spreadsheet Template IANA: "odt": "application/vnd.oasis.opendocument.text", // OpenDocument Text IANA: OpenDocument "odm": "application/vnd.oasis.opendocument.text-master", // OpenDocument Text Master IANA: "ott": "application/vnd.oasis.opendocument.text-template", // OpenDocument Text Template IANA: "oth": "application/vnd.oasis.opendocument.text-web", // Open Document Text Web IANA: "xo": "application/vnd.olpc-sugar", // Sugar Linux Application Bundle IANA: Sugar Linux app BundleIANA: OMA Download Agents "oxt": "application/vnd.openofficeorg.extension", // Open Office Extension IANA: Open Office "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", // Microsoft Office - OOXML - Presentation "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // Microsoft Office - OOXML - Spreadsheet IANA: MapGuide DBXMLIANA: OSGi Deployment Package "pdb": "application/vnd.palm", // PalmOS Data IANA: PalmOS Data "paw": "application/vnd.pawaafile", // PawaaFILE IANA: PawaaFILE "str": "application/vnd.pg.format", // Proprietary P&G Standard Reporting System IANA: Proprietary P&G Standard "ei6": "application/vnd.pg.osasli", // Proprietary P&G Standard Reporting System IANA: Proprietary P&G Standard "efif": "application/vnd.picsel", // Pcsel eFIF File IANA: Picsel eFIF File "wg": "application/vnd.pmi.widget", // Qualcomm's Plaza Mobile Internet IANA: Qualcomm's Plaza Mobile "plf": "application/vnd.pocketlearn", // PocketLearn Viewers IANA: PocketLearn Viewers "pbd": "application/vnd.powerbuilder6", // PowerBuilder IANA: PowerBuilder "box": "application/vnd.previewsystems.box", // Preview Systems ZipLock/VBox IANA: Preview Systems "mgz": "application/vnd.proteus.magazine", // EFI Proteus IANA: EFI Proteus "qps": "application/vnd.publishare-delta-tree", // PubliShare Objects IANA: PubliShare "ptid": "application/vnd.pvi.ptid1", // Princeton Video Image IANA: Princeton Video ImageIANA: QuarkXPress "bed": "application/vnd.realvnc.bed", // RealVNC IANA: RealVNC "mxl": "application/vnd.recordare.musicxml", // Recordare Applications IANA: Recordare AppsIANA: Recordare "cryptonote": "application/vnd.rig.cryptonote", // CryptoNote IANA: CryptoNote "rm": "application/vnd.rn-realmedia", // RealMedia "link66": "application/vnd.route66.link66+xml", // ROUTE 66 Location Based Services IANA: ROUTE 66 "st": "application/vnd.sailingtracker.track", // SailingTracker IANA: SailingTrackerIANA: SeeMail "sema": "application/vnd.sema", // Secured eMail IANA: Secured eMail "semd": "application/vnd.semd", // Secured eMail IANA: Secured eMail "semf": "application/vnd.semf", // Secured eMail IANA: Secured eMail "ifm": "application/vnd.shana.informed.formdata", // Shana Informed Filler IANA: Shana Informed "itp": "application/vnd.shana.informed.formtemplate", // Shana Informed Filler IANA: Shana "iif": "application/vnd.shana.informed.interchange", // Shana Informed Filler IANA: Shana "ipk": "application/vnd.shana.informed.package", // Shana Informed Filler IANA: Shana Informed "twd": "application/vnd.simtech-mindmapper", // SimTech MindMapper IANA: SimTech MindMapperIANA: SMAF File "teacher": "application/vnd.smart.teacher", // SMART Technologies Apps IANA: SMART Technologies "sdkm": "application/vnd.solent.sdkm+xml", // SudokuMagic IANA: SudokuMagic "dxp": "application/vnd.spotfire.dxp", // TIBCO Spotfire IANA: TIBCO Spotfire "sfs": "application/vnd.spotfire.sfs", // TIBCO Spotfire IANA: TIBCO Spotfire "sdc": "application/vnd.stardivision.calc", // StarOffice - Calc "sda": "application/vnd.stardivision.draw", // StarOffice - Draw "sdd": "application/vnd.stardivision.impress", // StarOffice - Impress "smf": "application/vnd.stardivision.math", // StarOffice - Math "sdw": "application/vnd.stardivision.writer", // StarOffice - Writer "sgl": "application/vnd.stardivision.writer-global", // StarOffice - Writer (Global) "sm": "application/vnd.stepmania.stepchart", // StepMania IANA: StepMania "sxc": "application/vnd.sun.xml.calc", // OpenOffice - Calc (Spreadsheet) Wikipedia: OpenOffice "stc": "application/vnd.sun.xml.calc.template", // OpenOffice - Calc Template (Spreadsheet) Wikipedia: OpenOffice "sxd": "application/vnd.sun.xml.draw", // OpenOffice - Draw (Graphics) Wikipedia: OpenOffice "std": "application/vnd.sun.xml.draw.template", // OpenOffice - Draw Template (Graphics) Wikipedia: OpenOffice "sxi": "application/vnd.sun.xml.impress", // OpenOffice - Impress (Presentation) Wikipedia: OpenOffice "sti": "application/vnd.sun.xml.impress.template", // OpenOffice - Impress Template (Presentation) Wikipedia: OpenOffice "sxm": "application/vnd.sun.xml.math", // OpenOffice - Math (Formula) Wikipedia: OpenOffice "sxw": "application/vnd.sun.xml.writer", // OpenOffice - Writer (Text - HTML) Wikipedia: OpenOffice "sxg": "application/vnd.sun.xml.writer.global", // OpenOffice - Writer (Text - HTML) Wikipedia: OpenOffice "stw": "application/vnd.sun.xml.writer.template", // OpenOffice - Writer Template (Text - HTML) Wikipedia: OpenOffice "sus": "application/vnd.sus-calendar", // ScheduleUs IANA: ScheduleUs "svd": "application/vnd.svd", // SourceView Document IANA: SourceView Document "sis": "application/vnd.symbian.install", // Symbian Install Package IANA: Symbian "xsm": "application/vnd.syncml+xml", // SyncML IANA: SyncML "bdm": "application/vnd.syncml.dm+wbxml", // SyncML - Device Management IANA: SyncML "xdm": "application/vnd.syncml.dm+xml", // SyncML - Device Management IANA: SyncML "tao": "application/vnd.tao.intent-module-archive", // Tao Intent IANA: Tao IntentIANA: MobileTV "tpt": "application/vnd.trid.tpt", // TRI Systems Config IANA: TRI Systems "mxs": "application/vnd.triscape.mxs", // Triscape Map Explorer IANA: Triscape Map ExplorerIANA: True BASIC "ufd": "application/vnd.ufdl", // Universal Forms Description Language IANA: Universal Forms Description "utz": "application/vnd.uiq.theme", // User Interface Quartz - Theme (Symbian) IANA: User Interface Quartz "umj": "application/vnd.umajin", // UMAJIN IANA: UMAJIN "unityweb": "application/vnd.unity", // Unity 3d IANA: Unity 3d "uoml": "application/vnd.uoml+xml", // Unique Object Markup Language IANA: UOML "vcx": "application/vnd.vcx", // VirtualCatalog IANA: VirtualCatalog "vsd": "application/vnd.visio", // Microsoft Visio IANA: Visio "vis": "application/vnd.visionary", // Visionary IANA: Visionary "vsf": "application/vnd.vsf", // Viewport+ IANA: Viewport+ "wbxml": "application/vnd.wap.wbxml", // WAP Binary XML (WBXML) IANA: WBXML "wmlc": "application/vnd.wap.wmlc", // Compiled Wireless Markup Language (WMLC) IANA: WMLC "wmlsc": "application/vnd.wap.wmlscriptc", // WMLScript IANA: WMLScript "wtb": "application/vnd.webturbo", // WebTurbo IANA: WebTurbo "nbp": "application/vnd.wolfram.player", // Mathematica Notebook Player IANA: Mathematica Notebook "wpd": "application/vnd.wordperfect", // Wordperfect IANA: Wordperfect "wqd": "application/vnd.wqd", // SundaHus WQ IANA: SundaHus WQ "stf": "application/vnd.wt.stf", // Worldtalk IANA: Worldtalk "xar": "application/vnd.xara", // CorelXARA IANA: CorelXARA "xfdl": "application/vnd.xfdl", // Extensible Forms Description Language IANA: Extensible Forms Description "hvd": "application/vnd.yamaha.hv-dic", // HV Voice Dictionary IANA: HV Voice DictionaryIANA: HV Script "hvp": "application/vnd.yamaha.hv-voice", // HV Voice Parameter IANA: HV Voice ParameterIANA: Open Score "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", // OSFPVG IANA: "saf": "application/vnd.yamaha.smaf-audio", // SMAF Audio IANA: SMAF Audio "spf": "application/vnd.yamaha.smaf-phrase", // SMAF Phrase IANA: SMAF Phrase "cmp": "application/vnd.yellowriver-custom-menu", // CustomMenu IANA: CustomMenuIANA: Z.U.L. "zaz": "application/vnd.zzazz.deck+xml", // Zzazz Deck IANA: Zzazz "vxml": "application/voicexml+xml", // VoiceXML RFC 4267 "wgt": "application/widget", // Widget Packaging and XML Configuration W3C Widget Packaging and XML "hlp": "application/winhlp", // WinHelp Wikipedia: WinHelp "wsdl": "application/wsdl+xml", // WSDL - Web Services Description Language W3C Web Service Description LanguageW3C Web Services Policy "7z": "application/x-7z-compressed", // 7-Zip Wikipedia: 7-Zip "abw": "application/x-abiword", // AbiWord Wikipedia: AbiWord "ace": "application/x-ace-compressed", // Ace Archive Wikipedia: ACE "aab": "application/x-authorware-bin", // Adobe (Macropedia) Authorware - Binary File Wikipedia: Authorware "aam": "application/x-authorware-map", // Adobe (Macropedia) Authorware - Map Wikipedia: Authorware "aas": "application/x-authorware-seg", // Adobe (Macropedia) Authorware - Segment File Wikipedia: Authorware "bcpio": "application/x-bcpio", // Binary CPIO Archive Wikipedia: cpio "torrent": "application/x-bittorrent", // BitTorrent Wikipedia: BitTorrent "bz": "application/x-bzip", // Bzip Archive Wikipedia: Bzip "bz2": "application/x-bzip2", // Bzip2 Archive Wikipedia: Bzip "vcd": "application/x-cdlink", // Video CD Wikipedia: Video CD "chat": "application/x-chat", // pIRCh Wikipedia: pIRCh "pgn": "application/x-chess-pgn", // Portable Game Notation (Chess Games) Wikipedia: Portable Game Notationb "cpio": "application/x-cpio", // CPIO Archive Wikipedia: cpio "csh": "application/x-csh", // C Shell Script Wikipedia: C Shell "deb": "application/x-debian-package", // Debian Package Wikipedia: Debian Package "dir": "application/x-director", // Adobe Shockwave Player Wikipedia: Adobe Shockwave Player "wad": "application/x-doom", // Doom Video Game Wikipedia: Doom WAD "ncx": "application/x-dtbncx+xml", // Navigation Control file for XML (for ePub) Wikipedia: EPUB "dtb": "application/x-dtbook+xml", // Digital Talking Book Wikipedia: EPUB "res": "application/x-dtbresource+xml", // Digital Talking Book - Resource File Digital Talking Book "dvi": "application/x-dvi", // Device Independent File Format (DVI) Wikipedia: DVI "bdf": "application/x-font-bdf", // Glyph Bitmap Distribution Format Wikipedia: Glyph Bitmap Distribution FormatWikipedia: Ghostscript "psf": "application/x-font-linux-psf", // PSF Fonts PSF Fonts "otf": "application/x-font-otf", // OpenType Font File OpenType Font File "pcf": "application/x-font-pcf", // Portable Compiled Format Wikipedia: Portable Compiled Format "snf": "application/x-font-snf", // Server Normal Format Wikipedia: Server Normal Format "ttf": "application/x-font-ttf", // TrueType Font Wikipedia: TrueType "pfa": "application/x-font-type1", // PostScript Fonts Wikipedia: PostScript Fonts "woff": "application/x-font-woff", // Web Open Font Format Wikipedia: Web Open Font Format "spl": "application/x-futuresplash", // FutureSplash Animator Wikipedia: FutureSplash Animator "gnumeric": "application/x-gnumeric", // Gnumeric Wikipedia: Gnumeric "gtar": "application/x-gtar", // GNU Tar Files GNU Tar "hdf": "application/x-hdf", // Hierarchical Data Format Wikipedia: Hierarchical Data Format "jnlp": "application/x-java-jnlp-file", // Java Network Launching Protocol Wikipedia: Java Web Start "latex": "application/x-latex", // LaTeX Wikipedia: LaTeX "prc": "application/x-mobipocket-ebook", // Mobipocket Wikipedia: Mobipocket "application": "application/x-ms-application", // Microsoft ClickOnce Wikipedia: ClickOnce "wmd": "application/x-ms-wmd", // Microsoft Windows Media Player Download Package Wikipedia: Windows Media Player "wmz": "application/x-ms-wmz", // Microsoft Windows Media Player Skin Package Wikipedia: Windows Media Player "xbap": "application/x-ms-xbap", // Microsoft XAML Browser Application Wikipedia: XAML Browser "mdb": "application/x-msaccess", // Microsoft Access Wikipedia: Microsoft Access "obd": "application/x-msbinder", // Microsoft Office Binder Wikipedia: Microsoft Shared Tools "crd": "application/x-mscardfile", // Microsoft Information Card Wikipedia: Information Card "clp": "application/x-msclip", // Microsoft Clipboard Clip Wikipedia: Clipboard "exe": "application/x-msdownload", // Microsoft Application Wikipedia: EXE "mvb": "application/x-msmediaview", // Microsoft MediaView "wmf": "application/x-msmetafile", // Microsoft Windows Metafile Wikipedia: Windows Metafile "mny": "application/x-msmoney", // Microsoft Money Wikipedia: Microsoft Money "pub": "application/x-mspublisher", // Microsoft Publisher Wikipedia: Microsoft Publisher "scd": "application/x-msschedule", // Microsoft Schedule+ Wikipedia: Microsoft Schedule Plus "trm": "application/x-msterminal", // Microsoft Windows Terminal Services Wikipedia: Terminal Server "wri": "application/x-mswrite", // Microsoft Wordpad Wikipedia: Wordpad "nc": "application/x-netcdf", // Network Common Data Form (NetCDF) Wikipedia: NetCDF "p12": "application/x-pkcs12", // PKCS #12 - Personal Information Exchange Syntax Standard RFC 2986 "p7b": "application/x-pkcs7-certificates", // PKCS #7 - Cryptographic Message Syntax Standard (Certificates) RFC 2986 "p7r": "application/x-pkcs7-certreqresp", // PKCS #7 - Cryptographic Message Syntax Standard (Certificate Request Response) RFC 2986 "rar": "application/x-rar-compressed", // RAR Archive Wikipedia: RAR "sh": "application/x-sh", // Bourne Shell Script Wikipedia: Bourne Shell "shar": "application/x-shar", // Shell Archive Wikipedia: Shell Archie "swf": "application/x-shockwave-flash", // Adobe Flash Wikipedia: Adobe Flash "xap": "application/x-silverlight-app", // Microsoft Silverlight Wikipedia: Silverlight "sit": "application/x-stuffit", // Stuffit Archive Wikipedia: Stuffit "sitx": "application/x-stuffitx", // Stuffit Archive Wikipedia: Stuffit "sv4cpio": "application/x-sv4cpio", // System V Release 4 CPIO Archive Wikipedia: pax "sv4crc": "application/x-sv4crc", // System V Release 4 CPIO Checksum Data Wikipedia: pax "tar": "application/x-tar", // Tar File (Tape Archive) Wikipedia: Tar "tcl": "application/x-tcl", // Tcl Script Wikipedia: Tcl "tex": "application/x-tex", // TeX Wikipedia: TeX "tfm": "application/x-tex-tfm", // TeX Font Metric Wikipedia: TeX Font Metric "texinfo": "application/x-texinfo", // GNU Texinfo Document Wikipedia: Texinfo "ustar": "application/x-ustar", // Ustar (Uniform Standard Tape Archive) Wikipedia: Ustar "src": "application/x-wais-source", // WAIS Source YoLinux "der": "application/x-x509-ca-cert", // X.509 Certificate Wikipedia: X.509 "fig": "application/x-xfig", // Xfig Wikipedia: Xfig "xpi": "application/x-xpinstall", // XPInstall - Mozilla Wikipedia: XPI "xdf": "application/xcap-diff+xml", // XML Configuration Access Protocol - XCAP Diff Wikipedia: XCAP "xenc": "application/xenc+xml", // XML Encryption Syntax and Processing W3C XML Encryption Syntax and Processing "xhtml": "application/xhtml+xml", // XHTML - The Extensible HyperText Markup Language W3C XHTML "xml": "application/xml", // XML - Extensible Markup Language W3C XML "dtd": "application/xml-dtd", // Document Type Definition W3C DTD "xop": "application/xop+xml", // XML-Binary Optimized Packaging W3C XOP "xslt": "application/xslt+xml", // XML Transformations W3C XSLT "xspf": "application/xspf+xml", // XSPF - XML Shareable Playlist Format XML Shareable Playlist Format "mxml": "application/xv+xml", // MXML Wikipedia: MXML "yang": "application/yang", // YANG Data Modeling Language Wikipedia: YANG "yin": "application/yin+xml", // YIN (YANG - XML) Wikipedia: YANG "zip": "application/zip", // Zip Archive Wikipedia: Zip "adp": "audio/adpcm", // Adaptive differential pulse-code modulation Wikipedia: ADPCM "au": "audio/basic", // Sun Audio - Au file format Wikipedia: Sun audio "mid": "audio/midi", // MIDI - Musical Instrument Digital Interface Wikipedia: MIDI "mp4a": "audio/mp4", // MPEG-4 Audio Wikipedia: MP4A "mpga": "audio/mpeg", // MPEG Audio Wikipedia: MPGA "oga": "audio/ogg", // Ogg Audio Wikipedia: Ogg "uva": "audio/vnd.dece.audio", // DECE Audio IANA: Dece Audio "eol": "audio/vnd.digital-winds", // Digital Winds Music IANA: Digital Winds "dra": "audio/vnd.dra", // DRA Audio IANA: DRA "dts": "audio/vnd.dts", // DTS Audio IANA: DTS "dtshd": "audio/vnd.dts.hd", // DTS High Definition Audio IANA: DTS HD "lvp": "audio/vnd.lucent.voice", // Lucent Voice IANA: Lucent Voice "pya": "audio/vnd.ms-playready.media.pya", // Microsoft PlayReady Ecosystem IANA: Microsoft PlayReady "ecelp4800": "audio/vnd.nuera.ecelp4800", // Nuera ECELP 4800 IANA: ECELP 4800 "ecelp7470": "audio/vnd.nuera.ecelp7470", // Nuera ECELP 7470 IANA: ECELP 7470 "ecelp9600": "audio/vnd.nuera.ecelp9600", // Nuera ECELP 9600 IANA: ECELP 9600 "rip": "audio/vnd.rip", // Hit'n'Mix IANA: Hit'n'Mix "weba": "audio/webm", // Open Web Media Project - Audio WebM Project "aac": "audio/x-aac", // Advanced Audio Coding (AAC) Wikipedia: AAC "aif": "audio/x-aiff", // Audio Interchange File Format Wikipedia: Audio Interchange File FormatWikipedia: M3U "wax": "audio/x-ms-wax", // Microsoft Windows Media Audio Redirector Windows Media MetafilesWikipedia: Windows Media Audio "ram": "audio/x-pn-realaudio", // Real Audio Sound Wikipedia: RealPlayer "rmp": "audio/x-pn-realaudio-plugin", // Real Audio Sound Wikipedia: RealPlayer "wav": "audio/x-wav", // Waveform Audio File Format (WAV) Wikipedia: WAV "cdx": "chemical/x-cdx", // ChemDraw eXchange file ChemDraw eXchange file "cif": "chemical/x-cif", // Crystallographic Interchange Format Crystallographic Interchange Format "cmdf": "chemical/x-cmdf", // CrystalMaker Data Format CrystalMaker Data Format "cml": "chemical/x-cml", // Chemical Markup Language Wikipedia: Chemical Markup Language "csml": "chemical/x-csml", // Chemical Style Markup Language Wikipedia: Chemical Style Markup Language "xyz": "chemical/x-xyz", // XYZ File Format Wikipedia: XYZ File Format "bmp": "image/bmp", // Bitmap Image File Wikipedia: BMP File Format "cgm": "image/cgm", // Computer Graphics Metafile Wikipedia: Computer Graphics Metafile "g3": "image/g3fax", // G3 Fax Image Wikipedia: G3 Fax Image "gif": "image/gif", // Graphics Interchange Format Wikipedia: Graphics Interchange Format "ief": "image/ief", // Image Exchange Format RFC 1314 "jpeg, .jpg": "image/jpeg", // JPEG Image RFC 1314 "ktx": "image/ktx", // OpenGL Textures (KTX) KTX File Format "png": "image/png", // Portable Network Graphics (PNG) RFC 2083 "btif": "image/prs.btif", // BTIF IANA: BTIF "svg": "image/svg+xml", // Scalable Vector Graphics (SVG) Wikipedia: SVG "tiff": "image/tiff", // Tagged Image File Format Wikipedia: TIFF "psd": "image/vnd.adobe.photoshop", // Photoshop Document Wikipedia: Photoshop Document "uvi": "image/vnd.dece.graphic", // DECE Graphic IANA: DECE Graphic "sub": "image/vnd.dvb.subtitle", // Close Captioning - Subtitle Wikipedia: Closed Captioning "djvu": "image/vnd.djvu", // DjVu Wikipedia: DjVu "dwg": "image/vnd.dwg", // DWG Drawing Wikipedia: DWG "dxf": "image/vnd.dxf", // AutoCAD DXF Wikipedia: AutoCAD DXF "fbs": "image/vnd.fastbidsheet", // FastBid Sheet IANA: FastBid Sheet "fpx": "image/vnd.fpx", // FlashPix IANA: FPX "fst": "image/vnd.fst", // FAST Search & Transfer ASA IANA: FAST Search & Transfer ASA "mmr": "image/vnd.fujixerox.edmics-mmr", // EDMICS 2000 IANA: EDMICS 2000 "rlc": "image/vnd.fujixerox.edmics-rlc", // EDMICS 2000 IANA: EDMICS 2000 "mdi": "image/vnd.ms-modi", // Microsoft Document Imaging Format Wikipedia: Microsoft Document Image FormatIANA: FPX "wbmp": "image/vnd.wap.wbmp", // WAP Bitamp (WBMP) IANA: WBMP "xif": "image/vnd.xiff", // eXtended Image File Format (XIFF) IANA: XIFF "webp": "image/webp", // WebP Image Wikipedia: WebP "ras": "image/x-cmu-raster", // CMU Image "cmx": "image/x-cmx", // Corel Metafile Exchange (CMX) Wikipedia: CorelDRAW "fh": "image/x-freehand", // FreeHand MX Wikipedia: Macromedia Freehand "ico": "image/x-icon", // Icon Image Wikipedia: ICO File Format "pcx": "image/x-pcx", // PCX Image Wikipedia: PCX "pic": "image/x-pict", // PICT Image Wikipedia: PICT "pnm": "image/x-portable-anymap", // Portable Anymap Image Wikipedia: Netpbm Format "pbm": "image/x-portable-bitmap", // Portable Bitmap Format Wikipedia: Netpbm Format "pgm": "image/x-portable-graymap", // Portable Graymap Format Wikipedia: Netpbm Format "ppm": "image/x-portable-pixmap", // Portable Pixmap Format Wikipedia: Netpbm Format "rgb": "image/x-rgb", // Silicon Graphics RGB Bitmap RGB Image Format "xbm": "image/x-xbitmap", // X BitMap Wikipedia: X BitMap "xpm": "image/x-xpixmap", // X PixMap Wikipedia: X PixMap "xwd": "image/x-xwindowdump", // X Window Dump Wikipedia: X Window Dump "eml": "message/rfc822", // Email Message RFC 2822 "igs": "model/iges", // Initial Graphics Exchange Specification (IGES) Wikipedia: IGES "msh": "model/mesh", // Mesh Data Type RFC 2077 "dae": "model/vnd.collada+xml", // COLLADA IANA: COLLADA "dwf": "model/vnd.dwf", // Autodesk Design Web Format (DWF) Wikipedia: Design Web Format "gdl": "model/vnd.gdl", // Geometric Description Language (GDL) IANA: GDL "gtw": "model/vnd.gtw", // Gen-Trix Studio IANA: GTW "mts": "model/vnd.mts", // Virtue MTS IANA: MTS "vtu": "model/vnd.vtu", // Virtue VTU IANA: VTU "wrl": "model/vrml", // Virtual Reality Modeling Language Wikipedia: VRML "ics": "text/calendar", // iCalendar Wikipedia: iCalendar "css": "text/css", // Cascading Style Sheets (CSS) Wikipedia: CSS "csv": "text/csv", // Comma-Seperated Values Wikipedia: CSV "html": "text/html", // HyperText Markup Language (HTML) Wikipedia: HTML "n3": "text/n3", // Notation3 Wikipedia: Notation3 "txt": "text/plain", // Text File Wikipedia: Text File "dsc": "text/prs.lines.tag", // PRS Lines Tag IANA: PRS Lines Tag "rtx": "text/richtext", // Rich Text Format (RTF) Wikipedia: Rich Text Format "sgml": "text/sgml", // Standard Generalized Markup Language (SGML) Wikipedia: SGML "tsv": "text/tab-separated-values", // Tab Seperated Values Wikipedia: TSV "t": "text/troff", // troff Wikipedia: troff "ttl": "text/turtle", // Turtle (Terse RDF Triple Language) Wikipedia: Turtle "uri": "text/uri-list", // URI Resolution Services RFC 2483 "curl": "text/vnd.curl", // Curl - Applet Curl AppletCurl Detached "scurl": "text/vnd.curl.scurl", // Curl - Source Code Curl Source "mcurl": "text/vnd.curl.mcurl", // Curl - Manifest File Curl Manifest "fly": "text/vnd.fly", // mod_fly / fly.cgi IANA: Fly "flx": "text/vnd.fmi.flexstor", // FLEXSTOR IANA: FLEXSTOR "gv": "text/vnd.graphviz", // Graphviz IANA: Graphviz "3dml": "text/vnd.in3d.3dml", // In3D - 3DML IANA: In3D "spot": "text/vnd.in3d.spot", // In3D - 3DML IANA: In3D "jad": "text/vnd.sun.j2me.app-descriptor", // J2ME app Descriptor IANA: J2ME app DescriptorWikipedia: WML "wmls": "text/vnd.wap.wmlscript", // Wireless Markup Language Script (WMLScript) Wikipedia: WMLScript "s": "text/x-asm", // Assembler Source File Wikipedia: Assembly "c": "text/x-c", // C Source File Wikipedia: C Programming Language "f": "text/x-fortran", // Fortran Source File Wikipedia: Fortran "p": "text/x-pascal", // Pascal Source File Wikipedia: Pascal "java": "text/x-java-source,java", // Java Source File Wikipedia: Java "etx": "text/x-setext", // Setext Wikipedia: Setext "uu": "text/x-uuencode", // UUEncode Wikipedia: UUEncode "vcs": "text/x-vcalendar", // vCalendar Wikipedia: vCalendar "vcf": "text/x-vcard", // vCard Wikipedia: vCard "3gp": "video/3gpp", // 3GP Wikipedia: 3GP "3g2": "video/3gpp2", // 3GP2 Wikipedia: 3G2 "h261": "video/h261", // H.261 Wikipedia: H.261 "h263": "video/h263", // H.263 Wikipedia: H.263 "h264": "video/h264", // H.264 Wikipedia: H.264 "jpgv": "video/jpeg", // JPGVideo RFC 3555 "jpm": "video/jpm", // JPEG 2000 Compound Image File Format IANA: JPM "mj2": "video/mj2", // Motion JPEG 2000 IANA: MJ2 "mp4": "video/mp4", // MPEG-4 Video Wikipedia: MP4 "mpeg": "video/mpeg", // MPEG Video Wikipedia: MPEG "ogv": "video/ogg", // Ogg Video Wikipedia: Ogg "qt": "video/quicktime", // Quicktime Video Wikipedia: Quicktime "uvh": "video/vnd.dece.hd", // DECE High Definition Video IANA: DECE HD Video "uvm": "video/vnd.dece.mobile", // DECE Mobile Video IANA: DECE Mobile Video "uvp": "video/vnd.dece.pd", // DECE PD Video IANA: DECE PD Video "uvs": "video/vnd.dece.sd", // DECE SD Video IANA: DECE SD Video "uvv": "video/vnd.dece.video", // DECE Video IANA: DECE Video "fvt": "video/vnd.fvt", // FAST Search & Transfer ASA IANA: FVT "mxu": "video/vnd.mpegurl", // MPEG Url IANA: MPEG Url "pyv": "video/vnd.ms-playready.media.pyv", // Microsoft PlayReady Ecosystem Video IANA: Microsoft PlayReady "uvu": "video/vnd.uvvu.mp4", // DECE MP4 IANA: DECE MP4 "viv": "video/vnd.vivo", // Vivo IANA: Vivo "webm": "video/webm", // Open Web Media Project - Video WebM Project "f4v": "video/x-f4v", // Flash Video Wikipedia: Flash Video "fli": "video/x-fli", // FLI/FLC Animation Format FLI/FLC Animation Format "flv": "video/x-flv", // Flash Video Wikipedia: Flash Video "m4v": "video/x-m4v", // M4v Wikipedia: M4v "asf": "video/x-ms-asf", // Microsoft Advanced Systems Format (ASF) Wikipedia: Advanced Systems Format (ASF) "wm": "video/x-ms-wm", // Microsoft Windows Media Wikipedia: Advanced Systems Format (ASF) "wmv": "video/x-ms-wmv", // Microsoft Windows Media Video Wikipedia: Advanced Systems Format (ASF) "wmx": "video/x-ms-wmx", // Microsoft Windows Media Audio/Video Playlist Wikipedia: Advanced Systems Format (ASF) "wvx": "video/x-ms-wvx", // Microsoft Windows Media Video Playlist Wikipedia: Advanced Systems Format (ASF) "avi": "video/x-msvideo", // Audio Video Interleave (AVI) Wikipedia: AVI "movie": "video/x-sgi-movie", // SGI Movie SGI Facts "ice": "x-conference/x-cooltalk", // CoolTalk Wikipedia: CoolTalk "par": "text/plain-bas" // BAS Partitur Format Phonetik BAS ] Fixed jpg and jpeg mime type retrieval for FileMiddleware // Scraped from http://www.freeformatter.com/mime-types-list.html let mediaTypes = [ "aw": "application/applixware", // Applixware Vistasource "atom": "application/atom+xml", // Atom Syndication Format RFC 4287 "atomcat": "application/atomcat+xml", // Atom Publishing Protocol RFC 5023 "atomsvc": "application/atomsvc+xml", // Atom Publishing Protocol Service Document RFC 5023 "ccxml": "application/ccxml+xml", // Voice Browser Call Control Voice Browser Call Control: CCXML Version 1.0 "cdmia": "application/cdmi-capability", // Cloud Data Management Interface (CDMI) - Capability RFC 6208 "cdmic": "application/cdmi-container", // Cloud Data Management Interface (CDMI) - Contaimer RFC 6209 "cdmid": "application/cdmi-domain", // Cloud Data Management Interface (CDMI) - Domain RFC 6210 "cdmio": "application/cdmi-object", // Cloud Data Management Interface (CDMI) - Object RFC 6211 "cdmiq": "application/cdmi-queue", // Cloud Data Management Interface (CDMI) - Queue RFC 6212 "cu": "application/cu-seeme", // CU-SeeMe White Pine "davmount": "application/davmount+xml", // Web Distributed Authoring and Versioning RFC 4918 "dssc": "application/dssc+der", // Data Structure for the Security Suitability of Cryptographic Algorithms RFC 5698 "xdssc": "application/dssc+xml", // Data Structure for the Security Suitability of Cryptographic Algorithms RFC 5698 "es": "application/ecmascript", // ECMAScript ECMA-357 "emma": "application/emma+xml", // Extensible MultiModal Annotation EMMA: Extensible MultiModal Annotation markup languageWikipedia: EPUB "exi": "application/exi", // Efficient XML Interchange Efficient XML Interchange (EXI) Best Practices "pfr": "application/font-tdpfr", // Portable Font Resource RFC 3073 "stk": "application/hyperstudio", // Hyperstudio IANA - Hyperstudio "ipfix": "application/ipfix", // Internet Protocol Flow Information Export RFC 3917 "jar": "application/java-archive", // Java Archive Wikipedia: JAR file format "ser": "application/java-serialized-object", // Java Serialized Object Java Serialization API "class": "application/java-vm", // Java Bytecode File Wikipedia: Java Bytecode "js": "application/javascript", // JavaScript JavaScript "json": "application/json", // JavaScript Object Notation (JSON) Wikipedia: JSON "hqx": "application/mac-binhex40", // Macintosh BinHex 4.0 MacMIME "cpt": "application/mac-compactpro", // Compact Pro Compact Pro "mads": "application/mads+xml", // Metadata Authority Description Schema RFC 6207 "mrc": "application/marc", // MARC Formats RFC 2220 "mrcx": "application/marcxml+xml", // MARC21 XML Schema RFC 6207 "ma": "application/mathematica", // Mathematica Notebooks IANA - Mathematica "mathml": "application/mathml+xml", // Mathematical Markup Language W3C Math Home "mbox": "application/mbox", // Mbox database files RFC 4155 "mscml": "application/mediaservercontrol+xml", // Media Server Control Markup Language RFC 5022 "meta4": "application/metalink4+xml", // Metalink Wikipedia: Metalink "mets": "application/mets+xml", // Metadata Encoding and Transmission Standard RFC 6207 "mods": "application/mods+xml", // Metadata Object Description Schema RFC 6207 "m21": "application/mp21", // MPEG-21 Wikipedia: MPEG-21 "doc": "application/msword", // Microsoft Word Wikipedia: Microsoft Word "mxf": "application/mxf", // Material Exchange Format RFC 4539 "bin": "application/octet-stream", // Binary Data "oda": "application/oda", // Office Document Architecture RFC 2161 "opf": "application/oebps-package+xml", // Open eBook Publication Structure Wikipedia: Open eBook "ogx": "application/ogg", // Ogg Wikipedia: Ogg "onetoc": "application/onenote", // Microsoft OneNote MS OneNote 2010 "xer": "application/patch-ops-error+xml", // XML Patch Framework RFC 5261 "pdf": "application/pdf", // Adobe Portable Document Format Adobe PDF "pgp": "application/pgp-signature", // Pretty Good Privacy - Signature RFC 2015 "prf": "application/pics-rules", // PICSRules W3C PICSRules "p10": "application/pkcs10", // PKCS #10 - Certification Request Standard RFC 2986 "p7m": "application/pkcs7-mime", // PKCS #7 - Cryptographic Message Syntax Standard RFC 2315 "p7s": "application/pkcs7-signature", // PKCS #7 - Cryptographic Message Syntax Standard RFC 2315 "p8": "application/pkcs8", // PKCS #8 - Private-Key Information Syntax Standard RFC 5208 "ac": "application/pkix-attr-cert", // Attribute Certificate RFC 5877 "cer": "application/pkix-cert", // Internet Public Key Infrastructure - Certificate RFC 2585 "crl": "application/pkix-crl", // Internet Public Key Infrastructure - Certificate Revocation Lists RFC 2585 "pkipath": "application/pkix-pkipath", // Internet Public Key Infrastructure - Certification Path RFC 2585 "pki": "application/pkixcmp", // Internet Public Key Infrastructure - Certificate Management Protocole RFC 2585 "pls": "application/pls+xml", // Pronunciation Lexicon Specification RFC 4267 "ai": "application/postscript", // PostScript Wikipedia: PostScript "cww": "application/prs.cww", // CU-Writer "pskcxml": "application/pskc+xml", // Portable Symmetric Key Container RFC 6030 "rdf": "application/rdf+xml", // Resource Description Framework RFC 3870 "rif": "application/reginfo+xml", // IMS Networks "rnc": "application/relax-ng-compact-syntax", // Relax NG Compact Syntax Relax NG "rl": "application/resource-lists+xml", // XML Resource Lists RFC 4826 "rld": "application/resource-lists-diff+xml", // XML Resource Lists Diff RFC 4826 "rs": "application/rls-services+xml", // XML Resource Lists RFC 4826 "rsd": "application/rsd+xml", // Really Simple Discovery Wikipedia: Really Simple Discovery "rss, .xml": "application/rss+xml", // RSS - Really Simple Syndication Wikipedia: RSS "rtf": "application/rtf", // Rich Text Format Wikipedia: Rich Text Format "sbml": "application/sbml+xml", // Systems Biology Markup Language RFC 3823 "scq": "application/scvp-cv-request", // Server-Based Certificate Validation Protocol - Validation Request RFC 5055 "scs": "application/scvp-cv-response", // Server-Based Certificate Validation Protocol - Validation Response RFC 5055 "spq": "application/scvp-vp-request", // Server-Based Certificate Validation Protocol - Validation Policies - Request RFC 5055 "spp": "application/scvp-vp-response", // Server-Based Certificate Validation Protocol - Validation Policies - Response RFC 5055 "sdp": "application/sdp", // Session Description Protocol RFC 2327 "setpay": "application/set-payment-initiation", // Secure Electronic Transaction - Payment IANA: SET PaymentIANA: SET "shf": "application/shf+xml", // S Hexdump Format RFC 4194 "smi": "application/smil+xml", // Synchronized Multimedia Integration Language RFC 4536 "rq": "application/sparql-query", // SPARQL - Query W3C SPARQL "srx": "application/sparql-results+xml", // SPARQL - Results W3C SPARQL "gram": "application/srgs", // Speech Recognition Grammar Specification W3C Speech Grammar "grxml": "application/srgs+xml", // Speech Recognition Grammar Specification - XML W3C Speech Grammar "sru": "application/sru+xml", // Search/Retrieve via URL Response Format RFC 6207 "ssml": "application/ssml+xml", // Speech Synthesis Markup Language W3C Speech Synthesis "tei": "application/tei+xml", // Text Encoding and Interchange RFC 6129 "tfi": "application/thraud+xml", // Sharing Transaction Fraud Data RFC 5941 "tsd": "application/timestamped-data", // Time Stamped Data Envelope RFC 5955 "plb": "application/vnd.3gpp.pic-bw-large", // 3rd Generation Partnership Project - Pic Large 3GPP "psb": "application/vnd.3gpp.pic-bw-small", // 3rd Generation Partnership Project - Pic Small 3GPP "pvb": "application/vnd.3gpp.pic-bw-var", // 3rd Generation Partnership Project - Pic Var 3GPP "tcap": "application/vnd.3gpp2.tcap", // 3rd Generation Partnership Project - Transaction Capabilities Application Part 3GPP "pwn": "application/vnd.3m.post-it-notes", // 3M Post It Notes IANA: 3M Post It NotesIANA: Simply AccountingIANA: Simply AccountingIANA: ACU Cobol "atc": "application/vnd.acucorp", // ACU Cobol IANA: ACU Cobol "air": "application/vnd.adobe.air-application-installer-package+zip", // Adobe AIR Application Building AIR Applications "fxp": "application/vnd.adobe.fxp", // Adobe Flex Project IANA: Adobe Flex Project "xdp": "application/vnd.adobe.xdp+xml", // Adobe XML Data Package Wikipedia: XML Data Package "xfdf": "application/vnd.adobe.xfdf", // Adobe XML Forms Data Format Wikipedia: XML Portable Document Format "ahead": "application/vnd.ahead.space", // Ahead AIR Application IANA: Ahead AIR ApplicationIANA: AirZip "azs": "application/vnd.airzip.filesecure.azs", // AirZip FileSECURE IANA: AirZip "azw": "application/vnd.amazon.ebook", // Amazon Kindle eBook format Kindle Direct Publishing "acc": "application/vnd.americandynamics.acc", // Active Content Compression IANA: Active Content "ami": "application/vnd.amiga.ami", // AmigaDE IANA: Amiga "apk": "application/vnd.android.package-archive", // Android Package Archive Wikipedia: APK File Format "cii": "application/vnd.anser-web-certificate-issue-initiation", // ANSER-WEB Terminal Client - Certificate Issue IANA: "fti": "application/vnd.anser-web-funds-transfer-initiation", // ANSER-WEB Terminal Client - Web Funds Transfer IANA: "atx": "application/vnd.antix.game-component", // Antix Game Player IANA: Antix Game "mpkg": "application/vnd.apple.installer+xml", // Apple Installer Package IANA: Apple InstallerWikipedia: M3U "swi": "application/vnd.aristanetworks.swi", // Arista Networks Software Image IANA: Arista Networks "aep": "application/vnd.audiograph", // Audiograph IANA: Audiograph "mpm": "application/vnd.blueice.multipass", // Blueice Research Multipass IANA: "bmi": "application/vnd.bmi", // BMI Drawing Data Interchange IANA: BMI "rep": "application/vnd.businessobjects", // BusinessObjects IANA: BusinessObjects "cdxml": "application/vnd.chemdraw+xml", // CambridgeSoft Chem Draw IANA: Chem Draw "mmd": "application/vnd.chipnuts.karaoke-mmd", // Karaoke on Chipnuts Chipsets IANA: Chipnuts KaraokeIANA: Cinderella "cla": "application/vnd.claymore", // Claymore Data Files IANA: Claymore "rp9": "application/vnd.cloanto.rp9", // RetroPlatform Player IANA: RetroPlatform PlayerIANA: Clonk "c11amc": "application/vnd.cluetrust.cartomobile-config", // ClueTrust CartoMobile - Config IANA: "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", // ClueTrust CartoMobile - Config Package IANA: "csp": "application/vnd.commonspace", // Sixth Floor Media - CommonSpace IANA: CommonSpace "cdbcmsg": "application/vnd.contact.cmsg", // CIM Database IANA: CIM Database "cmc": "application/vnd.cosmocaller", // CosmoCaller IANA: CosmoCaller "clkx": "application/vnd.crick.clicker", // CrickSoftware - Clicker IANA: Clicker "clkk": "application/vnd.crick.clicker.keyboard", // CrickSoftware - Clicker - Keyboard IANA: Clicker "clkp": "application/vnd.crick.clicker.palette", // CrickSoftware - Clicker - Palette IANA: Clicker "clkt": "application/vnd.crick.clicker.template", // CrickSoftware - Clicker - Template IANA: Clicker "clkw": "application/vnd.crick.clicker.wordbank", // CrickSoftware - Clicker - Wordbank IANA: Clicker "wbs": "application/vnd.criticaltools.wbs+xml", // Critical Tools - PERT Chart EXPERT IANA: Critical ToolsIANA: PosML "ppd": "application/vnd.cups-ppd", // Adobe PostScript Printer Description File Format IANA: Cups "car": "application/vnd.curl.car", // CURL Applet IANA: CURL Applet "pcurl": "application/vnd.curl.pcurl", // CURL Applet IANA: CURL Applet "rdz": "application/vnd.data-vision.rdz", // RemoteDocs R-Viewer IANA: Data-Vision "fe_launch": "application/vnd.denovo.fcselayout-link", // FCS Express Layout Link IANA: FCS "dna": "application/vnd.dna", // New Moon Liftoff/DNA IANA: New Moon Liftoff/DNA "mlp": "application/vnd.dolby.mlp", // Dolby Meridian Lossless Packing IANA: Dolby Meridian Lossless "dpg": "application/vnd.dpgraph", // DPGraph IANA: DPGraph "dfac": "application/vnd.dreamfactory", // DreamFactory IANA: DreamFactory "ait": "application/vnd.dvb.ait", // Digital Video Broadcasting IANA: Digital Video BroadcastingIANA: Digital Video BroadcastingIANA: DynaGeo "mag": "application/vnd.ecowin.chart", // EcoWin Chart IANA: EcoWin Chart "nml": "application/vnd.enliven", // Enliven Viewer IANA: Enliven Viewer "esf": "application/vnd.epson.esf", // QUASS Stream Player IANA: QUASS Stream Player "msf": "application/vnd.epson.msf", // QUASS Stream Player IANA: QUASS Stream Player "qam": "application/vnd.epson.quickanime", // QuickAnime Player IANA: QuickAnime PlayerIANA: SimpleAnimeLite PlayerIANA: QUASS Stream Player "es3": "application/vnd.eszigno3+xml", // MICROSEC e-Szign¢ IANA: MICROSEC e-Szign¢ "ez2": "application/vnd.ezpix-album", // EZPix Secure Photo Album IANA: EZPix Secure Photo AlbumIANA: EZPix Secure Photo AlbumIANA: Forms Data Format "seed": "application/vnd.fdsn.seed", // Digital Siesmograph Networks - SEED Datafiles IANA: SEED "gph": "application/vnd.flographit", // NpGraphIt IANA: FloGraphIt "ftc": "application/vnd.fluxtime.clip", // FluxTime Clip IANA: FluxTime Clip "fm": "application/vnd.framemaker", // FrameMaker Normal Format IANA: FrameMaker "fnc": "application/vnd.frogans.fnc", // Frogans Player IANA: Frogans Player "ltf": "application/vnd.frogans.ltf", // Frogans Player IANA: Frogans Player "fsc": "application/vnd.fsc.weblaunch", // Friendly Software Corporation IANA: Friendly Software "oas": "application/vnd.fujitsu.oasys", // Fujitsu Oasys IANA: Fujitsu Oasys "oa2": "application/vnd.fujitsu.oasys2", // Fujitsu Oasys IANA: Fujitsu Oasys "oa3": "application/vnd.fujitsu.oasys3", // Fujitsu Oasys IANA: Fujitsu Oasys "fg5": "application/vnd.fujitsu.oasysgp", // Fujitsu Oasys IANA: Fujitsu Oasys "bh2": "application/vnd.fujitsu.oasysprs", // Fujitsu Oasys IANA: Fujitsu Oasys "ddd": "application/vnd.fujixerox.ddd", // Fujitsu - Xerox 2D CAD Data IANA: Fujitsu DDD "xdw": "application/vnd.fujixerox.docuworks", // Fujitsu - Xerox DocuWorks IANA: Docuworks "xbd": "application/vnd.fujixerox.docuworks.binder", // Fujitsu - Xerox DocuWorks Binder IANA: Docuworks "fzs": "application/vnd.fuzzysheet", // FuzzySheet IANA: FuzySheet "txd": "application/vnd.genomatix.tuxedo", // Genomatix Tuxedo Framework IANA: Genomatix Tuxedo "ggb": "application/vnd.geogebra.file", // GeoGebra IANA: GeoGebra "ggt": "application/vnd.geogebra.tool", // GeoGebra IANA: GeoGebra "gex": "application/vnd.geometry-explorer", // GeoMetry Explorer IANA: GeoMetry ExplorerIANA: GEONExT and JSXGraph "g2w": "application/vnd.geoplan", // GeoplanW IANA: GeoplanW "g3w": "application/vnd.geospace", // GeospacW IANA: GeospacW "gmx": "application/vnd.gmx", // GameMaker ActiveX IANA: GameMaker ActiveX "kml": "application/vnd.google-earth.kml+xml", // Google Earth - KML IANA: Google EarthIANA: Google Earth "gqf": "application/vnd.grafeq", // GrafEq IANA: GrafEq "gac": "application/vnd.groove-account", // Groove - Account IANA: Groove "ghf": "application/vnd.groove-help", // Groove - Help IANA: Groove "gim": "application/vnd.groove-identity-message", // Groove - Identity Message IANA: Groove "grv": "application/vnd.groove-injector", // Groove - Injector IANA: Groove "gtm": "application/vnd.groove-tool-message", // Groove - Tool Message IANA: Groove "tpl": "application/vnd.groove-tool-template", // Groove - Tool Template IANA: Groove "vcg": "application/vnd.groove-vcard", // Groove - Vcard IANA: Groove "hal": "application/vnd.hal+xml", // Hypertext Application Language IANA: HAL "zmm": "application/vnd.handheld-entertainment+xml", // ZVUE Media Manager IANA: ZVUE Media "hbci": "application/vnd.hbci", // Homebanking Computer Interface (HBCI) IANA: HBCI "les": "application/vnd.hhe.lesson-player", // Archipelago Lesson Player IANA: Archipelago Lesson "hpgl": "application/vnd.hp-hpgl", // HP-GL/2 and HP RTL IANA: HP-GL/2 and HP RTL "hpid": "application/vnd.hp-hpid", // Hewlett Packard Instant Delivery IANA: Hewlett Packard Instant "hps": "application/vnd.hp-hps", // Hewlett-Packard's WebPrintSmart IANA: Hewlett-Packard's WebPrintSmartIANA: HP Job Layout Language "pcl": "application/vnd.hp-pcl", // HP Printer Command Language IANA: HP Printer Command LanguageIANA: HP PCL XL "sfd-hdstx": "application/vnd.hydrostatix.sof-data", // Hydrostatix Master Suite IANA: Hydrostatix "x3d": "application/vnd.hzn-3d-crossword", // 3D Crossword Plugin IANA: 3D Crossword PluginIANA: MiniPay "afp": "application/vnd.ibm.modcap", // MO: "DCA-P IANA: MO: "DCA-P "irm": "application/vnd.ibm.rights-management", // IBM DB2 Rights Manager IANA: IBM DB2 Rights "sc": "application/vnd.ibm.secure-container", // IBM Electronic Media Management System - Secure Container IANA: EMMS "icc": "application/vnd.iccprofile", // ICC profile IANA: ICC profile "igl": "application/vnd.igloader", // igLoader IANA: igLoader "ivp": "application/vnd.immervision-ivp", // ImmerVision PURE Players IANA: ImmerVision PURE "ivu": "application/vnd.immervision-ivu", // ImmerVision PURE Players IANA: ImmerVision PURE "igm": "application/vnd.insors.igm", // IOCOM Visimeet IANA: IOCOM Visimeet "xpw": "application/vnd.intercon.formnet", // Intercon FormNet IANA: Intercon FormNetIANA: Interactive Geometry SoftwareIANA: Open Financial ExchangeIANA: Quicken "rcprofile": "application/vnd.ipunplugged.rcprofile", // IP Unplugged Roaming Client IANA: IP "irp": "application/vnd.irepository.package+xml", // iRepository / Lucidoc Editor IANA: iRepository / "xpr": "application/vnd.is-xpr", // Express by Infoseek IANA: Express by Infoseek "fcs": "application/vnd.isac.fcs", // International Society for Advancement of Cytometry IANA: International Society for "jam": "application/vnd.jam", // Lightspeed Audio Lab IANA: Lightspeed Audio Lab "rms": "application/vnd.jcp.javame.midlet-rms", // Mobile Information Device Profile IANA: Mobile "jisp": "application/vnd.jisp", // RhymBox IANA: RhymBox "joda": "application/vnd.joost.joda-archive", // Joda Archive IANA: Joda ArchiveIANA: Kahootz "karbon": "application/vnd.kde.karbon", // KDE KOffice Office Suite - Karbon IANA "kia": "application/vnd.kidspiration", // Kidspiration IANA: Kidspiration "kne": "application/vnd.kinar", // Kinar Applications IANA: Kina Applications "skp": "application/vnd.koan", // SSEYO Koan Play File IANA: SSEYO Koan Play File "sse": "application/vnd.kodak-descriptor", // Kodak Storyshare IANA: Kodak StoryshareIANA: Laser app EnterpriseIANA: Life "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", // Life Balance - Exchange Format IANA: "123": "application/vnd.lotus-1-2-3", // Lotus 1-2-3 IANA: Lotus 1-2-3 "apr": "application/vnd.lotus-approach", // Lotus Approach IANA: Lotus Approach "pre": "application/vnd.lotus-freelance", // Lotus Freelance IANA: Lotus Freelance "nsf": "application/vnd.lotus-notes", // Lotus Notes IANA: Lotus Notes "org": "application/vnd.lotus-organizer", // Lotus Organizer IANA: Lotus Organizer "scm": "application/vnd.lotus-screencam", // Lotus Screencam IANA: Lotus Screencam "lwp": "application/vnd.lotus-wordpro", // Lotus Wordpro IANA: Lotus Wordpro "portpkg": "application/vnd.macports.portpkg", // MacPorts Port System IANA: MacPorts Port "mcd": "application/vnd.mcd", // Micro CADAM Helix D&D IANA: Micro CADAM Helix D&D "mc1": "application/vnd.medcalcdata", // MedCalc IANA: MedCalc "cdkey": "application/vnd.mediastation.cdkey", // MediaRemote IANA: MediaRemoteIANA: Medical Waveform Encoding FormatIANA: Melody Format for Mobile PlatformIANA: Micrografx "igx": "application/vnd.micrografx.igx", // Micrografx iGrafx Professional IANA: Micrografx "mif": "application/vnd.mif", // FrameMaker Interchange Format IANA: FrameMaker Interchange FormatIANA: Mobius Management Systems "mpc": "application/vnd.mophun.certificate", // Mophun Certificate IANA: Mophun CertificateIANA: XUL "cil": "application/vnd.ms-artgalry", // Microsoft Artgalry IANA: MS Artgalry "cab": "application/vnd.ms-cab-compressed", // Microsoft Cabinet File IANA: MS Cabinet FileIANA: MS Excel "xlam": "application/vnd.ms-excel.addin.macroenabled.12", // Microsoft Excel - Add-In File IANA: MS "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", // Microsoft Excel - Binary Workbook IANA: "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", // Microsoft Excel - Macro-Enabled Workbook IANA: MS "xltm": "application/vnd.ms-excel.template.macroenabled.12", // Microsoft Excel - Macro-Enabled Template File IANA: MS "eot": "application/vnd.ms-fontobject", // Microsoft Embedded OpenType IANA: MS Embedded OpenTypeIANA: "MS Html Help File "ims": "application/vnd.ms-ims", // Microsoft Class Server IANA: MS Class Server "lrm": "application/vnd.ms-lrm", // Microsoft Learning Resource Module IANA: MS Learning Resource ModuleIANA: MS Office System "cat": "application/vnd.ms-pki.seccat", // Microsoft Trust UI Provider - Security Catalog IANA: MS Trust UI ProviderIANA: MS Trust UI Provider "ppt": "application/vnd.ms-powerpoint", // Microsoft PowerPoint IANA: MS PowerPoint "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", // Microsoft PowerPoint - Add-in file IANA: MS "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Presentation File "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Open XML Slide IANA: MS "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", // Microsoft PowerPoint - Macro-Enabled Slide Show File "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", // Micosoft PowerPoint - Macro-Enabled Template File IANA: "mpp": "application/vnd.ms-project", // Microsoft Project IANA: MS PowerPoint "docm": "application/vnd.ms-word.document.macroenabled.12", // Micosoft Word - Macro-Enabled Document IANA: MS "dotm": "application/vnd.ms-word.template.macroenabled.12", // Micosoft Word - Macro-Enabled Template IANA: MS "wps": "application/vnd.ms-works", // Microsoft Works IANA: MS Works "wpl": "application/vnd.ms-wpl", // Microsoft Windows Media Player Playlist IANA: MS Windows Media Player PlaylistIANA: MS XML Paper "mseq": "application/vnd.mseq", // 3GPP MSEQ File IANA: 3GPP MSEQ File "mus": "application/vnd.musician", // MUsical Score Interpreted Code Invented for the ASCII designation of Notation IANA: MUSICIAN "msty": "application/vnd.muvee.style", // Muvee Automatic Video Editing IANA: Muvee "nlu": "application/vnd.neurolanguage.nlu", // neuroLanguage IANA: neuroLanguage "nnd": "application/vnd.noblenet-directory", // NobleNet Directory IANA: NobleNet DirectoryIANA: NobleNet Sealer "nnw": "application/vnd.noblenet-web", // NobleNet Web IANA: NobleNet Web "ngdat": "application/vnd.nokia.n-gage.data", // N-Gage Game Data IANA: N-Gage Game DataIANA: N-Gage "rpst": "application/vnd.nokia.radio-preset", // Nokia Radio Application - Preset IANA: Nokia Radio "rpss": "application/vnd.nokia.radio-presets", // Nokia Radio Application - Preset IANA: Nokia Radio "edm": "application/vnd.novadigm.edm", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "edx": "application/vnd.novadigm.edx", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "ext": "application/vnd.novadigm.ext", // Novadigm's RADIA and EDM products IANA: Novadigm's RADIA and EDM "odc": "application/vnd.oasis.opendocument.chart", // OpenDocument Chart IANA: OpenDocument "otc": "application/vnd.oasis.opendocument.chart-template", // OpenDocument Chart Template IANA: "odb": "application/vnd.oasis.opendocument.database", // OpenDocument Database IANA: "odf": "application/vnd.oasis.opendocument.formula", // OpenDocument Formula IANA: OpenDocument "odft": "application/vnd.oasis.opendocument.formula-template", // OpenDocument Formula Template IANA: "odg": "application/vnd.oasis.opendocument.graphics", // OpenDocument Graphics IANA: "otg": "application/vnd.oasis.opendocument.graphics-template", // OpenDocument Graphics Template IANA: "odi": "application/vnd.oasis.opendocument.image", // OpenDocument Image IANA: OpenDocument "oti": "application/vnd.oasis.opendocument.image-template", // OpenDocument Image Template IANA: "odp": "application/vnd.oasis.opendocument.presentation", // OpenDocument Presentation IANA: "otp": "application/vnd.oasis.opendocument.presentation-template", // OpenDocument Presentation Template "ods": "application/vnd.oasis.opendocument.spreadsheet", // OpenDocument Spreadsheet IANA: "ots": "application/vnd.oasis.opendocument.spreadsheet-template", // OpenDocument Spreadsheet Template IANA: "odt": "application/vnd.oasis.opendocument.text", // OpenDocument Text IANA: OpenDocument "odm": "application/vnd.oasis.opendocument.text-master", // OpenDocument Text Master IANA: "ott": "application/vnd.oasis.opendocument.text-template", // OpenDocument Text Template IANA: "oth": "application/vnd.oasis.opendocument.text-web", // Open Document Text Web IANA: "xo": "application/vnd.olpc-sugar", // Sugar Linux Application Bundle IANA: Sugar Linux app BundleIANA: OMA Download Agents "oxt": "application/vnd.openofficeorg.extension", // Open Office Extension IANA: Open Office "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", // Microsoft Office - OOXML - Presentation "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // Microsoft Office - OOXML - Spreadsheet IANA: MapGuide DBXMLIANA: OSGi Deployment Package "pdb": "application/vnd.palm", // PalmOS Data IANA: PalmOS Data "paw": "application/vnd.pawaafile", // PawaaFILE IANA: PawaaFILE "str": "application/vnd.pg.format", // Proprietary P&G Standard Reporting System IANA: Proprietary P&G Standard "ei6": "application/vnd.pg.osasli", // Proprietary P&G Standard Reporting System IANA: Proprietary P&G Standard "efif": "application/vnd.picsel", // Pcsel eFIF File IANA: Picsel eFIF File "wg": "application/vnd.pmi.widget", // Qualcomm's Plaza Mobile Internet IANA: Qualcomm's Plaza Mobile "plf": "application/vnd.pocketlearn", // PocketLearn Viewers IANA: PocketLearn Viewers "pbd": "application/vnd.powerbuilder6", // PowerBuilder IANA: PowerBuilder "box": "application/vnd.previewsystems.box", // Preview Systems ZipLock/VBox IANA: Preview Systems "mgz": "application/vnd.proteus.magazine", // EFI Proteus IANA: EFI Proteus "qps": "application/vnd.publishare-delta-tree", // PubliShare Objects IANA: PubliShare "ptid": "application/vnd.pvi.ptid1", // Princeton Video Image IANA: Princeton Video ImageIANA: QuarkXPress "bed": "application/vnd.realvnc.bed", // RealVNC IANA: RealVNC "mxl": "application/vnd.recordare.musicxml", // Recordare Applications IANA: Recordare AppsIANA: Recordare "cryptonote": "application/vnd.rig.cryptonote", // CryptoNote IANA: CryptoNote "rm": "application/vnd.rn-realmedia", // RealMedia "link66": "application/vnd.route66.link66+xml", // ROUTE 66 Location Based Services IANA: ROUTE 66 "st": "application/vnd.sailingtracker.track", // SailingTracker IANA: SailingTrackerIANA: SeeMail "sema": "application/vnd.sema", // Secured eMail IANA: Secured eMail "semd": "application/vnd.semd", // Secured eMail IANA: Secured eMail "semf": "application/vnd.semf", // Secured eMail IANA: Secured eMail "ifm": "application/vnd.shana.informed.formdata", // Shana Informed Filler IANA: Shana Informed "itp": "application/vnd.shana.informed.formtemplate", // Shana Informed Filler IANA: Shana "iif": "application/vnd.shana.informed.interchange", // Shana Informed Filler IANA: Shana "ipk": "application/vnd.shana.informed.package", // Shana Informed Filler IANA: Shana Informed "twd": "application/vnd.simtech-mindmapper", // SimTech MindMapper IANA: SimTech MindMapperIANA: SMAF File "teacher": "application/vnd.smart.teacher", // SMART Technologies Apps IANA: SMART Technologies "sdkm": "application/vnd.solent.sdkm+xml", // SudokuMagic IANA: SudokuMagic "dxp": "application/vnd.spotfire.dxp", // TIBCO Spotfire IANA: TIBCO Spotfire "sfs": "application/vnd.spotfire.sfs", // TIBCO Spotfire IANA: TIBCO Spotfire "sdc": "application/vnd.stardivision.calc", // StarOffice - Calc "sda": "application/vnd.stardivision.draw", // StarOffice - Draw "sdd": "application/vnd.stardivision.impress", // StarOffice - Impress "smf": "application/vnd.stardivision.math", // StarOffice - Math "sdw": "application/vnd.stardivision.writer", // StarOffice - Writer "sgl": "application/vnd.stardivision.writer-global", // StarOffice - Writer (Global) "sm": "application/vnd.stepmania.stepchart", // StepMania IANA: StepMania "sxc": "application/vnd.sun.xml.calc", // OpenOffice - Calc (Spreadsheet) Wikipedia: OpenOffice "stc": "application/vnd.sun.xml.calc.template", // OpenOffice - Calc Template (Spreadsheet) Wikipedia: OpenOffice "sxd": "application/vnd.sun.xml.draw", // OpenOffice - Draw (Graphics) Wikipedia: OpenOffice "std": "application/vnd.sun.xml.draw.template", // OpenOffice - Draw Template (Graphics) Wikipedia: OpenOffice "sxi": "application/vnd.sun.xml.impress", // OpenOffice - Impress (Presentation) Wikipedia: OpenOffice "sti": "application/vnd.sun.xml.impress.template", // OpenOffice - Impress Template (Presentation) Wikipedia: OpenOffice "sxm": "application/vnd.sun.xml.math", // OpenOffice - Math (Formula) Wikipedia: OpenOffice "sxw": "application/vnd.sun.xml.writer", // OpenOffice - Writer (Text - HTML) Wikipedia: OpenOffice "sxg": "application/vnd.sun.xml.writer.global", // OpenOffice - Writer (Text - HTML) Wikipedia: OpenOffice "stw": "application/vnd.sun.xml.writer.template", // OpenOffice - Writer Template (Text - HTML) Wikipedia: OpenOffice "sus": "application/vnd.sus-calendar", // ScheduleUs IANA: ScheduleUs "svd": "application/vnd.svd", // SourceView Document IANA: SourceView Document "sis": "application/vnd.symbian.install", // Symbian Install Package IANA: Symbian "xsm": "application/vnd.syncml+xml", // SyncML IANA: SyncML "bdm": "application/vnd.syncml.dm+wbxml", // SyncML - Device Management IANA: SyncML "xdm": "application/vnd.syncml.dm+xml", // SyncML - Device Management IANA: SyncML "tao": "application/vnd.tao.intent-module-archive", // Tao Intent IANA: Tao IntentIANA: MobileTV "tpt": "application/vnd.trid.tpt", // TRI Systems Config IANA: TRI Systems "mxs": "application/vnd.triscape.mxs", // Triscape Map Explorer IANA: Triscape Map ExplorerIANA: True BASIC "ufd": "application/vnd.ufdl", // Universal Forms Description Language IANA: Universal Forms Description "utz": "application/vnd.uiq.theme", // User Interface Quartz - Theme (Symbian) IANA: User Interface Quartz "umj": "application/vnd.umajin", // UMAJIN IANA: UMAJIN "unityweb": "application/vnd.unity", // Unity 3d IANA: Unity 3d "uoml": "application/vnd.uoml+xml", // Unique Object Markup Language IANA: UOML "vcx": "application/vnd.vcx", // VirtualCatalog IANA: VirtualCatalog "vsd": "application/vnd.visio", // Microsoft Visio IANA: Visio "vis": "application/vnd.visionary", // Visionary IANA: Visionary "vsf": "application/vnd.vsf", // Viewport+ IANA: Viewport+ "wbxml": "application/vnd.wap.wbxml", // WAP Binary XML (WBXML) IANA: WBXML "wmlc": "application/vnd.wap.wmlc", // Compiled Wireless Markup Language (WMLC) IANA: WMLC "wmlsc": "application/vnd.wap.wmlscriptc", // WMLScript IANA: WMLScript "wtb": "application/vnd.webturbo", // WebTurbo IANA: WebTurbo "nbp": "application/vnd.wolfram.player", // Mathematica Notebook Player IANA: Mathematica Notebook "wpd": "application/vnd.wordperfect", // Wordperfect IANA: Wordperfect "wqd": "application/vnd.wqd", // SundaHus WQ IANA: SundaHus WQ "stf": "application/vnd.wt.stf", // Worldtalk IANA: Worldtalk "xar": "application/vnd.xara", // CorelXARA IANA: CorelXARA "xfdl": "application/vnd.xfdl", // Extensible Forms Description Language IANA: Extensible Forms Description "hvd": "application/vnd.yamaha.hv-dic", // HV Voice Dictionary IANA: HV Voice DictionaryIANA: HV Script "hvp": "application/vnd.yamaha.hv-voice", // HV Voice Parameter IANA: HV Voice ParameterIANA: Open Score "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", // OSFPVG IANA: "saf": "application/vnd.yamaha.smaf-audio", // SMAF Audio IANA: SMAF Audio "spf": "application/vnd.yamaha.smaf-phrase", // SMAF Phrase IANA: SMAF Phrase "cmp": "application/vnd.yellowriver-custom-menu", // CustomMenu IANA: CustomMenuIANA: Z.U.L. "zaz": "application/vnd.zzazz.deck+xml", // Zzazz Deck IANA: Zzazz "vxml": "application/voicexml+xml", // VoiceXML RFC 4267 "wgt": "application/widget", // Widget Packaging and XML Configuration W3C Widget Packaging and XML "hlp": "application/winhlp", // WinHelp Wikipedia: WinHelp "wsdl": "application/wsdl+xml", // WSDL - Web Services Description Language W3C Web Service Description LanguageW3C Web Services Policy "7z": "application/x-7z-compressed", // 7-Zip Wikipedia: 7-Zip "abw": "application/x-abiword", // AbiWord Wikipedia: AbiWord "ace": "application/x-ace-compressed", // Ace Archive Wikipedia: ACE "aab": "application/x-authorware-bin", // Adobe (Macropedia) Authorware - Binary File Wikipedia: Authorware "aam": "application/x-authorware-map", // Adobe (Macropedia) Authorware - Map Wikipedia: Authorware "aas": "application/x-authorware-seg", // Adobe (Macropedia) Authorware - Segment File Wikipedia: Authorware "bcpio": "application/x-bcpio", // Binary CPIO Archive Wikipedia: cpio "torrent": "application/x-bittorrent", // BitTorrent Wikipedia: BitTorrent "bz": "application/x-bzip", // Bzip Archive Wikipedia: Bzip "bz2": "application/x-bzip2", // Bzip2 Archive Wikipedia: Bzip "vcd": "application/x-cdlink", // Video CD Wikipedia: Video CD "chat": "application/x-chat", // pIRCh Wikipedia: pIRCh "pgn": "application/x-chess-pgn", // Portable Game Notation (Chess Games) Wikipedia: Portable Game Notationb "cpio": "application/x-cpio", // CPIO Archive Wikipedia: cpio "csh": "application/x-csh", // C Shell Script Wikipedia: C Shell "deb": "application/x-debian-package", // Debian Package Wikipedia: Debian Package "dir": "application/x-director", // Adobe Shockwave Player Wikipedia: Adobe Shockwave Player "wad": "application/x-doom", // Doom Video Game Wikipedia: Doom WAD "ncx": "application/x-dtbncx+xml", // Navigation Control file for XML (for ePub) Wikipedia: EPUB "dtb": "application/x-dtbook+xml", // Digital Talking Book Wikipedia: EPUB "res": "application/x-dtbresource+xml", // Digital Talking Book - Resource File Digital Talking Book "dvi": "application/x-dvi", // Device Independent File Format (DVI) Wikipedia: DVI "bdf": "application/x-font-bdf", // Glyph Bitmap Distribution Format Wikipedia: Glyph Bitmap Distribution FormatWikipedia: Ghostscript "psf": "application/x-font-linux-psf", // PSF Fonts PSF Fonts "otf": "application/x-font-otf", // OpenType Font File OpenType Font File "pcf": "application/x-font-pcf", // Portable Compiled Format Wikipedia: Portable Compiled Format "snf": "application/x-font-snf", // Server Normal Format Wikipedia: Server Normal Format "ttf": "application/x-font-ttf", // TrueType Font Wikipedia: TrueType "pfa": "application/x-font-type1", // PostScript Fonts Wikipedia: PostScript Fonts "woff": "application/x-font-woff", // Web Open Font Format Wikipedia: Web Open Font Format "spl": "application/x-futuresplash", // FutureSplash Animator Wikipedia: FutureSplash Animator "gnumeric": "application/x-gnumeric", // Gnumeric Wikipedia: Gnumeric "gtar": "application/x-gtar", // GNU Tar Files GNU Tar "hdf": "application/x-hdf", // Hierarchical Data Format Wikipedia: Hierarchical Data Format "jnlp": "application/x-java-jnlp-file", // Java Network Launching Protocol Wikipedia: Java Web Start "latex": "application/x-latex", // LaTeX Wikipedia: LaTeX "prc": "application/x-mobipocket-ebook", // Mobipocket Wikipedia: Mobipocket "application": "application/x-ms-application", // Microsoft ClickOnce Wikipedia: ClickOnce "wmd": "application/x-ms-wmd", // Microsoft Windows Media Player Download Package Wikipedia: Windows Media Player "wmz": "application/x-ms-wmz", // Microsoft Windows Media Player Skin Package Wikipedia: Windows Media Player "xbap": "application/x-ms-xbap", // Microsoft XAML Browser Application Wikipedia: XAML Browser "mdb": "application/x-msaccess", // Microsoft Access Wikipedia: Microsoft Access "obd": "application/x-msbinder", // Microsoft Office Binder Wikipedia: Microsoft Shared Tools "crd": "application/x-mscardfile", // Microsoft Information Card Wikipedia: Information Card "clp": "application/x-msclip", // Microsoft Clipboard Clip Wikipedia: Clipboard "exe": "application/x-msdownload", // Microsoft Application Wikipedia: EXE "mvb": "application/x-msmediaview", // Microsoft MediaView "wmf": "application/x-msmetafile", // Microsoft Windows Metafile Wikipedia: Windows Metafile "mny": "application/x-msmoney", // Microsoft Money Wikipedia: Microsoft Money "pub": "application/x-mspublisher", // Microsoft Publisher Wikipedia: Microsoft Publisher "scd": "application/x-msschedule", // Microsoft Schedule+ Wikipedia: Microsoft Schedule Plus "trm": "application/x-msterminal", // Microsoft Windows Terminal Services Wikipedia: Terminal Server "wri": "application/x-mswrite", // Microsoft Wordpad Wikipedia: Wordpad "nc": "application/x-netcdf", // Network Common Data Form (NetCDF) Wikipedia: NetCDF "p12": "application/x-pkcs12", // PKCS #12 - Personal Information Exchange Syntax Standard RFC 2986 "p7b": "application/x-pkcs7-certificates", // PKCS #7 - Cryptographic Message Syntax Standard (Certificates) RFC 2986 "p7r": "application/x-pkcs7-certreqresp", // PKCS #7 - Cryptographic Message Syntax Standard (Certificate Request Response) RFC 2986 "rar": "application/x-rar-compressed", // RAR Archive Wikipedia: RAR "sh": "application/x-sh", // Bourne Shell Script Wikipedia: Bourne Shell "shar": "application/x-shar", // Shell Archive Wikipedia: Shell Archie "swf": "application/x-shockwave-flash", // Adobe Flash Wikipedia: Adobe Flash "xap": "application/x-silverlight-app", // Microsoft Silverlight Wikipedia: Silverlight "sit": "application/x-stuffit", // Stuffit Archive Wikipedia: Stuffit "sitx": "application/x-stuffitx", // Stuffit Archive Wikipedia: Stuffit "sv4cpio": "application/x-sv4cpio", // System V Release 4 CPIO Archive Wikipedia: pax "sv4crc": "application/x-sv4crc", // System V Release 4 CPIO Checksum Data Wikipedia: pax "tar": "application/x-tar", // Tar File (Tape Archive) Wikipedia: Tar "tcl": "application/x-tcl", // Tcl Script Wikipedia: Tcl "tex": "application/x-tex", // TeX Wikipedia: TeX "tfm": "application/x-tex-tfm", // TeX Font Metric Wikipedia: TeX Font Metric "texinfo": "application/x-texinfo", // GNU Texinfo Document Wikipedia: Texinfo "ustar": "application/x-ustar", // Ustar (Uniform Standard Tape Archive) Wikipedia: Ustar "src": "application/x-wais-source", // WAIS Source YoLinux "der": "application/x-x509-ca-cert", // X.509 Certificate Wikipedia: X.509 "fig": "application/x-xfig", // Xfig Wikipedia: Xfig "xpi": "application/x-xpinstall", // XPInstall - Mozilla Wikipedia: XPI "xdf": "application/xcap-diff+xml", // XML Configuration Access Protocol - XCAP Diff Wikipedia: XCAP "xenc": "application/xenc+xml", // XML Encryption Syntax and Processing W3C XML Encryption Syntax and Processing "xhtml": "application/xhtml+xml", // XHTML - The Extensible HyperText Markup Language W3C XHTML "xml": "application/xml", // XML - Extensible Markup Language W3C XML "dtd": "application/xml-dtd", // Document Type Definition W3C DTD "xop": "application/xop+xml", // XML-Binary Optimized Packaging W3C XOP "xslt": "application/xslt+xml", // XML Transformations W3C XSLT "xspf": "application/xspf+xml", // XSPF - XML Shareable Playlist Format XML Shareable Playlist Format "mxml": "application/xv+xml", // MXML Wikipedia: MXML "yang": "application/yang", // YANG Data Modeling Language Wikipedia: YANG "yin": "application/yin+xml", // YIN (YANG - XML) Wikipedia: YANG "zip": "application/zip", // Zip Archive Wikipedia: Zip "adp": "audio/adpcm", // Adaptive differential pulse-code modulation Wikipedia: ADPCM "au": "audio/basic", // Sun Audio - Au file format Wikipedia: Sun audio "mid": "audio/midi", // MIDI - Musical Instrument Digital Interface Wikipedia: MIDI "mp4a": "audio/mp4", // MPEG-4 Audio Wikipedia: MP4A "mpga": "audio/mpeg", // MPEG Audio Wikipedia: MPGA "oga": "audio/ogg", // Ogg Audio Wikipedia: Ogg "uva": "audio/vnd.dece.audio", // DECE Audio IANA: Dece Audio "eol": "audio/vnd.digital-winds", // Digital Winds Music IANA: Digital Winds "dra": "audio/vnd.dra", // DRA Audio IANA: DRA "dts": "audio/vnd.dts", // DTS Audio IANA: DTS "dtshd": "audio/vnd.dts.hd", // DTS High Definition Audio IANA: DTS HD "lvp": "audio/vnd.lucent.voice", // Lucent Voice IANA: Lucent Voice "pya": "audio/vnd.ms-playready.media.pya", // Microsoft PlayReady Ecosystem IANA: Microsoft PlayReady "ecelp4800": "audio/vnd.nuera.ecelp4800", // Nuera ECELP 4800 IANA: ECELP 4800 "ecelp7470": "audio/vnd.nuera.ecelp7470", // Nuera ECELP 7470 IANA: ECELP 7470 "ecelp9600": "audio/vnd.nuera.ecelp9600", // Nuera ECELP 9600 IANA: ECELP 9600 "rip": "audio/vnd.rip", // Hit'n'Mix IANA: Hit'n'Mix "weba": "audio/webm", // Open Web Media Project - Audio WebM Project "aac": "audio/x-aac", // Advanced Audio Coding (AAC) Wikipedia: AAC "aif": "audio/x-aiff", // Audio Interchange File Format Wikipedia: Audio Interchange File FormatWikipedia: M3U "wax": "audio/x-ms-wax", // Microsoft Windows Media Audio Redirector Windows Media MetafilesWikipedia: Windows Media Audio "ram": "audio/x-pn-realaudio", // Real Audio Sound Wikipedia: RealPlayer "rmp": "audio/x-pn-realaudio-plugin", // Real Audio Sound Wikipedia: RealPlayer "wav": "audio/x-wav", // Waveform Audio File Format (WAV) Wikipedia: WAV "cdx": "chemical/x-cdx", // ChemDraw eXchange file ChemDraw eXchange file "cif": "chemical/x-cif", // Crystallographic Interchange Format Crystallographic Interchange Format "cmdf": "chemical/x-cmdf", // CrystalMaker Data Format CrystalMaker Data Format "cml": "chemical/x-cml", // Chemical Markup Language Wikipedia: Chemical Markup Language "csml": "chemical/x-csml", // Chemical Style Markup Language Wikipedia: Chemical Style Markup Language "xyz": "chemical/x-xyz", // XYZ File Format Wikipedia: XYZ File Format "bmp": "image/bmp", // Bitmap Image File Wikipedia: BMP File Format "cgm": "image/cgm", // Computer Graphics Metafile Wikipedia: Computer Graphics Metafile "g3": "image/g3fax", // G3 Fax Image Wikipedia: G3 Fax Image "gif": "image/gif", // Graphics Interchange Format Wikipedia: Graphics Interchange Format "ief": "image/ief", // Image Exchange Format RFC 1314 "jpeg": "image/jpeg", // JPEG Image RFC 1314 "jpg": "image/jpeg", // JPEG Image RFC 1314 "ktx": "image/ktx", // OpenGL Textures (KTX) KTX File Format "png": "image/png", // Portable Network Graphics (PNG) RFC 2083 "btif": "image/prs.btif", // BTIF IANA: BTIF "svg": "image/svg+xml", // Scalable Vector Graphics (SVG) Wikipedia: SVG "tiff": "image/tiff", // Tagged Image File Format Wikipedia: TIFF "psd": "image/vnd.adobe.photoshop", // Photoshop Document Wikipedia: Photoshop Document "uvi": "image/vnd.dece.graphic", // DECE Graphic IANA: DECE Graphic "sub": "image/vnd.dvb.subtitle", // Close Captioning - Subtitle Wikipedia: Closed Captioning "djvu": "image/vnd.djvu", // DjVu Wikipedia: DjVu "dwg": "image/vnd.dwg", // DWG Drawing Wikipedia: DWG "dxf": "image/vnd.dxf", // AutoCAD DXF Wikipedia: AutoCAD DXF "fbs": "image/vnd.fastbidsheet", // FastBid Sheet IANA: FastBid Sheet "fpx": "image/vnd.fpx", // FlashPix IANA: FPX "fst": "image/vnd.fst", // FAST Search & Transfer ASA IANA: FAST Search & Transfer ASA "mmr": "image/vnd.fujixerox.edmics-mmr", // EDMICS 2000 IANA: EDMICS 2000 "rlc": "image/vnd.fujixerox.edmics-rlc", // EDMICS 2000 IANA: EDMICS 2000 "mdi": "image/vnd.ms-modi", // Microsoft Document Imaging Format Wikipedia: Microsoft Document Image FormatIANA: FPX "wbmp": "image/vnd.wap.wbmp", // WAP Bitamp (WBMP) IANA: WBMP "xif": "image/vnd.xiff", // eXtended Image File Format (XIFF) IANA: XIFF "webp": "image/webp", // WebP Image Wikipedia: WebP "ras": "image/x-cmu-raster", // CMU Image "cmx": "image/x-cmx", // Corel Metafile Exchange (CMX) Wikipedia: CorelDRAW "fh": "image/x-freehand", // FreeHand MX Wikipedia: Macromedia Freehand "ico": "image/x-icon", // Icon Image Wikipedia: ICO File Format "pcx": "image/x-pcx", // PCX Image Wikipedia: PCX "pic": "image/x-pict", // PICT Image Wikipedia: PICT "pnm": "image/x-portable-anymap", // Portable Anymap Image Wikipedia: Netpbm Format "pbm": "image/x-portable-bitmap", // Portable Bitmap Format Wikipedia: Netpbm Format "pgm": "image/x-portable-graymap", // Portable Graymap Format Wikipedia: Netpbm Format "ppm": "image/x-portable-pixmap", // Portable Pixmap Format Wikipedia: Netpbm Format "rgb": "image/x-rgb", // Silicon Graphics RGB Bitmap RGB Image Format "xbm": "image/x-xbitmap", // X BitMap Wikipedia: X BitMap "xpm": "image/x-xpixmap", // X PixMap Wikipedia: X PixMap "xwd": "image/x-xwindowdump", // X Window Dump Wikipedia: X Window Dump "eml": "message/rfc822", // Email Message RFC 2822 "igs": "model/iges", // Initial Graphics Exchange Specification (IGES) Wikipedia: IGES "msh": "model/mesh", // Mesh Data Type RFC 2077 "dae": "model/vnd.collada+xml", // COLLADA IANA: COLLADA "dwf": "model/vnd.dwf", // Autodesk Design Web Format (DWF) Wikipedia: Design Web Format "gdl": "model/vnd.gdl", // Geometric Description Language (GDL) IANA: GDL "gtw": "model/vnd.gtw", // Gen-Trix Studio IANA: GTW "mts": "model/vnd.mts", // Virtue MTS IANA: MTS "vtu": "model/vnd.vtu", // Virtue VTU IANA: VTU "wrl": "model/vrml", // Virtual Reality Modeling Language Wikipedia: VRML "ics": "text/calendar", // iCalendar Wikipedia: iCalendar "css": "text/css", // Cascading Style Sheets (CSS) Wikipedia: CSS "csv": "text/csv", // Comma-Seperated Values Wikipedia: CSV "html": "text/html", // HyperText Markup Language (HTML) Wikipedia: HTML "n3": "text/n3", // Notation3 Wikipedia: Notation3 "txt": "text/plain", // Text File Wikipedia: Text File "dsc": "text/prs.lines.tag", // PRS Lines Tag IANA: PRS Lines Tag "rtx": "text/richtext", // Rich Text Format (RTF) Wikipedia: Rich Text Format "sgml": "text/sgml", // Standard Generalized Markup Language (SGML) Wikipedia: SGML "tsv": "text/tab-separated-values", // Tab Seperated Values Wikipedia: TSV "t": "text/troff", // troff Wikipedia: troff "ttl": "text/turtle", // Turtle (Terse RDF Triple Language) Wikipedia: Turtle "uri": "text/uri-list", // URI Resolution Services RFC 2483 "curl": "text/vnd.curl", // Curl - Applet Curl AppletCurl Detached "scurl": "text/vnd.curl.scurl", // Curl - Source Code Curl Source "mcurl": "text/vnd.curl.mcurl", // Curl - Manifest File Curl Manifest "fly": "text/vnd.fly", // mod_fly / fly.cgi IANA: Fly "flx": "text/vnd.fmi.flexstor", // FLEXSTOR IANA: FLEXSTOR "gv": "text/vnd.graphviz", // Graphviz IANA: Graphviz "3dml": "text/vnd.in3d.3dml", // In3D - 3DML IANA: In3D "spot": "text/vnd.in3d.spot", // In3D - 3DML IANA: In3D "jad": "text/vnd.sun.j2me.app-descriptor", // J2ME app Descriptor IANA: J2ME app DescriptorWikipedia: WML "wmls": "text/vnd.wap.wmlscript", // Wireless Markup Language Script (WMLScript) Wikipedia: WMLScript "s": "text/x-asm", // Assembler Source File Wikipedia: Assembly "c": "text/x-c", // C Source File Wikipedia: C Programming Language "f": "text/x-fortran", // Fortran Source File Wikipedia: Fortran "p": "text/x-pascal", // Pascal Source File Wikipedia: Pascal "java": "text/x-java-source,java", // Java Source File Wikipedia: Java "etx": "text/x-setext", // Setext Wikipedia: Setext "uu": "text/x-uuencode", // UUEncode Wikipedia: UUEncode "vcs": "text/x-vcalendar", // vCalendar Wikipedia: vCalendar "vcf": "text/x-vcard", // vCard Wikipedia: vCard "3gp": "video/3gpp", // 3GP Wikipedia: 3GP "3g2": "video/3gpp2", // 3GP2 Wikipedia: 3G2 "h261": "video/h261", // H.261 Wikipedia: H.261 "h263": "video/h263", // H.263 Wikipedia: H.263 "h264": "video/h264", // H.264 Wikipedia: H.264 "jpgv": "video/jpeg", // JPGVideo RFC 3555 "jpm": "video/jpm", // JPEG 2000 Compound Image File Format IANA: JPM "mj2": "video/mj2", // Motion JPEG 2000 IANA: MJ2 "mp4": "video/mp4", // MPEG-4 Video Wikipedia: MP4 "mpeg": "video/mpeg", // MPEG Video Wikipedia: MPEG "ogv": "video/ogg", // Ogg Video Wikipedia: Ogg "qt": "video/quicktime", // Quicktime Video Wikipedia: Quicktime "uvh": "video/vnd.dece.hd", // DECE High Definition Video IANA: DECE HD Video "uvm": "video/vnd.dece.mobile", // DECE Mobile Video IANA: DECE Mobile Video "uvp": "video/vnd.dece.pd", // DECE PD Video IANA: DECE PD Video "uvs": "video/vnd.dece.sd", // DECE SD Video IANA: DECE SD Video "uvv": "video/vnd.dece.video", // DECE Video IANA: DECE Video "fvt": "video/vnd.fvt", // FAST Search & Transfer ASA IANA: FVT "mxu": "video/vnd.mpegurl", // MPEG Url IANA: MPEG Url "pyv": "video/vnd.ms-playready.media.pyv", // Microsoft PlayReady Ecosystem Video IANA: Microsoft PlayReady "uvu": "video/vnd.uvvu.mp4", // DECE MP4 IANA: DECE MP4 "viv": "video/vnd.vivo", // Vivo IANA: Vivo "webm": "video/webm", // Open Web Media Project - Video WebM Project "f4v": "video/x-f4v", // Flash Video Wikipedia: Flash Video "fli": "video/x-fli", // FLI/FLC Animation Format FLI/FLC Animation Format "flv": "video/x-flv", // Flash Video Wikipedia: Flash Video "m4v": "video/x-m4v", // M4v Wikipedia: M4v "asf": "video/x-ms-asf", // Microsoft Advanced Systems Format (ASF) Wikipedia: Advanced Systems Format (ASF) "wm": "video/x-ms-wm", // Microsoft Windows Media Wikipedia: Advanced Systems Format (ASF) "wmv": "video/x-ms-wmv", // Microsoft Windows Media Video Wikipedia: Advanced Systems Format (ASF) "wmx": "video/x-ms-wmx", // Microsoft Windows Media Audio/Video Playlist Wikipedia: Advanced Systems Format (ASF) "wvx": "video/x-ms-wvx", // Microsoft Windows Media Video Playlist Wikipedia: Advanced Systems Format (ASF) "avi": "video/x-msvideo", // Audio Video Interleave (AVI) Wikipedia: AVI "movie": "video/x-sgi-movie", // SGI Movie SGI Facts "ice": "x-conference/x-cooltalk", // CoolTalk Wikipedia: CoolTalk "par": "text/plain-bas" // BAS Partitur Format Phonetik BAS ]
// // APIService.swift // Stormpath // // Created by Adis on 18/11/15. // Copyright © 2015 Stormpath. All rights reserved. // import Foundation final class APIService: NSObject { weak var stormpath: Stormpath! init(withStormpath stormpath: Stormpath) { self.stormpath = stormpath } // MARK: Registration func register(newAccount account: RegistrationModel, completionHandler: StormpathAccountCallback?) { let registerURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.registerEndpoint) let requestManager = RegistrationAPIRequestManager(withURL: registerURL, newAccount: account) { (account, error) -> Void in completionHandler?(account, error) } requestManager.begin() } // MARK: Login func login(username: String, password: String, completionHandler: StormpathSuccessCallback?) { let oauthURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.oauthEndpoint) let requestManager = OAuthAPIRequestManager(withURL: oauthURL, username: username, password: password) { (accessToken, refreshToken, error) -> Void in guard let accessToken = accessToken where error == nil else { completionHandler?(false, error) return } self.stormpath.keychain.accessToken = accessToken if refreshToken != nil { self.stormpath.keychain.refreshToken = refreshToken } completionHandler?(true, nil) } requestManager.begin() } // MARK: Access token refresh func refreshAccessToken(completionHandler: StormpathSuccessCallback?) { let oauthURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.oauthEndpoint) guard let refreshToken = stormpath.refreshToken else { let error = NSError(domain: oauthURL.absoluteString, code: 400, userInfo: [NSLocalizedDescriptionKey: "Refresh token not found. Have you logged in yet?"]) Logger.logError(error) dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler?(false, error) }) return } let requestManager = OAuthAPIRequestManager(withURL: oauthURL, refreshToken: refreshToken) { (accessToken, refreshToken, error) -> Void in guard let accessToken = accessToken where error == nil else { completionHandler?(false, error) return } self.stormpath.accessToken = accessToken self.stormpath.refreshToken = refreshToken completionHandler?(true, nil) } requestManager.begin() } // MARK: Account data func me(completionHandler: StormpathAccountCallback?) { let meURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.meEndpoint) guard let accessToken = stormpath.accessToken else { let error = NSError(domain: meURL.absoluteString, code: 401, userInfo: [NSLocalizedDescriptionKey: "Refresh token not found. Have you logged in yet?"]) Logger.logError(error) dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler?(nil, error) }) return } let requestManager = MeAPIRequestManager(withURL: meURL, accessToken: accessToken) { (account, error) -> Void in if error?.code == 401 { //Refresh access token & retry self.stormpath.refreshAccessToken({ (success, error) -> Void in guard error == nil else { completionHandler?(nil, error) return } self.stormpath.me(completionHandler) }) } else { completionHandler?(account, error) } } requestManager.begin() } // MARK: Logout func logout() { let logoutURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.logoutEndpoint) let request = NSMutableURLRequest(URL: logoutURL) request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "GET" Logger.logRequest(request) // Regardless of how the API calls goes, we can logout the user locally stormpath.accessToken = nil stormpath.refreshToken = nil // TODO: Hit the API to delete the access token, because this literally does nothing right now. } // MARK: Forgot password func resetPassword(email: String, completionHandler: StormpathSuccessCallback?) { let resetPasswordURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.forgotPasswordEndpoint) let requestManager = ResetPasswordAPIRequestManager(withURL: resetPasswordURL, email: email, callback: { (error) -> Void in completionHandler?(error == nil, error) }) requestManager.begin() } } only retries once for /me // // APIService.swift // Stormpath // // Created by Adis on 18/11/15. // Copyright © 2015 Stormpath. All rights reserved. // import Foundation final class APIService: NSObject { weak var stormpath: Stormpath! init(withStormpath stormpath: Stormpath) { self.stormpath = stormpath } // MARK: Registration func register(newAccount account: RegistrationModel, completionHandler: StormpathAccountCallback?) { let registerURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.registerEndpoint) let requestManager = RegistrationAPIRequestManager(withURL: registerURL, newAccount: account) { (account, error) -> Void in completionHandler?(account, error) } requestManager.begin() } // MARK: Login func login(username: String, password: String, completionHandler: StormpathSuccessCallback?) { let oauthURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.oauthEndpoint) let requestManager = OAuthAPIRequestManager(withURL: oauthURL, username: username, password: password) { (accessToken, refreshToken, error) -> Void in guard let accessToken = accessToken where error == nil else { completionHandler?(false, error) return } self.stormpath.keychain.accessToken = accessToken if refreshToken != nil { self.stormpath.keychain.refreshToken = refreshToken } completionHandler?(true, nil) } requestManager.begin() } // MARK: Access token refresh func refreshAccessToken(completionHandler: StormpathSuccessCallback?) { let oauthURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.oauthEndpoint) guard let refreshToken = stormpath.refreshToken else { let error = NSError(domain: oauthURL.absoluteString, code: 400, userInfo: [NSLocalizedDescriptionKey: "Refresh token not found. Have you logged in yet?"]) Logger.logError(error) dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler?(false, error) }) return } let requestManager = OAuthAPIRequestManager(withURL: oauthURL, refreshToken: refreshToken) { (accessToken, refreshToken, error) -> Void in guard let accessToken = accessToken where error == nil else { completionHandler?(false, error) return } self.stormpath.accessToken = accessToken self.stormpath.refreshToken = refreshToken completionHandler?(true, nil) } requestManager.begin() } // MARK: Account data func me(completionHandler: StormpathAccountCallback?) { let meURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.meEndpoint) guard let accessToken = stormpath.accessToken else { let error = NSError(domain: meURL.absoluteString, code: 401, userInfo: [NSLocalizedDescriptionKey: "Refresh token not found. Have you logged in yet?"]) Logger.logError(error) dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler?(nil, error) }) return } let requestManager = MeAPIRequestManager(withURL: meURL, accessToken: accessToken) { (account, error) -> Void in if error?.code == 401 { //Refresh access token & retry self.stormpath.refreshAccessToken({ (success, error) -> Void in guard error == nil else { completionHandler?(nil, error) return } let retryRequestManager = MeAPIRequestManager(withURL: meURL, accessToken: accessToken, callback: { (account, error) -> Void in completionHandler?(account, error) }) retryRequestManager.begin() }) } else { completionHandler?(account, error) } } requestManager.begin() } // MARK: Logout func logout() { let logoutURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.logoutEndpoint) let request = NSMutableURLRequest(URL: logoutURL) request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "GET" Logger.logRequest(request) // Regardless of how the API calls goes, we can logout the user locally stormpath.accessToken = nil stormpath.refreshToken = nil // TODO: Hit the API to delete the access token, because this literally does nothing right now. } // MARK: Forgot password func resetPassword(email: String, completionHandler: StormpathSuccessCallback?) { let resetPasswordURL = stormpath.configuration.APIURL.URLByAppendingPathComponent(stormpath.configuration.forgotPasswordEndpoint) let requestManager = ResetPasswordAPIRequestManager(withURL: resetPasswordURL, email: email, callback: { (error) -> Void in completionHandler?(error == nil, error) }) requestManager.begin() } }
// // CollectionViewLayout.swift // SwiftBoard // // Created by Matt Daw on 2014-09-15. // Copyright (c) 2014 Matt Daw. All rights reserved. // import UIKit class CollectionViewLayout: UICollectionViewLayout { let itemSize = CGFloat(96) var itemFrames: [CGRect] = [] var numberOfItems = 0 var zoomToIndexPath: NSIndexPath? override func collectionViewContentSize() -> CGSize { if let cv = collectionView { return cv.bounds.size } else { return CGSizeZero } } override func prepareLayout() { if collectionView == nil { return } let myCollectionView = collectionView! let availableHeight = myCollectionView.bounds.height let availableWidth = myCollectionView.bounds.width let itemsPerRow = Int(floor(availableWidth / itemSize)) var top = CGFloat(0) var left = CGFloat(0) var column = 1 var zoomedSize = itemSize var leftOffset = CGFloat(0) if let zoomIndex = zoomToIndexPath { zoomedSize = availableWidth - 10 } itemFrames = [] numberOfItems = myCollectionView.numberOfItemsInSection(0) for itemIndex in 0..<numberOfItems { let itemFrame = CGRect(x: left, y: top, width: zoomedSize, height: zoomedSize) itemFrames.append(itemFrame) column += 1 if column > itemsPerRow { column = 1 left = CGFloat(0) top += zoomedSize } else { left += zoomedSize } } if let zoomIndex = zoomToIndexPath { var frame = itemFrames[zoomIndex.item] var transform = CGAffineTransformMakeTranslation(-frame.origin.x, -frame.origin.y) transform = CGAffineTransformTranslate(transform, (availableWidth - zoomedSize) / 2, (availableHeight - zoomedSize) / 2) for itemIndex in 0..<numberOfItems { itemFrames[itemIndex] = CGRectApplyAffineTransform(itemFrames[itemIndex], transform) } } } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var attributes: [UICollectionViewLayoutAttributes] = [] if let myCollectionView = collectionView { for itemIndex in 0..<numberOfItems { let indexPath = NSIndexPath(forItem: itemIndex, inSection: 0) attributes.append(layoutAttributesForItemAtIndexPath(indexPath)) } } return attributes; } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let itemAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) itemAttributes.frame = itemFrames[indexPath.item] return itemAttributes } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } } More work on zooming // // CollectionViewLayout.swift // SwiftBoard // // Created by Matt Daw on 2014-09-15. // Copyright (c) 2014 Matt Daw. All rights reserved. // import UIKit class CollectionViewLayout: UICollectionViewLayout { let itemSize = CGFloat(96) var itemFrames: [CGRect] = [] var numberOfItems = 0 var zoomToIndexPath: NSIndexPath? override func collectionViewContentSize() -> CGSize { if let cv = collectionView { return cv.bounds.size } else { return CGSizeZero } } override func prepareLayout() { if collectionView == nil { return } let myCollectionView = collectionView! let availableHeight = myCollectionView.bounds.height let availableWidth = myCollectionView.bounds.width let itemsPerRow = Int(floor(availableWidth / itemSize)) var top = CGFloat(0) var left = CGFloat(0) var column = 1 var zoomedSize = itemSize var rowOffset = zoomedSize if let zoomIndex = zoomToIndexPath { zoomedSize = availableWidth - 10 rowOffset = zoomedSize + (availableHeight - zoomedSize) / 2 } itemFrames = [] numberOfItems = myCollectionView.numberOfItemsInSection(0) for itemIndex in 0..<numberOfItems { let itemFrame = CGRect(x: left, y: top, width: zoomedSize, height: zoomedSize) itemFrames.append(itemFrame) column += 1 if column > itemsPerRow { column = 1 left = CGFloat(0) top += rowOffset } else { left += zoomedSize } } if let zoomIndex = zoomToIndexPath { var frame = itemFrames[zoomIndex.item] var transform = CGAffineTransformMakeTranslation(-frame.origin.x, -frame.origin.y) transform = CGAffineTransformTranslate(transform, (availableWidth - zoomedSize) / 2, (availableHeight - zoomedSize) / 2) for itemIndex in 0..<numberOfItems { itemFrames[itemIndex] = CGRectApplyAffineTransform(itemFrames[itemIndex], transform) } } } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var attributes: [UICollectionViewLayoutAttributes] = [] if let myCollectionView = collectionView { for itemIndex in 0..<numberOfItems { let indexPath = NSIndexPath(forItem: itemIndex, inSection: 0) attributes.append(layoutAttributesForItemAtIndexPath(indexPath)) } } return attributes; } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let itemAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) itemAttributes.frame = itemFrames[indexPath.item] return itemAttributes } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } }
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where a:a{var d{class a{func g:d=var d=b Mark as duplicate.
// // ShiftImport.swift // masamon // // Created by 岩見建汰 on 2015/11/04. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit class ShiftImport: UIViewController{ let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //AppDelegateのインスタンスを取得 let notificationCenter = NSNotificationCenter.defaultCenter() @IBOutlet weak var Label: UILabel! override func viewDidLoad() { super.viewDidLoad() //アプリがアクティブになったとき notificationCenter.addObserver(self,selector: "ShiftImportViewActived",name:UIApplicationDidBecomeActiveNotification,object: nil) if(DBmethod().FilePathTmpGet().isEmpty){ Label.text = "nil" }else{ Label.text = DBmethod().FilePathTmpGet() } let rightBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "取り込む", style: UIBarButtonItemStyle.Plain, target: self, action: "xlsximport:") let leftBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "キャンセル", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel:") // let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) self.navigationItem.setRightBarButtonItems([rightBarButtonItem], animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func ShiftImportViewActived(){ Label.text = DBmethod().FilePathTmpGet() } func xlsximport(sender: UIButton){ } func cancel(sender: UIButton){ } } いらない記述を削除 // // ShiftImport.swift // masamon // // Created by 岩見建汰 on 2015/11/04. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit class ShiftImport: UIViewController{ let notificationCenter = NSNotificationCenter.defaultCenter() @IBOutlet weak var Label: UILabel! override func viewDidLoad() { super.viewDidLoad() //アプリがアクティブになったとき notificationCenter.addObserver(self,selector: "ShiftImportViewActived",name:UIApplicationDidBecomeActiveNotification,object: nil) if(DBmethod().FilePathTmpGet().isEmpty){ Label.text = "nil" }else{ Label.text = DBmethod().FilePathTmpGet() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func ShiftImportViewActived(){ Label.text = DBmethod().FilePathTmpGet() } func xlsximport(sender: UIButton){ } func cancel(sender: UIButton){ } }
// // ShiftRegister.swift // masamon // // Created by 岩見建汰 on 2015/12/06. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit import RealmSwift class Shiftmethod: UIViewController { //cellの列(日付が記載されている範囲) let cellrow = ["G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ"] let holiday = ["公","夏","有"] //表に記載される休暇日 let staffnumber = 27 //TODO: 仮に設定。あとで入力項目を設ける let mark = "F" var number = 6 // func ShiftDBOneCoursRegist(importname: String, importpath: String, update: Bool){ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var date = 11 let staffcellposition = self.StaffCellPositionGet() //スタッフの名前が記載されているセル場所 ex.)F8,F9 var shiftdetailarray = List<ShiftDetailDB>() var shiftdetailrecordcount = DBmethod().DBRecordCount(ShiftDetailDB) //30日分繰り返すループ for(var i = 0; i < 30; i++){ let shiftdb = ShiftDB() let shiftdetaildb = ShiftDetailDB() if(update){ shiftdb.id = DBmethod().SearchShiftDB(importname).id //取り込みが上書きの場合は使われているidをそのまま使う let AAA = DBmethod().SearchShiftDB(importname) let BBB = ShiftDetailDB() BBB.id = AAA.shiftdetail[i].id BBB.date = AAA.shiftdetail[i].date BBB.staff = "BBB" DBmethod().AddandUpdate(BBB, update: true) }else{ shiftdb.id = DBmethod().DBRecordCount(ShiftDetailDB)/30 //新規の場合はレコードの数を割ったidを使う shiftdb.shiftimportname = importname shiftdb.shiftimportpath = importpath shiftdetaildb.id = shiftdetailrecordcount shiftdetailrecordcount++ shiftdetaildb.date = date shiftdetaildb.shiftDBrelationship = shiftdb shiftdetaildb.staff = ABS(i, staffcellpositionarray: staffcellposition, worksheet: worksheet) //シフトが11日〜来月10日のため日付のリセットを行うか判断 if(date < 30){ date++ }else{ date = 1 } //すでに記録してあるListを取得して後ろに現在の記録を追加する for(var i = 0; i < shiftdetailarray.count; i++){ shiftdb.shiftdetail.append(shiftdetailarray[i]) } shiftdb.shiftdetail.append(shiftdetaildb) let ID = shiftdb.id DBmethod().AddandUpdate(shiftdb, update: true) DBmethod().AddandUpdate(shiftdetaildb, update: true) shiftdetailarray = self.ShiftDBRelationArrayGet(ID) } } } // //表中にあるスタッフ名の場所を返す func StaffCellPositionGet() -> Array<String>{ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var array:[String] = [] while(true){ let Fcell: String = worksheet.cellForCellReference(mark+String(number)).stringValue() if(Fcell.isEmpty){ //セルが空なら進めるだけ number++ }else{ array.append(mark+String(number)) number++ } if(staffnumber == array.count){ //設定したスタッフ人数と取り込み数が一致したら break } } return array } //ShiftDBのリレーションシップ配列を返す func ShiftDBRelationArrayGet(id: Int) -> List<ShiftDetailDB>{ var list = List<ShiftDetailDB>() let realm = try! Realm() list = realm.objects(ShiftDB).filter("id = %@", id)[0].shiftdetail return list } //入力したユーザ名の月給を計算して結果を返す func UserMonthlySalaryRegist(importname: String){ var usershift:[String] = [] let username = DBmethod().UserNameGet() let staffcellposition = self.StaffCellPositionGet() let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var userposition = "" //F列からユーザ名と合致する箇所を探す for(var i = 0; i < staffnumber; i++){ let nowcell: String = worksheet.cellForCellReference(staffcellposition[i]).stringValue() if(nowcell == username){ userposition = staffcellposition[i] break } } //1クール分行う for(var i = 0; i < 30; i++){ let replaceday = userposition.stringByReplacingOccurrencesOfString("F", withString: cellrow[i]) let dayshift: String = worksheet.cellForCellReference(replaceday).stringValue() if(holiday.contains(dayshift) == false){ //holiday以外なら usershift.append(dayshift) } } //月給の計算をする var shiftsystem = ShiftSystem() var monthlysalary = 0.0 let houlypayrecord = DBmethod().HourlyPayRecordGet() for(var i = 0; i < usershift.count; i++){ shiftsystem = DBmethod().SearchShiftSystem(usershift[i]) if(shiftsystem.endtime <= houlypayrecord[0].timeto){ monthlysalary = monthlysalary + (shiftsystem.endtime - shiftsystem.starttime - 1) * Double(houlypayrecord[0].pay) }else{ //22時以降の給与を先に計算 let latertime = shiftsystem.endtime - houlypayrecord[0].timeto monthlysalary = monthlysalary + latertime * Double(houlypayrecord[1].pay) monthlysalary = monthlysalary + (shiftsystem.endtime - latertime - shiftsystem.starttime - 1) * Double(houlypayrecord[0].pay) } } print(monthlysalary) //TODO: データベースへ記録 // let realm = try! Realm() // let todos = realm.objects(ShiftDB).filter("shiftimportname = %@",importname) // todos.setValue(monthlysalary, forKey: "saraly") // realm.create(ShiftDB.self, value: ["shiftimportname": importname,"saraly": monthlysalary], update: true) // let AAA = ShiftDB() // AAA.id = 1 // AAA.shiftimportname = importname // AAA.saraly = Int(monthlysalary) // DBmethod().AddandUpdate(AAA, update: true) } //その日のシフトを全員分調べて出勤者だけ列挙する。 /*引数の説明。 day => その日の日付 staffcellpositionarray =>スタッフのセル位置を配列で記録したもの worksheet =>対象となるエクセルファイルのワークシート */ func ABS(day: Int, staffcellpositionarray: Array<String>, worksheet: BRAWorksheet) -> String{ var staffstring = "" for(var i = 0; i < staffnumber; i++){ let nowstaff = staffcellpositionarray[i] let replaceday = nowstaff.stringByReplacingOccurrencesOfString("F", withString: cellrow[day]) let dayshift: String = worksheet.cellForCellReference(replaceday).stringValue() let staffname: String = worksheet.cellForCellReference(nowstaff).stringValue() if(holiday.contains(dayshift) == false){ //Holiday以外なら記録 staffstring = staffstring + staffname + ":" + dayshift + "," } } return staffstring } } 関数名の変更 // // ShiftRegister.swift // masamon // // Created by 岩見建汰 on 2015/12/06. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit import RealmSwift class Shiftmethod: UIViewController { //cellの列(日付が記載されている範囲) let cellrow = ["G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ"] let holiday = ["公","夏","有"] //表に記載される休暇日 let staffnumber = 27 //TODO: 仮に設定。あとで入力項目を設ける let mark = "F" var number = 6 // func ShiftDBOneCoursRegist(importname: String, importpath: String, update: Bool){ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var date = 11 let staffcellposition = self.StaffCellPositionGet() //スタッフの名前が記載されているセル場所 ex.)F8,F9 var shiftdetailarray = List<ShiftDetailDB>() var shiftdetailrecordcount = DBmethod().DBRecordCount(ShiftDetailDB) //30日分繰り返すループ for(var i = 0; i < 30; i++){ let shiftdb = ShiftDB() let shiftdetaildb = ShiftDetailDB() if(update){ shiftdb.id = DBmethod().SearchShiftDB(importname).id //取り込みが上書きの場合は使われているidをそのまま使う let AAA = DBmethod().SearchShiftDB(importname) let BBB = ShiftDetailDB() BBB.id = AAA.shiftdetail[i].id BBB.date = AAA.shiftdetail[i].date BBB.staff = "BBB" DBmethod().AddandUpdate(BBB, update: true) }else{ shiftdb.id = DBmethod().DBRecordCount(ShiftDetailDB)/30 //新規の場合はレコードの数を割ったidを使う shiftdb.shiftimportname = importname shiftdb.shiftimportpath = importpath shiftdetaildb.id = shiftdetailrecordcount shiftdetailrecordcount++ shiftdetaildb.date = date shiftdetaildb.shiftDBrelationship = shiftdb shiftdetaildb.staff = TheDayStaffAttendance(i, staffcellpositionarray: staffcellposition, worksheet: worksheet) //シフトが11日〜来月10日のため日付のリセットを行うか判断 if(date < 30){ date++ }else{ date = 1 } //すでに記録してあるListを取得して後ろに現在の記録を追加する for(var i = 0; i < shiftdetailarray.count; i++){ shiftdb.shiftdetail.append(shiftdetailarray[i]) } shiftdb.shiftdetail.append(shiftdetaildb) let ID = shiftdb.id DBmethod().AddandUpdate(shiftdb, update: true) DBmethod().AddandUpdate(shiftdetaildb, update: true) shiftdetailarray = self.ShiftDBRelationArrayGet(ID) } } } // //表中にあるスタッフ名の場所を返す func StaffCellPositionGet() -> Array<String>{ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var array:[String] = [] while(true){ let Fcell: String = worksheet.cellForCellReference(mark+String(number)).stringValue() if(Fcell.isEmpty){ //セルが空なら進めるだけ number++ }else{ array.append(mark+String(number)) number++ } if(staffnumber == array.count){ //設定したスタッフ人数と取り込み数が一致したら break } } return array } //ShiftDBのリレーションシップ配列を返す func ShiftDBRelationArrayGet(id: Int) -> List<ShiftDetailDB>{ var list = List<ShiftDetailDB>() let realm = try! Realm() list = realm.objects(ShiftDB).filter("id = %@", id)[0].shiftdetail return list } //入力したユーザ名の月給を計算して結果を返す func UserMonthlySalaryRegist(importname: String){ var usershift:[String] = [] let username = DBmethod().UserNameGet() let staffcellposition = self.StaffCellPositionGet() let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var userposition = "" //F列からユーザ名と合致する箇所を探す for(var i = 0; i < staffnumber; i++){ let nowcell: String = worksheet.cellForCellReference(staffcellposition[i]).stringValue() if(nowcell == username){ userposition = staffcellposition[i] break } } //1クール分行う for(var i = 0; i < 30; i++){ let replaceday = userposition.stringByReplacingOccurrencesOfString("F", withString: cellrow[i]) let dayshift: String = worksheet.cellForCellReference(replaceday).stringValue() if(holiday.contains(dayshift) == false){ //holiday以外なら usershift.append(dayshift) } } //月給の計算をする var shiftsystem = ShiftSystem() var monthlysalary = 0.0 let houlypayrecord = DBmethod().HourlyPayRecordGet() for(var i = 0; i < usershift.count; i++){ shiftsystem = DBmethod().SearchShiftSystem(usershift[i]) if(shiftsystem.endtime <= houlypayrecord[0].timeto){ monthlysalary = monthlysalary + (shiftsystem.endtime - shiftsystem.starttime - 1) * Double(houlypayrecord[0].pay) }else{ //22時以降の給与を先に計算 let latertime = shiftsystem.endtime - houlypayrecord[0].timeto monthlysalary = monthlysalary + latertime * Double(houlypayrecord[1].pay) monthlysalary = monthlysalary + (shiftsystem.endtime - latertime - shiftsystem.starttime - 1) * Double(houlypayrecord[0].pay) } } print(monthlysalary) //TODO: データベースへ記録 // let realm = try! Realm() // let todos = realm.objects(ShiftDB).filter("shiftimportname = %@",importname) // todos.setValue(monthlysalary, forKey: "saraly") // realm.create(ShiftDB.self, value: ["shiftimportname": importname,"saraly": monthlysalary], update: true) // let AAA = ShiftDB() // AAA.id = 1 // AAA.shiftimportname = importname // AAA.saraly = Int(monthlysalary) // DBmethod().AddandUpdate(AAA, update: true) } //その日のシフトを全員分調べて出勤者だけ列挙する。 /*引数の説明。 day => その日の日付 staffcellpositionarray =>スタッフのセル位置を配列で記録したもの worksheet =>対象となるエクセルファイルのワークシート */ func TheDayStaffAttendance(day: Int, staffcellpositionarray: Array<String>, worksheet: BRAWorksheet) -> String{ var staffstring = "" for(var i = 0; i < staffnumber; i++){ let nowstaff = staffcellpositionarray[i] let replaceday = nowstaff.stringByReplacingOccurrencesOfString("F", withString: cellrow[day]) let dayshift: String = worksheet.cellForCellReference(replaceday).stringValue() let staffname: String = worksheet.cellForCellReference(nowstaff).stringValue() if(holiday.contains(dayshift) == false){ //Holiday以外なら記録 staffstring = staffstring + staffname + ":" + dayshift + "," } } return staffstring } }
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import TensorFlow final class LossTests: XCTestCase { func testMeanSquaredErrorLoss() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = meanSquaredError(predicted: predicted, expected: expected) let expectedLoss: Float = 23.324999 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testMeanAbsoluteError() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = meanAbsoluteError(predicted: predicted, expected: expected) let expectedLoss: Float = 4.25 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testMeanSquaredErrorGrad() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [1.8, 3.6, 5.4, 7.2, 9.2, 11.4, 13.6, 15.8]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(predicted.scalars.count) let gradients = gradient( at: predicted, in: { meanSquaredError(predicted: $0, expected: expected) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func testHingeLoss() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = hingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.225 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSquaredHingeLoss() { let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>([0.5, 1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]) let loss = squaredHingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.03125 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testCategoricalHingeLoss() { let predicted = Tensor<Float>([3, 4 ,5]) let expected = Tensor<Float>([0.3, 0.4, 0.3]) let loss = categoricalHingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.5 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSoftmaxCrossEntropyWithProbabilitiesLoss() { let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = softmaxCrossEntropy(logits: logits, probabilities: labels) // Loss for two rows are 1.44019 and 2.44019 respectively. let expectedLoss: Float = (1.44019 + 2.44019) / 2.0 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSoftmaxCrossEntropyWithProbabilitiesGrad() { let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) // For the logits and labels above, the gradients below are the golden values. To calcuate // them by hand, you can do // // D Loss / D logits_i = p_i - labels_i // // where p_i is softmax(logits_i). let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [-0.067941, -0.112856, -0.063117, 0.243914, -0.367941, -0.212856, 0.036883, 0.543914]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(logits.shape[0]) let gradients = gradient( at: logits, in: { softmaxCrossEntropy(logits: $0, probabilities: labels) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func testSigmoidCrossEntropyLoss() { let logits = Tensor<Float>( shape: [2, 4], scalars: [-100, -2, -2, 0, 2, 2, 2, 100]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0, 0, 1, 0, 0, 1, 0.5, 1]) let loss = sigmoidCrossEntropy(logits: logits, labels: labels) let expectedLoss: Float = 0.7909734 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSigmoidCrossEntropyGrad() { let logits = Tensor<Float>( shape: [2, 4], scalars: [-100, -2, -2, 0, 2, 2, 2, 100]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0, 0, 1, 0, 0, 1, 0.5, 1]) // For each element x in logits and y in labels, the gradient is sigmoid(x) - y. let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [0.00, 0.11920291, -0.8807971, 0.5, 0.8807971, -0.11920291, 0.3807971 , 0.0]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(logits.scalars.count) let gradients = gradient( at: logits, in: { sigmoidCrossEntropy(logits: $0, labels: labels) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func assertElementsEqual( expected: Tensor<Float>, actual: Tensor<Float>, accuracy: Float = 1e-6 ) { XCTAssertEqual(expected.shape, actual.shape, "Shape mismatch.") for (index, expectedElement) in expected.scalars.enumerated() { let actualElement = actual.scalars[index] XCTAssertEqual( expectedElement, actualElement, accuracy: accuracy, "Found difference at \(index), " + "expected: \(expectedElement), actual: \(actualElement).") } } static var allTests = [ ("testMeanSquaredErrorLoss", testMeanSquaredErrorLoss), ("testMeanSquaredErrorGrad", testMeanSquaredErrorGrad), ("testHingeLoss", testHingeLoss), ("testCategoricalHingeLoss", testCategoricalHingeLoss), ("testSquaredHingeLoss", testSquaredHingeLoss), ("testSoftmaxCrossEntropyWithProbabilitiesLoss", testSoftmaxCrossEntropyWithProbabilitiesLoss), ("testSoftmaxCrossEntropyWithProbabilitiesGrad", testSoftmaxCrossEntropyWithProbabilitiesGrad), ("testSigmoidCrossEntropyLoss", testSigmoidCrossEntropyLoss), ("testSigmoidCrossEntropyGrad", testSigmoidCrossEntropyGrad), ] } adding MeanAbsoluteError test to allTests (#189) // Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import TensorFlow final class LossTests: XCTestCase { func testMeanSquaredErrorLoss() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = meanSquaredError(predicted: predicted, expected: expected) let expectedLoss: Float = 23.324999 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testMeanAbsoluteError() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = meanAbsoluteError(predicted: predicted, expected: expected) let expectedLoss: Float = 4.25 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testMeanSquaredErrorGrad() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [1.8, 3.6, 5.4, 7.2, 9.2, 11.4, 13.6, 15.8]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(predicted.scalars.count) let gradients = gradient( at: predicted, in: { meanSquaredError(predicted: $0, expected: expected) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func testHingeLoss() { let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = hingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.225 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSquaredHingeLoss() { let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8]) let expected = Tensor<Float>([0.5, 1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]) let loss = squaredHingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.03125 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testCategoricalHingeLoss() { let predicted = Tensor<Float>([3, 4 ,5]) let expected = Tensor<Float>([0.3, 0.4, 0.3]) let loss = categoricalHingeLoss(predicted: predicted, expected: expected) let expectedLoss: Float = 0.5 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSoftmaxCrossEntropyWithProbabilitiesLoss() { let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) let loss = softmaxCrossEntropy(logits: logits, probabilities: labels) // Loss for two rows are 1.44019 and 2.44019 respectively. let expectedLoss: Float = (1.44019 + 2.44019) / 2.0 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSoftmaxCrossEntropyWithProbabilitiesGrad() { let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1]) // For the logits and labels above, the gradients below are the golden values. To calcuate // them by hand, you can do // // D Loss / D logits_i = p_i - labels_i // // where p_i is softmax(logits_i). let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [-0.067941, -0.112856, -0.063117, 0.243914, -0.367941, -0.212856, 0.036883, 0.543914]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(logits.shape[0]) let gradients = gradient( at: logits, in: { softmaxCrossEntropy(logits: $0, probabilities: labels) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func testSigmoidCrossEntropyLoss() { let logits = Tensor<Float>( shape: [2, 4], scalars: [-100, -2, -2, 0, 2, 2, 2, 100]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0, 0, 1, 0, 0, 1, 0.5, 1]) let loss = sigmoidCrossEntropy(logits: logits, labels: labels) let expectedLoss: Float = 0.7909734 assertElementsEqual(expected: Tensor(expectedLoss), actual: loss) } func testSigmoidCrossEntropyGrad() { let logits = Tensor<Float>( shape: [2, 4], scalars: [-100, -2, -2, 0, 2, 2, 2, 100]) let labels = Tensor<Float>( shape: [2, 4], scalars: [0, 0, 1, 0, 0, 1, 0.5, 1]) // For each element x in logits and y in labels, the gradient is sigmoid(x) - y. let expectedGradientsBeforeMean = Tensor<Float>( shape: [2, 4], scalars: [0.00, 0.11920291, -0.8807971, 0.5, 0.8807971, -0.11920291, 0.3807971 , 0.0]) // As the loss is mean loss, we should scale the golden gradient numbers. let expectedGradients = expectedGradientsBeforeMean / Float(logits.scalars.count) let gradients = gradient( at: logits, in: { sigmoidCrossEntropy(logits: $0, labels: labels) }) assertElementsEqual(expected: expectedGradients, actual: gradients) } func assertElementsEqual( expected: Tensor<Float>, actual: Tensor<Float>, accuracy: Float = 1e-6 ) { XCTAssertEqual(expected.shape, actual.shape, "Shape mismatch.") for (index, expectedElement) in expected.scalars.enumerated() { let actualElement = actual.scalars[index] XCTAssertEqual( expectedElement, actualElement, accuracy: accuracy, "Found difference at \(index), " + "expected: \(expectedElement), actual: \(actualElement).") } } static var allTests = [ ("testMeanSquaredErrorLoss", testMeanSquaredErrorLoss), ("testMeanSquaredErrorGrad", testMeanSquaredErrorGrad), ("testMeanAbsoluteError", testMeanAbsoluteError), ("testHingeLoss", testHingeLoss), ("testCategoricalHingeLoss", testCategoricalHingeLoss), ("testSquaredHingeLoss", testSquaredHingeLoss), ("testSoftmaxCrossEntropyWithProbabilitiesLoss", testSoftmaxCrossEntropyWithProbabilitiesLoss), ("testSoftmaxCrossEntropyWithProbabilitiesGrad", testSoftmaxCrossEntropyWithProbabilitiesGrad), ("testSigmoidCrossEntropyLoss", testSigmoidCrossEntropyLoss), ("testSigmoidCrossEntropyGrad", testSigmoidCrossEntropyGrad), ] }
import UIKit import WebKit public protocol TLSessionDelegate: class { func prepareWebViewConfiguration(configuration: WKWebViewConfiguration, forSession session: TLSession) func session(session: TLSession, didInitializeWebView webView: WKWebView) func session(session: TLSession, didProposeVisitToLocation location: NSURL) func sessionDidStartRequest(session: TLSession) func session(session: TLSession, didFailRequestForVisitable visitable: TLVisitable, withError error: NSError) func session(session: TLSession, didFailRequestForVisitable visitable: TLVisitable, withStatusCode statusCode: Int) func sessionDidFinishRequest(session: TLSession) } public class TLSession: NSObject, TLWebViewDelegate, TLVisitDelegate, TLVisitableDelegate { public weak var delegate: TLSessionDelegate? var initialized: Bool = false var refreshing: Bool = false lazy var webView: TLWebView = { let configuration = WKWebViewConfiguration() self.delegate?.prepareWebViewConfiguration(configuration, forSession: self) let webView = TLWebView(configuration: configuration) webView.delegate = self return webView }() // MARK: Visiting public var currentVisitable: TLVisitable? private var currentVisit: TLVisit? { didSet { NSLog("\(self) currentVisit = \(currentVisit)") } } private var lastIssuedVisit: TLVisit? { didSet { NSLog("\(self) lastIssuedVisit = \(lastIssuedVisit)") } } public func visit(visitable: TLVisitable) { visitVisitable(visitable, action: .Advance) } func visitVisitable(visitable: TLVisitable, action: TLVisitAction) { if let location = visitable.location { let visit: TLVisit if initialized { visit = TLJavaScriptVisit(visitable: visitable, action: action, webView: webView) } else { visit = TLColdBootVisit(visitable: visitable, action: action, webView: webView) } lastIssuedVisit?.cancel() lastIssuedVisit = visit visit.delegate = self visit.start() } } public func reload() { if let visitable = currentVisitable { initialized = false visitVisitable(visitable, action: .Advance) activateVisitable(visitable) } } // MARK: TLWebViewDelegate func webView(webView: TLWebView, didProposeVisitToLocation location: NSURL) { delegate?.session(self, didProposeVisitToLocation: location) } func webViewDidInvalidatePage(webView: TLWebView) { if let visitable = currentVisitable { visitable.updateScreenshot() currentVisit?.cancel() visitable.showScreenshot() visitable.showActivityIndicator() reload() } } // MARK: TLVisitDelegate func visitDidInitializeWebView(visit: TLVisit) { initialized = true delegate?.session(self, didInitializeWebView: webView) visit.visitable.didLoadResponse?() } func visitDidStart(visit: TLVisit) { visit.visitable.showScreenshot() if !visit.hasSnapshot { visit.visitable.showActivityIndicator() } } func visitDidRestoreSnapshot(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() visit.visitable.didRestoreSnapshot?() } func visitDidLoadResponse(visit: TLVisit) { visit.visitable.didLoadResponse?() } func visitDidComplete(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() if refreshing { refreshing = false visit.visitable.didRefresh() } } func visitDidFail(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() deactivateVisitable(visit.visitable) } // MARK: TLVisitDelegate - Request func visitRequestDidStart(visit: TLVisit) { delegate?.sessionDidStartRequest(self) } func visitRequestDidFinish(visit: TLVisit) { delegate?.sessionDidFinishRequest(self) } func visit(visit: TLVisit, requestDidFailWithError error: NSError) { delegate?.session(self, didFailRequestForVisitable: visit.visitable, withError: error) } func visit(visit: TLVisit, requestDidFailWithStatusCode statusCode: Int) { delegate?.session(self, didFailRequestForVisitable: visit.visitable, withStatusCode: statusCode) } // MARK: TLVisitableDelegate public func visitableViewWillAppear(visitable: TLVisitable) { if let currentVisitable = self.currentVisitable, currentVisit = self.currentVisit, lastIssuedVisit = self.lastIssuedVisit { if visitable === currentVisitable && visitable.viewController.isMovingToParentViewController() { // Back swipe gesture canceled if currentVisit.state == .Completed { // Top visitable was fully loaded before the gesture began lastIssuedVisit.cancel() } else { // Top visitable was *not* fully loaded before the gesture began visitVisitable(visitable, action: .Advance) } } else if lastIssuedVisit.visitable !== visitable || lastIssuedVisit.state == .Canceled { // Navigating backward visitVisitable(visitable, action: .Restore) } } } public func visitableViewDidAppear(visitable: TLVisitable) { activateVisitable(visitable) currentVisit?.completeNavigation() } public func visitableViewWillDisappear(visitable: TLVisitable) { visitable.updateScreenshot() } public func visitableDidRequestRefresh(visitable: TLVisitable) { if visitable === currentVisitable { refreshing = true visitable.willRefresh() reload() } } func activateVisitable(visitable: TLVisitable) { if currentVisitable != nil && currentVisitable !== visitable { deactivateVisitable(currentVisitable!) } currentVisitable = visitable if lastIssuedVisit?.visitable === visitable { currentVisit = lastIssuedVisit } if !webView.isDescendantOfView(visitable.viewController.view) { visitable.activateWebView(webView) } } func deactivateVisitable(visitable: TLVisitable) { if webView.isDescendantOfView(visitable.viewController.view) { visitable.deactivateWebView() } } } Remove Session visit didSet logging import UIKit import WebKit public protocol TLSessionDelegate: class { func prepareWebViewConfiguration(configuration: WKWebViewConfiguration, forSession session: TLSession) func session(session: TLSession, didInitializeWebView webView: WKWebView) func session(session: TLSession, didProposeVisitToLocation location: NSURL) func sessionDidStartRequest(session: TLSession) func session(session: TLSession, didFailRequestForVisitable visitable: TLVisitable, withError error: NSError) func session(session: TLSession, didFailRequestForVisitable visitable: TLVisitable, withStatusCode statusCode: Int) func sessionDidFinishRequest(session: TLSession) } public class TLSession: NSObject, TLWebViewDelegate, TLVisitDelegate, TLVisitableDelegate { public weak var delegate: TLSessionDelegate? var initialized: Bool = false var refreshing: Bool = false lazy var webView: TLWebView = { let configuration = WKWebViewConfiguration() self.delegate?.prepareWebViewConfiguration(configuration, forSession: self) let webView = TLWebView(configuration: configuration) webView.delegate = self return webView }() // MARK: Visiting public var currentVisitable: TLVisitable? private var currentVisit: TLVisit? private var lastIssuedVisit: TLVisit? public func visit(visitable: TLVisitable) { visitVisitable(visitable, action: .Advance) } func visitVisitable(visitable: TLVisitable, action: TLVisitAction) { if let location = visitable.location { let visit: TLVisit if initialized { visit = TLJavaScriptVisit(visitable: visitable, action: action, webView: webView) } else { visit = TLColdBootVisit(visitable: visitable, action: action, webView: webView) } lastIssuedVisit?.cancel() lastIssuedVisit = visit visit.delegate = self visit.start() } } public func reload() { if let visitable = currentVisitable { initialized = false visitVisitable(visitable, action: .Advance) activateVisitable(visitable) } } // MARK: TLWebViewDelegate func webView(webView: TLWebView, didProposeVisitToLocation location: NSURL) { delegate?.session(self, didProposeVisitToLocation: location) } func webViewDidInvalidatePage(webView: TLWebView) { if let visitable = currentVisitable { visitable.updateScreenshot() currentVisit?.cancel() visitable.showScreenshot() visitable.showActivityIndicator() reload() } } // MARK: TLVisitDelegate func visitDidInitializeWebView(visit: TLVisit) { initialized = true delegate?.session(self, didInitializeWebView: webView) visit.visitable.didLoadResponse?() } func visitDidStart(visit: TLVisit) { visit.visitable.showScreenshot() if !visit.hasSnapshot { visit.visitable.showActivityIndicator() } } func visitDidRestoreSnapshot(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() visit.visitable.didRestoreSnapshot?() } func visitDidLoadResponse(visit: TLVisit) { visit.visitable.didLoadResponse?() } func visitDidComplete(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() if refreshing { refreshing = false visit.visitable.didRefresh() } } func visitDidFail(visit: TLVisit) { visit.visitable.hideScreenshot() visit.visitable.hideActivityIndicator() deactivateVisitable(visit.visitable) } // MARK: TLVisitDelegate - Request func visitRequestDidStart(visit: TLVisit) { delegate?.sessionDidStartRequest(self) } func visitRequestDidFinish(visit: TLVisit) { delegate?.sessionDidFinishRequest(self) } func visit(visit: TLVisit, requestDidFailWithError error: NSError) { delegate?.session(self, didFailRequestForVisitable: visit.visitable, withError: error) } func visit(visit: TLVisit, requestDidFailWithStatusCode statusCode: Int) { delegate?.session(self, didFailRequestForVisitable: visit.visitable, withStatusCode: statusCode) } // MARK: TLVisitableDelegate public func visitableViewWillAppear(visitable: TLVisitable) { if let currentVisitable = self.currentVisitable, currentVisit = self.currentVisit, lastIssuedVisit = self.lastIssuedVisit { if visitable === currentVisitable && visitable.viewController.isMovingToParentViewController() { // Back swipe gesture canceled if currentVisit.state == .Completed { // Top visitable was fully loaded before the gesture began lastIssuedVisit.cancel() } else { // Top visitable was *not* fully loaded before the gesture began visitVisitable(visitable, action: .Advance) } } else if lastIssuedVisit.visitable !== visitable || lastIssuedVisit.state == .Canceled { // Navigating backward visitVisitable(visitable, action: .Restore) } } } public func visitableViewDidAppear(visitable: TLVisitable) { activateVisitable(visitable) currentVisit?.completeNavigation() } public func visitableViewWillDisappear(visitable: TLVisitable) { visitable.updateScreenshot() } public func visitableDidRequestRefresh(visitable: TLVisitable) { if visitable === currentVisitable { refreshing = true visitable.willRefresh() reload() } } func activateVisitable(visitable: TLVisitable) { if currentVisitable != nil && currentVisitable !== visitable { deactivateVisitable(currentVisitable!) } currentVisitable = visitable if lastIssuedVisit?.visitable === visitable { currentVisit = lastIssuedVisit } if !webView.isDescendantOfView(visitable.viewController.view) { visitable.activateWebView(webView) } } func deactivateVisitable(visitable: TLVisitable) { if webView.isDescendantOfView(visitable.viewController.view) { visitable.deactivateWebView() } } }
import UIKit import WMF #if OSM import Mapbox #else import MapKit #endif protocol ArticlePlaceViewDelegate: NSObjectProtocol { func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) } class ArticlePlaceView: MapAnnotationView { static let smallDotImage = #imageLiteral(resourceName: "places-dot-small") static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium") static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque") static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium") static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque") static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium") static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque") static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large") static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque") static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ") static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium") static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large") static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium") static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large") public weak var delegate: ArticlePlaceViewDelegate? var imageView: UIView! private var imageImageView: UIImageView! private var imageImagePlaceholderView: UIImageView! private var imageOutlineView: UIView! private var imageBackgroundView: UIView! private var selectedImageView: UIView! private var selectedImageImageView: UIImageView! private var selectedImageImagePlaceholderView: UIImageView! private var selectedImageOutlineView: UIView! private var selectedImageBackgroundView: UIView! private var dotView: UIView! private var groupView: UIView! private var countLabel: UILabel! private var dimension: CGFloat! private var collapsedDimension: CGFloat! var groupDimension: CGFloat! var imageDimension: CGFloat! var selectedImageButton: UIButton! private var alwaysShowImage = false private let selectionAnimationDuration = 0.3 private let springDamping: CGFloat = 0.5 private let crossFadeRelativeHalfDuration: TimeInterval = 0.1 private let alwaysRasterize = true // set this or rasterize on animations, not both private let rasterizeOnAnimations = false override func setup() { selectedImageView = UIView() imageView = UIView() selectedImageImageView = UIImageView() imageImageView = UIImageView() countLabel = UILabel() dotView = UIView() groupView = UIView() imageOutlineView = UIView() selectedImageOutlineView = UIView() imageBackgroundView = UIView() selectedImageBackgroundView = UIView() selectedImageButton = UIButton() imageImagePlaceholderView = UIImageView() selectedImageImagePlaceholderView = UIImageView() let scale = ArticlePlaceView.mediumDotImage.scale let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage collapsedDimension = ArticlePlaceView.smallDotImage.size.width groupDimension = ArticlePlaceView.mediumDotImage.size.width dimension = largeOpaqueDotOutlineImage.size.width imageDimension = mediumOpaqueDotOutlineImage.size.width let gravity = kCAGravityBottomRight isPlaceholderHidden = false frame = CGRect(x: 0, y: 0, width: dimension, height: dimension) dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension) dotView.layer.contentsGravity = gravity dotView.layer.contentsScale = scale dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) addSubview(dotView) groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension) groupView.layer.contentsGravity = gravity groupView.layer.contentsScale = scale groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage addSubview(groupView) imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension) imageView.layer.rasterizationScale = scale addSubview(imageView) imageBackgroundView.frame = imageView.bounds imageBackgroundView.layer.contentsGravity = gravity imageBackgroundView.layer.contentsScale = scale imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage imageView.addSubview(imageBackgroundView) imageImagePlaceholderView.frame = imageView.bounds imageImagePlaceholderView.contentMode = .center imageImagePlaceholderView.image = mediumPlaceholderImage imageView.addSubview(imageImagePlaceholderView) var inset: CGFloat = 3.5 var imageViewFrame = UIEdgeInsetsInsetRect(imageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) imageImageView.frame = imageViewFrame imageImageView.contentMode = .scaleAspectFill imageImageView.layer.masksToBounds = true imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5 imageImageView.backgroundColor = UIColor.white imageView.addSubview(imageImageView) imageOutlineView.frame = imageView.bounds imageOutlineView.layer.contentsGravity = gravity imageOutlineView.layer.contentsScale = scale imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage imageView.addSubview(imageOutlineView) selectedImageView.bounds = bounds selectedImageView.layer.rasterizationScale = scale addSubview(selectedImageView) selectedImageBackgroundView.frame = selectedImageView.bounds selectedImageBackgroundView.layer.contentsGravity = gravity selectedImageBackgroundView.layer.contentsScale = scale selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage selectedImageView.addSubview(selectedImageBackgroundView) selectedImageImagePlaceholderView.frame = selectedImageView.bounds selectedImageImagePlaceholderView.contentMode = .center selectedImageImagePlaceholderView.image = largePlaceholderImage selectedImageView.addSubview(selectedImageImagePlaceholderView) inset = imageDimension > 40 ? 3.5 : 5.5 imageViewFrame = UIEdgeInsetsInsetRect(selectedImageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) selectedImageImageView.frame = imageViewFrame selectedImageImageView.contentMode = .scaleAspectFill selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5 selectedImageImageView.layer.masksToBounds = true selectedImageImageView.backgroundColor = UIColor.white selectedImageView.addSubview(selectedImageImageView) selectedImageOutlineView.frame = selectedImageView.bounds selectedImageOutlineView.layer.contentsGravity = gravity selectedImageOutlineView.layer.contentsScale = scale selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage selectedImageView.addSubview(selectedImageOutlineView) selectedImageButton.frame = selectedImageView.bounds selectedImageButton.accessibilityTraits = UIAccessibilityTraitNone selectedImageView.addSubview(selectedImageButton) countLabel.frame = groupView.bounds countLabel.textColor = UIColor.white countLabel.textAlignment = .center countLabel.font = UIFont.boldSystemFont(ofSize: 16) groupView.addSubview(countLabel) prepareForReuse() super.setup() updateLayout() if let annotation = annotation as? ArticlePlace { update(withArticlePlace: annotation) } } func set(alwaysShowImage: Bool, animated: Bool) { self.alwaysShowImage = alwaysShowImage let scale = collapsedDimension/imageDimension let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale) if alwaysShowImage { loadImage() imageView.alpha = 0 imageView.isHidden = false dotView.alpha = 1 dotView.isHidden = false imageView.transform = imageViewScaleDownTransform dotView.transform = CGAffineTransform.identity } else { dotView.transform = dotViewScaleUpTransform imageView.transform = CGAffineTransform.identity imageView.alpha = 1 imageView.isHidden = false dotView.alpha = 0 dotView.isHidden = false } let transforms = { if alwaysShowImage { self.imageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform } else { self.imageView.transform = imageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity } } let fadesIn = { if alwaysShowImage { self.imageView.alpha = 1 } else { self.dotView.alpha = 1 } } let fadesOut = { if alwaysShowImage { self.dotView.alpha = 0 } else { self.imageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = false } guard let articlePlace = self.annotation as? ArticlePlace else { return } self.updateDotAndImageHiddenState(withArticlePlace: articlePlace) } if animated { if alwaysShowImage { UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } override func didMoveToSuperview() { super.didMoveToSuperview() guard superview != nil else { selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) return } selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) } func selectedImageViewWasTapped(_ sender: UIButton) { delegate?.articlePlaceViewWasTapped(self) } var zPosition: CGFloat = 1 { didSet { guard !isSelected else { return } layer.zPosition = zPosition } } var isPlaceholderHidden: Bool = true { didSet { selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden imageImagePlaceholderView.isHidden = isPlaceholderHidden imageImageView.isHidden = !isPlaceholderHidden selectedImageImageView.isHidden = !isPlaceholderHidden } } private var shouldRasterize = false { didSet { imageView.layer.shouldRasterize = shouldRasterize selectedImageView.layer.shouldRasterize = shouldRasterize } } private var isImageLoaded = false func loadImage() { guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else { return } if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = true let article = articlePlace.articles[0] if let thumbnailURL = article.thumbnailURL { imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in if self.alwaysRasterize { self.shouldRasterize = true } }, success: { self.selectedImageImageView.image = self.imageImageView.image self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect self.isPlaceholderHidden = true if self.alwaysRasterize { self.shouldRasterize = true } }) } } func update(withArticlePlace articlePlace: ArticlePlace) { if articlePlace.articles.count == 1 { zPosition = 1 isImageLoaded = false if isSelected || alwaysShowImage { loadImage() } accessibilityLabel = articlePlace.articles.first?.displayTitle } else if articlePlace.articles.count == 0 { zPosition = 1 isPlaceholderHidden = false imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more") accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles") } else { zPosition = 2 let countString = "\(articlePlace.articles.count)" countLabel.text = countString accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group\n{{Identical|Article}}"), countString) } updateDotAndImageHiddenState(withArticlePlace: articlePlace) } func updateDotAndImageHiddenState(withArticlePlace articlePlace: ArticlePlace) { switch articlePlace.articles.count { case 0: fallthrough case 1: imageView.isHidden = !alwaysShowImage dotView.isHidden = alwaysShowImage groupView.isHidden = true default: imageView.isHidden = true dotView.isHidden = true groupView.isHidden = false } } #if OSM override var annotation: MGLAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #else override var annotation: MKAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #endif override func prepareForReuse() { super.prepareForReuse() if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = false delegate = nil imageImageView.wmf_reset() selectedImageImageView.wmf_reset() countLabel.text = nil set(alwaysShowImage: false, animated: false) setSelected(false, animated: false) alpha = 1 transform = CGAffineTransform.identity } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) guard let place = annotation as? ArticlePlace, place.articles.count == 1 else { selectedImageView.alpha = 0 return } let dotScale = collapsedDimension/dimension let imageViewScale = imageDimension/dimension let scale = alwaysShowImage ? imageViewScale : dotScale let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale) let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale) layer.zPosition = 3 if selected { loadImage() selectedImageView.transform = selectedImageViewScaleDownTransform dotView.transform = CGAffineTransform.identity imageView.transform = CGAffineTransform.identity selectedImageView.alpha = 0 imageView.alpha = 1 dotView.alpha = 1 } else { selectedImageView.transform = CGAffineTransform.identity dotView.transform = dotViewScaleUpTransform imageView.transform = imageViewScaleUpTransform selectedImageView.alpha = 1 imageView.alpha = 0 dotView.alpha = 0 } let transforms = { if selected { self.selectedImageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform self.imageView.transform = imageViewScaleUpTransform } else { self.selectedImageView.transform = selectedImageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity self.imageView.transform = CGAffineTransform.identity } } let fadesIn = { if selected { self.selectedImageView.alpha = 1 } else { self.imageView.alpha = 1 self.dotView.alpha = 1 } } let fadesOut = { if selected { self.imageView.alpha = 0 self.dotView.alpha = 0 } else { self.selectedImageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.shouldRasterize = false } if !selected { self.layer.zPosition = self.zPosition } } if animated { let duration = 2*selectionAnimationDuration if selected { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } func updateLayout() { let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) selectedImageView.center = center imageView.center = center dotView.center = center groupView.center = center } override var frame: CGRect { didSet { guard isSetup else { return } updateLayout() } } override var bounds: CGRect { didSet { guard isSetup else { return } updateLayout() } } } fix article place view setup & initial state import UIKit import WMF #if OSM import Mapbox #else import MapKit #endif protocol ArticlePlaceViewDelegate: NSObjectProtocol { func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) } class ArticlePlaceView: MapAnnotationView { static let smallDotImage = #imageLiteral(resourceName: "places-dot-small") static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium") static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque") static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium") static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque") static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium") static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque") static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large") static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque") static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ") static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium") static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large") static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium") static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large") public weak var delegate: ArticlePlaceViewDelegate? var imageView: UIView! private var imageImageView: UIImageView! private var imageImagePlaceholderView: UIImageView! private var imageOutlineView: UIView! private var imageBackgroundView: UIView! private var selectedImageView: UIView! private var selectedImageImageView: UIImageView! private var selectedImageImagePlaceholderView: UIImageView! private var selectedImageOutlineView: UIView! private var selectedImageBackgroundView: UIView! private var dotView: UIView! private var groupView: UIView! private var countLabel: UILabel! private var dimension: CGFloat! private var collapsedDimension: CGFloat! var groupDimension: CGFloat! var imageDimension: CGFloat! var selectedImageButton: UIButton! private var alwaysShowImage = false private let selectionAnimationDuration = 0.3 private let springDamping: CGFloat = 0.5 private let crossFadeRelativeHalfDuration: TimeInterval = 0.1 private let alwaysRasterize = true // set this or rasterize on animations, not both private let rasterizeOnAnimations = false override func setup() { selectedImageView = UIView() imageView = UIView() selectedImageImageView = UIImageView() imageImageView = UIImageView() countLabel = UILabel() dotView = UIView() groupView = UIView() imageOutlineView = UIView() selectedImageOutlineView = UIView() imageBackgroundView = UIView() selectedImageBackgroundView = UIView() selectedImageButton = UIButton() imageImagePlaceholderView = UIImageView() selectedImageImagePlaceholderView = UIImageView() let scale = ArticlePlaceView.mediumDotImage.scale let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage collapsedDimension = ArticlePlaceView.smallDotImage.size.width groupDimension = ArticlePlaceView.mediumDotImage.size.width dimension = largeOpaqueDotOutlineImage.size.width imageDimension = mediumOpaqueDotOutlineImage.size.width let gravity = kCAGravityBottomRight isPlaceholderHidden = false frame = CGRect(x: 0, y: 0, width: dimension, height: dimension) dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension) dotView.layer.contentsGravity = gravity dotView.layer.contentsScale = scale dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) addSubview(dotView) groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension) groupView.layer.contentsGravity = gravity groupView.layer.contentsScale = scale groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage addSubview(groupView) imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension) imageView.layer.rasterizationScale = scale addSubview(imageView) imageBackgroundView.frame = imageView.bounds imageBackgroundView.layer.contentsGravity = gravity imageBackgroundView.layer.contentsScale = scale imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage imageView.addSubview(imageBackgroundView) imageImagePlaceholderView.frame = imageView.bounds imageImagePlaceholderView.contentMode = .center imageImagePlaceholderView.image = mediumPlaceholderImage imageView.addSubview(imageImagePlaceholderView) var inset: CGFloat = 3.5 var imageViewFrame = UIEdgeInsetsInsetRect(imageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) imageImageView.frame = imageViewFrame imageImageView.contentMode = .scaleAspectFill imageImageView.layer.masksToBounds = true imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5 imageImageView.backgroundColor = UIColor.white imageView.addSubview(imageImageView) imageOutlineView.frame = imageView.bounds imageOutlineView.layer.contentsGravity = gravity imageOutlineView.layer.contentsScale = scale imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage imageView.addSubview(imageOutlineView) selectedImageView.bounds = bounds selectedImageView.layer.rasterizationScale = scale addSubview(selectedImageView) selectedImageBackgroundView.frame = selectedImageView.bounds selectedImageBackgroundView.layer.contentsGravity = gravity selectedImageBackgroundView.layer.contentsScale = scale selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage selectedImageView.addSubview(selectedImageBackgroundView) selectedImageImagePlaceholderView.frame = selectedImageView.bounds selectedImageImagePlaceholderView.contentMode = .center selectedImageImagePlaceholderView.image = largePlaceholderImage selectedImageView.addSubview(selectedImageImagePlaceholderView) inset = imageDimension > 40 ? 3.5 : 5.5 imageViewFrame = UIEdgeInsetsInsetRect(selectedImageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) selectedImageImageView.frame = imageViewFrame selectedImageImageView.contentMode = .scaleAspectFill selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5 selectedImageImageView.layer.masksToBounds = true selectedImageImageView.backgroundColor = UIColor.white selectedImageView.addSubview(selectedImageImageView) selectedImageOutlineView.frame = selectedImageView.bounds selectedImageOutlineView.layer.contentsGravity = gravity selectedImageOutlineView.layer.contentsScale = scale selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage selectedImageView.addSubview(selectedImageOutlineView) selectedImageButton.frame = selectedImageView.bounds selectedImageButton.accessibilityTraits = UIAccessibilityTraitNone selectedImageView.addSubview(selectedImageButton) countLabel.frame = groupView.bounds countLabel.textColor = UIColor.white countLabel.textAlignment = .center countLabel.font = UIFont.boldSystemFont(ofSize: 16) groupView.addSubview(countLabel) prepareForReuse() super.setup() updateLayout() update(withArticlePlace: annotation as? ArticlePlace) } func set(alwaysShowImage: Bool, animated: Bool) { self.alwaysShowImage = alwaysShowImage let scale = collapsedDimension/imageDimension let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale) if alwaysShowImage { loadImage() imageView.alpha = 0 imageView.isHidden = false dotView.alpha = 1 dotView.isHidden = false imageView.transform = imageViewScaleDownTransform dotView.transform = CGAffineTransform.identity } else { dotView.transform = dotViewScaleUpTransform imageView.transform = CGAffineTransform.identity imageView.alpha = 1 imageView.isHidden = false dotView.alpha = 0 dotView.isHidden = false } let transforms = { if alwaysShowImage { self.imageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform } else { self.imageView.transform = imageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity } } let fadesIn = { if alwaysShowImage { self.imageView.alpha = 1 } else { self.dotView.alpha = 1 } } let fadesOut = { if alwaysShowImage { self.dotView.alpha = 0 } else { self.imageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = false } guard let articlePlace = self.annotation as? ArticlePlace else { return } self.updateDotAndImageHiddenState(with: articlePlace.articles.count) } if animated { if alwaysShowImage { UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } override func didMoveToSuperview() { super.didMoveToSuperview() guard superview != nil else { selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) return } selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) } func selectedImageViewWasTapped(_ sender: UIButton) { delegate?.articlePlaceViewWasTapped(self) } var zPosition: CGFloat = 1 { didSet { guard !isSelected else { return } layer.zPosition = zPosition } } var isPlaceholderHidden: Bool = true { didSet { selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden imageImagePlaceholderView.isHidden = isPlaceholderHidden imageImageView.isHidden = !isPlaceholderHidden selectedImageImageView.isHidden = !isPlaceholderHidden } } private var shouldRasterize = false { didSet { imageView.layer.shouldRasterize = shouldRasterize selectedImageView.layer.shouldRasterize = shouldRasterize } } private var isImageLoaded = false func loadImage() { guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else { return } if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = true let article = articlePlace.articles[0] if let thumbnailURL = article.thumbnailURL { imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in if self.alwaysRasterize { self.shouldRasterize = true } }, success: { self.selectedImageImageView.image = self.imageImageView.image self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect self.isPlaceholderHidden = true if self.alwaysRasterize { self.shouldRasterize = true } }) } } func update(withArticlePlace articlePlace: ArticlePlace?) { let articleCount = articlePlace?.articles.count ?? 1 switch articleCount { case 0: zPosition = 1 isPlaceholderHidden = false imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more") accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles") case 1: zPosition = 1 isImageLoaded = false if isSelected || alwaysShowImage { loadImage() } accessibilityLabel = articlePlace?.articles.first?.displayTitle default: zPosition = 2 let countString = "\(articleCount)" countLabel.text = countString accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group\n{{Identical|Article}}"), countString) } updateDotAndImageHiddenState(with: articleCount) } func updateDotAndImageHiddenState(with articleCount: Int) { switch articleCount { case 0: fallthrough case 1: imageView.isHidden = !alwaysShowImage dotView.isHidden = alwaysShowImage groupView.isHidden = true default: imageView.isHidden = true dotView.isHidden = true groupView.isHidden = false } } #if OSM override var annotation: MGLAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #else override var annotation: MKAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #endif override func prepareForReuse() { super.prepareForReuse() if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = false delegate = nil imageImageView.wmf_reset() selectedImageImageView.wmf_reset() countLabel.text = nil set(alwaysShowImage: false, animated: false) setSelected(false, animated: false) alpha = 1 transform = CGAffineTransform.identity } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) guard let place = annotation as? ArticlePlace, place.articles.count == 1 else { selectedImageView.alpha = 0 return } let dotScale = collapsedDimension/dimension let imageViewScale = imageDimension/dimension let scale = alwaysShowImage ? imageViewScale : dotScale let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale) let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale) layer.zPosition = 3 if selected { loadImage() selectedImageView.transform = selectedImageViewScaleDownTransform dotView.transform = CGAffineTransform.identity imageView.transform = CGAffineTransform.identity selectedImageView.alpha = 0 imageView.alpha = 1 dotView.alpha = 1 } else { selectedImageView.transform = CGAffineTransform.identity dotView.transform = dotViewScaleUpTransform imageView.transform = imageViewScaleUpTransform selectedImageView.alpha = 1 imageView.alpha = 0 dotView.alpha = 0 } let transforms = { if selected { self.selectedImageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform self.imageView.transform = imageViewScaleUpTransform } else { self.selectedImageView.transform = selectedImageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity self.imageView.transform = CGAffineTransform.identity } } let fadesIn = { if selected { self.selectedImageView.alpha = 1 } else { self.imageView.alpha = 1 self.dotView.alpha = 1 } } let fadesOut = { if selected { self.imageView.alpha = 0 self.dotView.alpha = 0 } else { self.selectedImageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.shouldRasterize = false } if !selected { self.layer.zPosition = self.zPosition } } if animated { let duration = 2*selectionAnimationDuration if selected { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } func updateLayout() { let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) selectedImageView.center = center imageView.center = center dotView.center = center groupView.center = center } override var frame: CGRect { didSet { guard isSetup else { return } updateLayout() } } override var bounds: CGRect { didSet { guard isSetup else { return } updateLayout() } } }
// // denverrailUITests.swift // denverrailUITests // // Created by Naomi Himley on 6/1/16. // Copyright © 2016 Tack Mobile. All rights reserved. // import XCTest class denverrailUITests: XCTestCase { let app = XCUIApplication() override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } func testOpenThenCloseMap() { app.buttons["mapButton"].tap() let webViewQuery:XCUIElementQuery = app.descendantsMatchingType(.Any) let pdfMapView = webViewQuery.elementMatchingType(.Any, identifier:"Map View") XCTAssertNotNil(pdfMapView) XCTAssertTrue(pdfMapView.hittable) //Close map and make sure table with Eastbound/Westbound is showing app.buttons["mapButton"].tap() let eastboundButton = app.buttons["South Or East Button"] XCTAssertTrue(eastboundButton.hittable) } func testAutoButton() { let autobuttonButton = app.buttons["autoButton"] autobuttonButton.tap() //After tapping the auto button make sure the picker appears app.buttons["Open Time Picker"].tap() let datePicker = app.pickers["Non Auto Time Picker"] XCTAssertNotNil(datePicker) //Set picker to Holiday then dismiss app.pickerWheels.elementBoundByIndex(0).adjustToPickerWheelValue("Holiday") app.buttons["Done"].tap() //Check that label showing Holiday exists let label = app.staticTexts["Holiday"] let exists = NSPredicate(format: "exists == true") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) } func testSearch () { //Tap to open Search app.buttons["Station Search Button"].tap() //Check number of rows is 53 for all 53 stations let tablesQuery = app.tables let count = tablesQuery.cells.count XCTAssert(count == 53) //Search for Union let searchTextField = app.textFields["Find a Station"] searchTextField.tap() searchTextField.typeText("Union") app.keyboards.buttons["Done"].tap() //Check there is only one result let searchTableQuery = app.tables let resultCount = searchTableQuery.cells.count XCTAssert(resultCount == 1) //Select Yale to dismiss search and check Yale was selected app.tables.staticTexts["Union "].tap() let stationNameQuery:XCUIElementQuery = app.descendantsMatchingType(.Any) let stationNameLabel = stationNameQuery.elementMatchingType(.Any, identifier:"Station Name Label") XCTAssertTrue(stationNameLabel.label == "Union Station") } func testNowButton () { //Get time test is being run let now:NSDate = NSDate() let calendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian) calendar?.timeZone = NSTimeZone.init(name:"US/Mountain")! let unitFlags: NSCalendarUnit = [ .Hour, .Minute] let nowComponents = calendar?.components(unitFlags, fromDate: now) var hour = nowComponents!.hour let isPM : Bool if hour > 12 { isPM = true hour -= 12 } else if hour == 12 { isPM = true } else { isPM = false } let minute = nowComponents!.minute let minuteString : String if minute < 10 { minuteString = "0" + String(minute) } else { minuteString = String(minute) } let AMPMString = isPM ? "PM" : "AM" //Start test app.buttons["autoButton"].tap() //Make sure the picker appears app.buttons["Open Time Picker"].tap() let datePicker = app.pickers["Non Auto Time Picker"] XCTAssertNotNil(datePicker) //Mess up the picker app.pickerWheels.elementBoundByIndex(0).adjustToPickerWheelValue("Holiday") app.pickerWheels.elementBoundByIndex(1).adjustToPickerWheelValue("12") app.pickerWheels.elementBoundByIndex(2).adjustToPickerWheelValue("59") //Tap NOW, dismiss and then make sure the current times show up app.buttons["Now"].tap() app.buttons["Done"].tap() let constructedTimeString = String(hour) + ":" + minuteString + " " + AMPMString let label = app.staticTexts[constructedTimeString] let exists = NSPredicate(format: "exists == true") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) } } using guard let instead of force unwrapping obj c initialized optionals // // denverrailUITests.swift // denverrailUITests // // Created by Naomi Himley on 6/1/16. // Copyright © 2016 Tack Mobile. All rights reserved. // import XCTest class denverrailUITests: XCTestCase { let app = XCUIApplication() override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } func testOpenThenCloseMap() { app.buttons["mapButton"].tap() let webViewQuery:XCUIElementQuery = app.descendantsMatchingType(.Any) let pdfMapView = webViewQuery.elementMatchingType(.Any, identifier:"Map View") XCTAssertNotNil(pdfMapView) XCTAssertTrue(pdfMapView.hittable) //Close map and make sure table with Eastbound/Westbound is showing app.buttons["mapButton"].tap() let eastboundButton = app.buttons["South Or East Button"] XCTAssertTrue(eastboundButton.hittable) } func testAutoButton() { let autobuttonButton = app.buttons["autoButton"] autobuttonButton.tap() //After tapping the auto button make sure the picker appears app.buttons["Open Time Picker"].tap() let datePicker = app.pickers["Non Auto Time Picker"] XCTAssertNotNil(datePicker) //Set picker to Holiday then dismiss app.pickerWheels.elementBoundByIndex(0).adjustToPickerWheelValue("Holiday") app.buttons["Done"].tap() //Check that label showing Holiday exists let label = app.staticTexts["Holiday"] let exists = NSPredicate(format: "exists == true") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) } func testSearch () { //Tap to open Search app.buttons["Station Search Button"].tap() //Check number of rows is 53 for all 53 stations let tablesQuery = app.tables let count = tablesQuery.cells.count XCTAssert(count == 53) //Search for Union let searchTextField = app.textFields["Find a Station"] searchTextField.tap() searchTextField.typeText("Union") app.keyboards.buttons["Done"].tap() //Check there is only one result let searchTableQuery = app.tables let resultCount = searchTableQuery.cells.count XCTAssert(resultCount == 1) //Select Union to dismiss search and check Union was selected app.tables.staticTexts["Union "].tap() let stationNameQuery:XCUIElementQuery = app.descendantsMatchingType(.Any) let stationNameLabel = stationNameQuery.elementMatchingType(.Any, identifier:"Station Name Label") XCTAssertTrue(stationNameLabel.label == "Union Station") } func testNowButton () { //Get time test is being run let now:NSDate = NSDate() guard let calendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian) else { //Could not initialize calendar return } guard let mountainTime = NSTimeZone.init(name:"US/Mountain") else { //Could not initialize Mountain time return } calendar.timeZone = mountainTime let unitFlags: NSCalendarUnit = [ .Hour, .Minute] let nowComponents = calendar.components(unitFlags, fromDate: now) var hour = nowComponents.hour let isPM : Bool if hour > 12 { isPM = true hour -= 12 } else if hour == 12 { isPM = true } else { isPM = false } let minute = nowComponents.minute let minuteString : String if minute < 10 { minuteString = "0" + String(minute) } else { minuteString = String(minute) } let AMPMString = isPM ? "PM" : "AM" //Start test app.buttons["autoButton"].tap() //Make sure the picker appears app.buttons["Open Time Picker"].tap() let datePicker = app.pickers["Non Auto Time Picker"] XCTAssertNotNil(datePicker) //Mess up the picker app.pickerWheels.elementBoundByIndex(0).adjustToPickerWheelValue("Holiday") app.pickerWheels.elementBoundByIndex(1).adjustToPickerWheelValue("12") app.pickerWheels.elementBoundByIndex(2).adjustToPickerWheelValue("59") //Tap NOW, dismiss and then make sure the current times show up app.buttons["Now"].tap() app.buttons["Done"].tap() let constructedTimeString = String(hour) + ":" + minuteString + " " + AMPMString let label = app.staticTexts[constructedTimeString] let exists = NSPredicate(format: "exists == true") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) } }
// // ViewController.swift // SegmentedControlExample // // Created by Domenico Solazzo on 05/05/15. // License MIT // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } Added SegmentedControl; Added initialization code // // ViewController.swift // SegmentedControlExample // // Created by Domenico Solazzo on 05/05/15. // License MIT // import UIKit class ViewController: UIViewController { var segmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let segments = [ "iPhone", "iPad", "iPod", "iMac" ] segmentedControl = UISegmentedControl(items: segments) segmentedControl.center = self.view.center self.view.addSubview(segmentedControl) } }
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib // rdar://78109470 // UNSUPPORTED: back_deployment_runtime // https://bugs.swift.org/browse/SR-14466 // UNSUPPORTED: OS=windows-msvc import _Concurrency import StdlibUnittest import Dispatch struct SomeError: Error, Equatable { var value = Int.random(in: 0..<100) } var tests = TestSuite("AsyncStream") @main struct Main { static func main() async { if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { final class Expectation: UnsafeSendable { var fulfilled = false } tests.test("yield with no awaiting next") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") } } tests.test("yield with no awaiting next throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") } } tests.test("yield with awaiting next") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") } tests.test("yield with awaiting next throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") } tests.test("yield with awaiting next 2 throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and throw") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish(throwing: thrownError) } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") try await iterator.next() expectUnreachable("expected thrown error") } catch { if let failure = error as? SomeError { expectEqual(failure, thrownError) } else { expectUnreachable("unexpected error type") } } } tests.test("yield with no awaiting next detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") } } } tests.test("yield with no awaiting next detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") } } } tests.test("yield with awaiting next detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") } tests.test("yield with awaiting next detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") } tests.test("yield with awaiting next 2 detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and throw detached") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish(throwing: thrownError) } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") try await iterator.next() expectUnreachable("expected thrown error") } catch { if let failure = error as? SomeError { expectEqual(failure, thrownError) } else { expectUnreachable("unexpected error type") } } } tests.test("yield with awaiting next 2 and finish detached with value after finish") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.yield("This should not be emitted") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish detached with value after finish throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.yield("This should not be emitted") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish detached with throw after finish throwing") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.finish(throwing: thrownError) } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish with throw after finish throwing") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.finish(throwing: thrownError) } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("cancellation behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in expectation.fulfilled = true } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("termination behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in expectation.fulfilled = true } continuation.finish() } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable terminal in switch terminal { case .cancelled: expectation.fulfilled = true default: break } } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior on deinit with no values being awaited throwing") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncThrowingStream(String.self) { continuation in continuation.onTermination = { @Sendable terminal in switch terminal { case .cancelled: expectation.fulfilled = true default: break } } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior of value emitted in handler") { let ready = DispatchSemaphore(value: 0) let done = DispatchSemaphore(value: 0) let task = detach { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in continuation.yield("Hit cancel") } } ready.signal() var iterator = series.makeAsyncIterator() let first = await iterator.next() expectEqual(first, "Hit cancel") let second = await iterator.next() expectEqual(second, nil) done.signal() } ready.wait() task.cancel() let result = done.wait(timeout: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 1_000_000_000)) switch result { case .timedOut: expectFalse(true, "Timeout when awaiting finished state") default: break } } tests.test("cancellation behavior of value emitted in handler throwing") { let ready = DispatchSemaphore(value: 0) let done = DispatchSemaphore(value: 0) let task = detach { let series = AsyncThrowingStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in continuation.yield("Hit cancel") } } ready.signal() var iterator = series.makeAsyncIterator() do { let first = try await iterator.next() expectEqual(first, "Hit cancel") let second = try await iterator.next() expectEqual(second, nil) } catch { expectUnreachable("unexpected error thrown") } done.signal() } ready.wait() task.cancel() let result = done.wait(timeout: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 1_000_000_000)) switch result { case .timedOut: expectFalse(true, "Timeout when awaiting finished state") default: break } } await runAllTestsAsync() } } } Disable Concurrency/Runtime/async_stream.swift This test has a race condition which can cause PR testing to fail, blocking other work. rdar://78033828 (Swift CI: timeout) // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib // rdar://78109470 // UNSUPPORTED: back_deployment_runtime // https://bugs.swift.org/browse/SR-14466 // UNSUPPORTED: OS=windows-msvc // Race condition // REQUIRES: rdar78033828 import _Concurrency import StdlibUnittest import Dispatch struct SomeError: Error, Equatable { var value = Int.random(in: 0..<100) } var tests = TestSuite("AsyncStream") @main struct Main { static func main() async { if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { final class Expectation: UnsafeSendable { var fulfilled = false } tests.test("yield with no awaiting next") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") } } tests.test("yield with no awaiting next throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") } } tests.test("yield with awaiting next") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") } tests.test("yield with awaiting next throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") } tests.test("yield with awaiting next 2 throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish") { let series = AsyncStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish throwing") { let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and throw") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish(throwing: thrownError) } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") try await iterator.next() expectUnreachable("expected thrown error") } catch { if let failure = error as? SomeError { expectEqual(failure, thrownError) } else { expectUnreachable("unexpected error type") } } } tests.test("yield with no awaiting next detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") } } } tests.test("yield with no awaiting next detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") } } } tests.test("yield with awaiting next detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") } tests.test("yield with awaiting next detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") } tests.test("yield with awaiting next 2 detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish detached") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish detached throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and throw detached") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish(throwing: thrownError) } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") try await iterator.next() expectUnreachable("expected thrown error") } catch { if let failure = error as? SomeError { expectEqual(failure, thrownError) } else { expectUnreachable("unexpected error type") } } } tests.test("yield with awaiting next 2 and finish detached with value after finish") { let series = AsyncStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.yield("This should not be emitted") } } var iterator = series.makeAsyncIterator() expectEqual(await iterator.next(), "hello") expectEqual(await iterator.next(), "world") expectEqual(await iterator.next(), nil) expectEqual(await iterator.next(), nil) } tests.test("yield with awaiting next 2 and finish detached with value after finish throwing") { let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.yield("This should not be emitted") } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish detached with throw after finish throwing") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in detach { continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.finish(throwing: thrownError) } } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("yield with awaiting next 2 and finish with throw after finish throwing") { let thrownError = SomeError() let series = AsyncThrowingStream(String.self) { continuation in continuation.yield("hello") continuation.yield("world") continuation.finish() continuation.finish(throwing: thrownError) } var iterator = series.makeAsyncIterator() do { expectEqual(try await iterator.next(), "hello") expectEqual(try await iterator.next(), "world") expectEqual(try await iterator.next(), nil) expectEqual(try await iterator.next(), nil) } catch { expectUnreachable("unexpected error thrown") } } tests.test("cancellation behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in expectation.fulfilled = true } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("termination behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in expectation.fulfilled = true } continuation.finish() } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior on deinit with no values being awaited") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable terminal in switch terminal { case .cancelled: expectation.fulfilled = true default: break } } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior on deinit with no values being awaited throwing") { let expectation = Expectation() func scopedLifetime(_ expectation: Expectation) { let series = AsyncThrowingStream(String.self) { continuation in continuation.onTermination = { @Sendable terminal in switch terminal { case .cancelled: expectation.fulfilled = true default: break } } } } scopedLifetime(expectation) expectTrue(expectation.fulfilled) } tests.test("cancellation behavior of value emitted in handler") { let ready = DispatchSemaphore(value: 0) let done = DispatchSemaphore(value: 0) let task = detach { let series = AsyncStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in continuation.yield("Hit cancel") } } ready.signal() var iterator = series.makeAsyncIterator() let first = await iterator.next() expectEqual(first, "Hit cancel") let second = await iterator.next() expectEqual(second, nil) done.signal() } ready.wait() task.cancel() let result = done.wait(timeout: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 1_000_000_000)) switch result { case .timedOut: expectFalse(true, "Timeout when awaiting finished state") default: break } } tests.test("cancellation behavior of value emitted in handler throwing") { let ready = DispatchSemaphore(value: 0) let done = DispatchSemaphore(value: 0) let task = detach { let series = AsyncThrowingStream(String.self) { continuation in continuation.onTermination = { @Sendable _ in continuation.yield("Hit cancel") } } ready.signal() var iterator = series.makeAsyncIterator() do { let first = try await iterator.next() expectEqual(first, "Hit cancel") let second = try await iterator.next() expectEqual(second, nil) } catch { expectUnreachable("unexpected error thrown") } done.signal() } ready.wait() task.cancel() let result = done.wait(timeout: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 1_000_000_000)) switch result { case .timedOut: expectFalse(true, "Timeout when awaiting finished state") default: break } } await runAllTestsAsync() } } }
// REQUIRES: asan_runtime // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -sanitize=address -o %t/%target-library-name(TypesToReflect) // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.Box // CHECK: ------------------ // CHECK: item: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: anEnum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (variadic // CHECK: (struct TypesToReflect.S)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (shared // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: TypesToReflect.S // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: (struct Swift.Int)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> () // CHECK: (function convention=thin // CHECK: (tuple)) // CHECK: aFunctionWithCRepresentation: @convention(c) () -> () // CHECK: (function convention=c // CHECK: (tuple)) // CHECK: TypesToReflect.S.NestedS // CHECK: ------------------------ // CHECK: aField: Swift.Int // CHECK: (struct Swift.Int) // CHECK: TypesToReflect.E // CHECK: ---------------- // CHECK: Class: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: Struct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: Enum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (tuple)) // CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (struct Swift.Int)) // CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: NestedStruct: TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S)) // CHECK: Metatype // CHECK: EmptyCase // CHECK: TypesToReflect.References // CHECK: ------------------------- // CHECK: strongRef: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: weakRef: weak Swift.Optional<TypesToReflect.C> // CHECK: (weak_storage // CHECK: (bound_generic_enum Swift.Optional // CHECK: (class TypesToReflect.C))) // CHECK: unownedRef: unowned TypesToReflect.C // CHECK: (unowned_storage // CHECK: (class TypesToReflect.C)) // CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C // CHECK: (unmanaged_storage // CHECK: (class TypesToReflect.C)) // CHECK: TypesToReflect.C1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: dependentMember: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.C3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.C4 // CHECK: ----------------- // CHECK: TypesToReflect.S1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.S2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.S3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.S4 // CHECK: ----------------- // CHECK: TypesToReflect.E1 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Int: Swift.Int // CHECK: (struct Swift.Int) // CHECK: Function: (A) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: Metatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E2 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S2<A> // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E2<A> // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberInner: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: ExistentialMetatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E3 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberOuter: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: DependentMemberInner: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.E4 // CHECK: ----------------- // CHECK: TypesToReflect.P1 // CHECK: ----------------- // CHECK: TypesToReflect.P2 // CHECK: ----------------- // CHECK: TypesToReflect.P3 // CHECK: ----------------- // CHECK: TypesToReflect.P4 // CHECK: ----------------- // CHECK: TypesToReflect.ClassBoundP // CHECK: -------------------------- // CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}) // CHECK: ------------------------------------------------------------------------- // CHECK: TypesToReflect.HasFileprivateProtocol // CHECK: ------------------------------------- // CHECK: x: TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}) // CHECK: (protocol_composition // CHECK-NEXT: (protocol TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}))) // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P2 // CHECK: typealias Outer = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.E4 : TypesToReflect.P3 // CHECK: typealias First = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: typealias Second = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.S : TypesToReflect.P4 // CHECK: typealias Result = Swift.Int // CHECK: (struct Swift.Int) // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK: CAPTURE DESCRIPTORS: // CHECK: ==================== // CHECK: - Capture types: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (closure_binding index=1) // CHECK: - Capture types: // CHECK: (struct Swift.Int) // CHECK: - Metadata sources: // CHECK: - Capture types: // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=1)) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (generic_argument index=0 // CHECK: (reference_capture index=0)) [Linux] XFAIL typeref_decoding_asan test on linux-aarch64 (#37000) ASan seems to cause reflection information to not be extractable from binaries on aarch64. rdar://76975976 // XFAIL: OS=linux-gnu && CPU=aarch64 // REQUIRES: asan_runtime // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -sanitize=address -o %t/%target-library-name(TypesToReflect) // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.Box // CHECK: ------------------ // CHECK: item: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: anEnum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E