repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
headione/criticalmaps-ios
CriticalMapsKit/Sources/SharedModels/NextRideFeature/Ride.swift
1
3291
import CoreLocation import Foundation import Helpers import MapKit public struct Ride: Hashable, Codable, Identifiable { public let id: Int public let slug: String? public let title: String public let description: String? public let dateTime: Date public let location: String? public let latitude: Double? public let longitude: Double? public let estimatedParticipants: Int? public let estimatedDistance: Double? public let estimatedDuration: Double? public let enabled: Bool public let disabledReason: String? public let disabledReasonMessage: String? public let rideType: RideType? public init( id: Int, slug: String? = nil, title: String, description: String? = nil, dateTime: Date, location: String? = nil, latitude: Double? = nil, longitude: Double? = nil, estimatedParticipants: Int? = nil, estimatedDistance: Double? = nil, estimatedDuration: Double? = nil, enabled: Bool, disabledReason: String? = nil, disabledReasonMessage: String? = nil, rideType: Ride.RideType? = nil ) { self.id = id self.slug = slug self.title = title self.description = description self.dateTime = dateTime self.location = location self.latitude = latitude self.longitude = longitude self.estimatedParticipants = estimatedParticipants self.estimatedDistance = estimatedDistance self.estimatedDuration = estimatedDuration self.enabled = enabled self.disabledReason = disabledReason self.disabledReasonMessage = disabledReasonMessage self.rideType = rideType } } public extension Ride { var coordinate: CLLocationCoordinate2D? { guard let lat = latitude, let lng = longitude else { return nil } return CLLocationCoordinate2D(latitude: lat, longitude: lng) } var titleAndTime: String { let titleWithoutDate = title.removedDatePattern() return """ \(titleWithoutDate) \(rideDateAndTime) """ } var rideDateAndTime: String { "\(dateTime.humanReadableDate) - \(dateTime.humanReadableTime)" } var shareMessage: String { guard let location = location else { return titleAndTime } return """ \(titleAndTime) \(location) """ } } public extension Ride { func openInMaps(_ options: [String: Any] = [ MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault ]) { guard let coordinate = self.coordinate else { debugPrint("Coordinte is nil") return } let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = location mapItem.openInMaps(launchOptions: options) } } public extension Ride { enum RideType: String, CaseIterable, Codable { case criticalMass = "CRITICAL_MASS" case kidicalMass = "KIDICAL_MASS" case nightride = "NIGHT_RIDE" case lunchride = "LUNCH_RIDE" case dawnride = "DAWN_RIDE" case duskride = "DUSK_RIDE" case demonstration = "DEMONSTRATION" case alleycat = "ALLEYCAT" case tour = "TOUR" case event = "EVENT" public var title: String { rawValue .replacingOccurrences(of: "_", with: " ") .capitalized } } }
mit
234681ad57c23f8815a96d6ab0dca6eb
25.756098
79
0.680948
4.290743
false
false
false
false
rcobelli/GameOfficials
Game Officials/LoginViewController.swift
1
2628
// // LoginViewController.swift // Game Officials // // Created by Ryan Cobelli on 1/2/17. // Copyright © 2017 Rybel LLC. All rights reserved. // import UIKit import Alamofire class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var loginButton: UIButton! { didSet { loginButton.layer.cornerRadius = 15 } } @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { if UserDefaults.standard.bool(forKey: "loggedIn") { self.performSegue(withIdentifier: "login", sender: self) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == usernameField { passwordField.becomeFirstResponder() } else { passwordField.resignFirstResponder() login(loginButton) } return true } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } @IBAction func login(_ sender: Any) { let params : Parameters = ["username" : usernameField.text!, "password": passwordField.text!] Alamofire.request("https://rybel-llc.com/game-officials/validateLogin.php", method: .post, parameters: params) .responseData { response in if response.response?.statusCode == 302 { DispatchQueue.global().sync { let alert = UIAlertController(title: "Invalid Username and/or Password", message: "Please try again", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } else if response.response?.statusCode == 200 { UserDefaults.standard.set(self.usernameField.text!, forKey: "username") UserDefaults.standard.set(self.passwordField.text!, forKey: "password") UserDefaults.standard.set(true, forKey: "loggedIn") DispatchQueue.global().sync { self.performSegue(withIdentifier: "login", sender: self) } } else { DispatchQueue.global().sync { let alert = UIAlertController(title: "Something Went Wrong", message: "Please try again", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } @IBAction func forgotPassword(_ sender: Any) { UIApplication.shared.openURL(URL(string: "https://www.gameofficials.net/public/lostPassword.cfm")!) } }
mit
963716655a2e7e86906980fb6bf36b0a
31.036585
153
0.709174
3.962293
false
false
false
false
Flaque/ViewGuru
ViewGuru/ViewGuru.swift
1
2558
// // ViewGuru.swift // ProjectWaitTime // // Created by Evan Conrad on 11/20/15. // Copyright © 2015 Evan Conrad. All rights reserved. // import UIKit /* A Collection of functions for easy manipulation of views * */ class ViewGuru { /* Puts in the center of the parent * */ static func centerViewCompletelyWithinParent(child: UIView, parent: UIView) { centerViewHorizontallyWithinParent(child, parent: parent) centerViewVerticallyWithinParent(child, parent: parent) } /* Puts in the horizontal center of the parent. Keeps y value. * */ static func centerViewHorizontallyWithinParent(child : UIView, parent : UIView) { setViewX(child, x: parent.frame.width/2-child.frame.width*2) } /* Puts in the vertical center of the parent. Keeps x value. * */ static func centerViewVerticallyWithinParent(child: UIView, parent: UIView) { setViewY(child, y: parent.frame.height/2-child.frame.height*2) } /* shortcut for setting x value of a view * */ static func setViewX(view : UIView, x : CGFloat) { var frame : CGRect = view.frame frame.origin.x = x view.frame = frame } /* shortcut for setting y value of a view * */ static func setViewY(view : UIView, y : CGFloat) { var frame : CGRect = view.frame frame.origin.y = y view.frame = frame } /* shortcut for setting the width of a view * */ static func setViewWidth(view : UIView, width : CGFloat) { let frame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y, width: width, height: view.frame.height) view.frame = frame } /* shortcut for setting the height of a view * */ static func setViewHeight(view : UIView, height : CGFloat) { let frame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y, width: view.frame.height, height: height) view.frame = frame } /* Gives the font a black outline to make it more readible on photos * */ static func setUILabelStringPhotoReadible(label: UILabel) { let strokeTextAttributes = [ NSStrokeColorAttributeName : UIColor.blackColor(), NSForegroundColorAttributeName : UIColor.whiteColor(), NSStrokeWidthAttributeName : -2.0, ] label.attributedText = NSAttributedString(string: label.text!, attributes: strokeTextAttributes) } }
mit
7c2ac6600d0d6178c4b7eab81d3e252b
27.10989
104
0.619085
4.254576
false
false
false
false
iachievedit/swiftysockets
Source/TCPServerSocket.swift
1
3156
// TCPServerSocket.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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 Tide import Glibc public final class TCPServerSocket { private var socket: tcpsock public private(set) var closed = false public var port: Int { return Int(tcpport(self.socket)) } public var fileDescriptor: Int32 { return tcpfd(socket) } public init(ip: IP, backlog: Int = 10) throws { self.socket = tcplisten(ip.address, Int32(backlog)) if errno != 0 { closed = true let description = TCPError.lastSystemErrorDescription throw TCPError(description: description) } } public init(fileDescriptor: Int32) throws { self.socket = tcpattach(fileDescriptor, 1) if errno != 0 { closed = true let description = TCPError.lastSystemErrorDescription throw TCPError(description: description) } } deinit { close() } public func accept() throws -> TCPClientSocket { if closed { throw TCPError(description: "Closed socket") } let clientSocket = tcpaccept(socket) if errno != 0 { let description = TCPError.lastSystemErrorDescription throw TCPError(description: description) } return TCPClientSocket(socket: clientSocket) } public func attach(fileDescriptor: Int32) throws { if !closed { tcpclose(socket) } socket = tcpattach(fileDescriptor, 1) if errno != 0 { closed = true let description = TCPError.lastSystemErrorDescription throw TCPError(description: description) } closed = false } public func detach() throws -> Int32 { if closed { throw TCPError(description: "Closed socket") } closed = true return tcpdetach(socket) } public func close() { if !closed { closed = true tcpclose(socket) } } }
mit
1cf754be48ab05ed73cdae78ee401b6e
27.690909
81
0.640368
4.648012
false
false
false
false
gkye/DribbbleSwift
Source/HTTPRequest.swift
1
4311
// // HTTPRequest.swift // DribbbleSwift // // Created by George on 2016-05-06. // Copyright © 2016 George. All rights reserved. // import Foundation public struct ClientReturn{ public var error: NSError? public var json: JSON? public var response: URLResponse? init(error: NSError?, json: JSON?, response: URLResponse?){ self.error = error self.json = json self.response = response } } enum RequestType: String{ case GET, POST, DELETE, PUT } class HTTPRequest{ class func request(_ url: String, parameters: [String: AnyObject]?, requestType: RequestType = .GET, authRequest: Bool = false, completionHandler: @escaping (ClientReturn) -> ()) -> (){ let baseURL = "https://api.dribbble.com/v1"+url var url: URL! var params: [String: AnyObject] = [:] var request: NSMutableURLRequest! switch requestType { case .GET: if(parameters != nil){ params = parameters! } if(!authRequest){ params["access_token"] = access_token as AnyObject? } let parameterString = params.stringFromHttpParameters() url = URL(string: "\(baseURL)?\(parameterString)")! request = NSMutableURLRequest(url: url) default: break; } if(authRequest){ if(requestType == .GET && parameters != nil){ let parameterString = parameters!.stringFromHttpParameters() url = URL(string: "\(baseURL)?\(parameterString)")! }else{ url = URL(string: baseURL) } request = NSMutableURLRequest(url: url) if(OAuth2Token != nil){ request.addValue("Bearer \(OAuth2Token)", forHTTPHeaderField: "Authorization") }else{ fatalError("OAuth token not set!") } } request.httpMethod = requestType.rawValue request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept") let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in DispatchQueue.main.async(execute: { () -> Void in if error == nil{ let json = JSON(data: data!) completionHandler(ClientReturn.init(error: error as NSError?, json: json, response: response)) }else{ print("Error -> \(error)") print(error) completionHandler(ClientReturn.init(error: error as NSError?, json: nil, response: response)) } }) }) task.resume() } } extension String { /// Percent escapes values to be added to a URL query as specified in RFC 3986 /// /// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~". /// /// http://www.ietf.org/rfc/rfc3986.txt /// /// :returns: Returns percent-escaped string. func stringByAddingPercentEncodingForURLQueryValue() -> String? { let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) } } extension Dictionary { /// Build string representation of HTTP parameter dictionary of keys and objects /// /// This percent escapes in compliance with RFC 3986 /// /// http://www.ietf.org/rfc/rfc3986.txt /// /// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped func stringFromHttpParameters() -> String { let parameterArray = self.map { (key, value) -> String in let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()! let percentEscapedValue = (String(describing: value)).stringByAddingPercentEncodingForURLQueryValue()! return "\(percentEscapedKey)=\(percentEscapedValue)" } return parameterArray.joined(separator: "&") } }
mit
ca9cf97e865f70ff26da5b9929889a46
33.48
189
0.590951
5.076561
false
false
false
false
pointfreeco/swift-web
Sources/UrlFormEncoding/UrlFormEncoding.swift
1
2739
import Foundation import Prelude /// Encodes an encodable into `x-www-form-urlencoded` format. It first converts the value into a JSON /// dictionary, and then it encodes that into the format. /// /// - Parameter value: The encodable value to encode. public func urlFormEncode<A: Encodable>(value: A) -> String { return (try? JSONEncoder().encode(value)) .flatMap { try? JSONSerialization.jsonObject(with: $0) } .flatMap { $0 as? [String: Any] } .map(urlFormEncode(value:)) ?? "" } /// Encodes an array into `x-www-form-urlencoded` format. /// /// - Parameters: /// - value: The array of values to encode. /// - rootKey: A root key to hold the array. public func urlFormEncode(values: [Any], rootKey: String) -> String { return urlFormEncode(values: values, rootKey: rootKey, keyConstructor: id) } /// Encodes a dictionary of values into `x-www-form-urlencoded` format. /// /// - Parameter value: The dictionary of values to encode public func urlFormEncode(value: [String: Any]) -> String { return urlFormEncode(value: value, keyConstructor: id) } // MARK: - Private private func urlFormEncode(values: [Any], rootKey: String, keyConstructor: (String) -> String) -> String { return values.enumerated() .map { idx, value in switch value { case let value as [String: Any]: return urlFormEncode(value: value, keyConstructor: { "\(keyConstructor(rootKey))[\(idx)][\($0)]" }) case let values as [Any]: return urlFormEncode( values: values, rootKey: "", keyConstructor: { _ in "\(keyConstructor(rootKey))[\(idx)]" } ) default: return urlFormEncode(value: value, keyConstructor: { _ in "\(keyConstructor(rootKey))[\(idx)]" }) } } .joined(separator: "&") } private func urlFormEncode(value: Any, keyConstructor: (String) -> String) -> String { guard let dictionary = value as? [String: Any] else { let encoded = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryParamAllowed) ?? value return "\(keyConstructor(""))=\(encoded)" } return dictionary .sorted(by: { $0.key < $1.key }) .map { key, value in switch value { case let value as [String: Any]: return urlFormEncode(value: value, keyConstructor: { "\(keyConstructor(key))[\($0)]" }) case let values as [Any]: return urlFormEncode(values: values, rootKey: key, keyConstructor: keyConstructor) default: return urlFormEncode(value: value, keyConstructor: { _ in keyConstructor(key) }) } } .joined(separator: "&") } extension CharacterSet { public static let urlQueryParamAllowed = CharacterSet.urlQueryAllowed .subtracting(.init(charactersIn: ":#[]@!$&'()*+,;=")) }
mit
295375b22501845ebf1095c982c53861
33.2375
107
0.656809
3.890625
false
false
false
false
kenwilcox/WeeDate
WeeDate/MatchesTableViewController.swift
1
2732
// // MatchesTableViewController.swift // WeeDate // // Created by Kenneth Wilcox on 7/9/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import UIKit class MatchesTableViewController: UITableViewController { var matches: [Match] = [] 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() navigationItem.titleView = UIImageView(image: UIImage(named: "chat-header")) let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav-back-button"), style: .Plain, target: self, action: "goToPreviousVC:") navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: true) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchMatches({ matches in self.matches = matches self.tableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func goToPreviousVC(button: UIBarButtonItem) { pageController.goToPreviousVC() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return matches.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as! UserCell // Configure the cell... let user = matches[indexPath.row].user cell.nameLabel.text = user.name user.getPhoto({ image in cell.avatarImageView.image = image }) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = ChatViewController() vc.recipient = matches[indexPath.row].user let match = matches[indexPath.row] vc.matchID = match.id vc.title = match.user.name navigationController?.pushViewController(vc, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
e69ebf7fc42c6394d1b18031ec2d0c78
29.696629
141
0.711933
5.049908
false
false
false
false
firebase/firebase-ios-sdk
FirebaseSharedSwift/Sources/third_party/FirebaseDataEncoder/FirebaseDataEncoder.swift
1
110271
// This file is derived from swift/stdlib/public/Darwin/Foundation/JSONEncoder.swift //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation public protocol StructureCodingPassthroughTypeResolver { static func isPassthroughType<T>(_ t: T) -> Bool } private struct NoPassthroughTypes: StructureCodingPassthroughTypeResolver { static func isPassthroughType<T>(_ t: T) -> Bool { return false } } public protocol StructureCodingUncodedUnkeyed {} extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. fileprivate static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { return "\(type(of: value))" } } } /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary` /// containing `Encodable` values (in which case it should be exempt from key conversion strategies). /// /// NOTE: The architecture and environment check is due to a bug in the current (2018-08-08) Swift 4.2 /// runtime when running on i386 simulator. The issue is tracked in https://bugs.swift.org/browse/SR-8276 /// Making the protocol `internal` instead of `fileprivate` works around this issue. /// Once SR-8276 is fixed, this check can be removed and the protocol always be made fileprivate. #if arch(i386) || arch(arm) internal protocol _JSONStringDictionaryEncodableMarker { } #else fileprivate protocol _JSONStringDictionaryEncodableMarker { } #endif extension Dictionary : _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { } /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary` /// containing `Decodable` values (in which case it should be exempt from key conversion strategies). /// /// The marker protocol also provides access to the type of the `Decodable` values, /// which is needed for the implementation of the key conversion strategy exemption. /// /// NOTE: Please see comment above regarding SR-8276 #if arch(i386) || arch(arm) internal protocol _JSONStringDictionaryDecodableMarker { static var elementType: Decodable.Type { get } } #else fileprivate protocol _JSONStringDictionaryDecodableMarker { static var elementType: Decodable.Type { get } } #endif extension Dictionary : _JSONStringDictionaryDecodableMarker where Key == String, Value: Decodable { static var elementType: Decodable.Type { return Value.self } } //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. // NOTE: older overlays had Foundation.JSONEncoder as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtC10Foundation13__JSONEncoder is the // mangled name for Foundation.__JSONEncoder. public class FirebaseDataEncoder { // MARK: Options /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Swift.Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Swift.Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words : [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// A type that can resolve which types to 'pass through' - or leave alone while encoding. Defaults to not passing any types through. open var passthroughTypeResolver: StructureCodingPassthroughTypeResolver.Type = NoPassthroughTypes.self /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let passthroughTypeResolver: StructureCodingPassthroughTypeResolver.Type let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, passthroughTypeResolver: passthroughTypeResolver, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Any { let encoder = __JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw Swift.EncodingError.invalidValue(value, Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } return topLevel } } // MARK: - __JSONEncoder // NOTE: older overlays called this class _JSONEncoder. // The two must coexist without a conflicting ObjC class name, so it // was renamed. The old name must not be used in the new runtime. fileprivate class __JSONEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _JSONEncodingStorage /// Options set on the top-level encoder. fileprivate let options: FirebaseDataEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: FirebaseDataEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _JSONEncodingStorage() self.codingPath = codingPath } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _JSONEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: __owned NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: __JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations private func _converted(_ key: CodingKey) -> CodingKey { switch encoder.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = FirebaseDataEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _JSONKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { if T.self is StructureCodingUncodedUnkeyed.Type { return } self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let containerKey = _converted(key).stringValue let dictionary: NSMutableDictionary if let existingContainer = self.container[containerKey] { precondition( existingContainer is NSMutableDictionary, "Attempt to re-encode into nested KeyedEncodingContainer<\(Key.self)> for key \"\(containerKey)\" is invalid: non-keyed container already encoded for this key" ) dictionary = existingContainer as! NSMutableDictionary } else { dictionary = NSMutableDictionary() self.container[containerKey] = dictionary } self.codingPath.append(key) defer { self.codingPath.removeLast() } let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let containerKey = _converted(key).stringValue let array: NSMutableArray if let existingContainer = self.container[containerKey] { precondition( existingContainer is NSMutableArray, "Attempt to re-encode into nested UnkeyedEncodingContainer for key \"\(containerKey)\" is invalid: keyed container/single value already encoded for this key" ) array = existingContainer as! NSMutableArray } else { array = NSMutableArray() self.container[containerKey] = array } self.codingPath.append(key) defer { self.codingPath.removeLast() } return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return __JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return __JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container) } } fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: __JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return __JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension __JSONEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } } // MARK: - Concrete Value Representations extension __JSONEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count do { try closure(date, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. let depth = self.storage.count do { try data.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count do { try closure(data, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ dict: [String : Encodable]) throws -> NSObject? { let depth = self.storage.count let result = self.storage.pushKeyedContainer() do { for (key, value) in dict { self.codingPath.append(_JSONKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try box(value) } } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } fileprivate func box(_ value: Encodable) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want. fileprivate func box_(_ value: Encodable) throws -> NSObject? { // Disambiguation between variable and function is required due to // issue tracked at: https://bugs.swift.org/browse/SR-1846 let type = Swift.type(of: value) if type == Date.self || type == NSDate.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if type == Data.self || type == NSData.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if type == URL.self || type == NSURL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if type == Decimal.self || type == NSDecimalNumber.self { // JSONSerialization can natively handle NSDecimalNumber. return (value as! NSDecimalNumber) } else if value is _JSONStringDictionaryEncodableMarker { return try self.box(value as! [String : Encodable]) } else if let object = value as? NSObject, self.options.passthroughTypeResolver.isPassthroughType(value) { return object } // The value should request a container from the __JSONEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } } // MARK: - __JSONReferencingEncoder /// __JSONReferencingEncoder is a special subclass of __JSONEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). // NOTE: older overlays called this class _JSONReferencingEncoder. // The two must coexist without a conflicting ObjC class name, so it // was renamed. The old name must not be used in the new runtime. fileprivate class __JSONReferencingEncoder : __JSONEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: __JSONEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: __JSONEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_JSONKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: __JSONEncoder, key: CodingKey, convertedKey: __shared CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, convertedKey.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // JSON Decoder //===----------------------------------------------------------------------===// /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types. // NOTE: older overlays had Foundation.JSONDecoder as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtC10Foundation13__JSONDecoder is the // mangled name for Foundation.__JSONDecoder. public class FirebaseDataDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a JSON number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Swift.Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Swift.Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore) } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex let components = stringKey[keyRange].split(separator: "_") let joinedString : String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result : String if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) { result = joinedString } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if (!leadingUnderscoreRange.isEmpty) { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// A type that can resolve which types to 'pass through' - or leave alone while decoding. Defaults to not passing any types through. open var passthroughTypeResolver: StructureCodingPassthroughTypeResolver.Type = NoPassthroughTypes.self /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let passthroughTypeResolver: StructureCodingPassthroughTypeResolver.Type let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, passthroughTypeResolver: passthroughTypeResolver, userInfo: userInfo) } // MARK: - Constructing a JSON Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given JSON representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from structure: Any) throws -> T { let decoder = __JSONDecoder(referencing: structure, options: self.options) guard let value = try decoder.unbox(structure, as: type) else { throw Swift.DecodingError.valueNotFound(type, Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.")) } return value } } // MARK: - __JSONDecoder // NOTE: older overlays called this class _JSONDecoder. The two must // coexist without a conflicting ObjC class name, so it was renamed. // The old name must not be used in the new runtime. fileprivate class __JSONDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _JSONDecodingStorage /// Options set on the top-level decoder. fileprivate let options: FirebaseDataDecoder._Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: FirebaseDataDecoder._Options) { self.storage = _JSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } var topContainer : [String : Any] if let rcValue = self.storage.topContainer as? FirebaseRemoteConfigValueDecoding { guard let top = rcValue.dictionaryValue() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: rcValue) } topContainer = top } else { guard let top = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } topContainer = top } let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } if let rcValue = self.storage.topContainer as? FirebaseRemoteConfigValueDecoding { guard let arrayValue = rcValue.arrayValue() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: rcValue) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: arrayValue ) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _JSONDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: __owned Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(!self.containers.isEmpty, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: __JSONDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [String : Any]) { self.decoder = decoder switch decoder.options.keyDecodingStrategy { case .useDefaultKeys: self.container = container case .convertFromSnakeCase: // Convert the snake case keys in the container to camel case. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries. self.container = Dictionary(container.map { key, value in (FirebaseDataDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value) }, uniquingKeysWith: { (first, _) in first }) case .custom(let converter): self.container = Dictionary(container.map { key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value) }, uniquingKeysWith: { (first, _) in first }) } self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } private func _errorDescription(of key: CodingKey) -> String { switch decoder.options.keyDecodingStrategy { case .convertFromSnakeCase: // In this case we can attempt to recover the original value by reversing the transform let original = key.stringValue let converted = FirebaseDataEncoder.KeyEncodingStrategy._convertToSnakeCase(original) let roundtrip = FirebaseDataDecoder.KeyDecodingStrategy._convertFromSnakeCase(converted) if converted == original { return "\(key) (\"\(original)\")" } else if roundtrip == original { return "\(key) (\"\(original)\"), converted to \(converted)" } else { return "\(key) (\"\(original)\"), with divergent representation \(roundtrip), converted to \(converted)" } default: // Otherwise, just report the converted string return "\(key) (\"\(key.stringValue)\")" } } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { if type is StructureCodingUncodedUnkeyed.Type { // Note: not pushing and popping key to codingPath since the key is // not part of the decoded structure. return try T.init(from: self.decoder) } guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: __owned CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = self.container[key.stringValue] ?? NSNull() return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _JSONKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: __JSONDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } extension __JSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(type) return try self.unbox(self.storage.topContainer, as: type)! } } // MARK: - Concrete Value Representations extension __JSONDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } if let rcValue = value as? FirebaseRemoteConfigValueDecoding { return rcValue.boolValue() } if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func rcValNumberAdaptor(_ value: Any) -> Any { if let rcValue = value as? FirebaseRemoteConfigValueDecoding { return rcValue.numberValue() } return value } fileprivate func getNumber(_ value: Any, as type: Any.Type) throws -> NSNumber { let val = rcValNumberAdaptor(value) guard let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: val) } return number } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } let number = try getNumber(value, as: type) let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } let val = rcValNumberAdaptor(value) if let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = val as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } let val = rcValNumberAdaptor(value) if let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = val as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } if let rcValue = value as? FirebaseRemoteConfigValueDecoding { return rcValue.stringValue() } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) defer { self.storage.popContainer() } return try Date(from: self) case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } if let rcValue = value as? FirebaseRemoteConfigValueDecoding { return rcValue.dataValue() } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) defer { self.storage.popContainer() } return try Data(from: self) case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } let val = rcValNumberAdaptor(value) // Attempt to bridge from NSDecimalNumber. if let decimal = val as? Decimal { return decimal } else { let doubleValue = try self.unbox(val, as: Double.self)! return Decimal(doubleValue) } } fileprivate func unbox<T>(_ value: Any, as type: _JSONStringDictionaryDecodableMarker.Type) throws -> T? { guard !(value is NSNull) else { return nil } if let rcValue = value as? FirebaseRemoteConfigValueDecoding { guard let dictionaryValue = rcValue.dictionaryValue() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: rcValue) } return dictionaryValue as? T } var result = [String : Any]() guard let dict = value as? NSDictionary else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let elementType = type.elementType for (key, value) in dict { let key = key as! String self.codingPath.append(_JSONKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try unbox_(value, as: elementType) } return result as? T } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { return try unbox_(value, as: type) as? T } fileprivate func unbox_(_ value: Any, as _type: Decodable.Type) throws -> Any? { if _type == Date.self || _type == NSDate.self { return try self.unbox(value, as: Date.self) } else if _type == Data.self || _type == NSData.self { return try self.unbox(value, as: Data.self) } else if _type == URL.self || _type == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url } else if _type == Decimal.self || _type == NSDecimalNumber.self { return try self.unbox(value, as: Decimal.self) } else if let stringKeyedDictType = _type as? _JSONStringDictionaryDecodableMarker.Type { return try self.unbox(value, as: stringKeyedDictType) } else { self.storage.push(container: value) defer { self.storage.popContainer() } if self.options.passthroughTypeResolver.isPassthroughType(value) && type(of: value) == _type { return value } return try _type.init(from: self) } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _JSONKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
apache-2.0
023fa4058ae01c6b9e5a455cb271506e
40.848577
321
0.696094
4.663608
false
false
false
false
zhaobin19918183/zhaobinCode
swift_NavigationController/swift_iPad/HomeViewController.swift
1
4876
// // HomeViewController.swift // swift_iPad // // Created by Zhao.bin on 16/3/25. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import Result import Alamofire class HomeViewController: UIViewController,UIPopoverPresentationControllerDelegate,popViewControllerDelegate { @IBOutlet weak var textImageVIew: UIImageView! @IBOutlet weak var popbutton: UIButton! var HUDProgtess = MBProgressHUD() var delegate : popViewControllerDelegate! let BaiduURL = "http://apis.haoservice.com/lifeservice/cook/query?" var basketballTeamName:NSMutableArray! var progressView: UIProgressView! var remainTime = 100 override func viewDidLoad() { super.viewDidLoad() } func progressAction() { // 初始化 progressView progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Bar) progressView.frame = CGRectMake(self.view.frame.width/2 - 50, 200, 300, 100) // 设置初始值 progressView.progress = 1.0 // 设置进度条颜色 progressView.progressTintColor = UIColor.blueColor() // 设置进度轨迹颜色 progressView.trackTintColor = UIColor.greenColor() // 扩展:可以通过 progressImage、trackImage 属性自定义出个性进度条 self.view.addSubview(progressView) reloadData() } func reloadData() { let url = "http://img2.imgtn.bdimg.com/it/u=1457437487,655486635&fm=11&gp=0.jpg" AlamofireView.alamofireDelegate(url, complete: { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in let percent = totalBytesRead*100/totalBytesExpectedToRead self.remainTime = self.remainTime - Int(percent) self.progressView.setProgress(Float(self.remainTime)/100, animated:true) print("已下载:\(totalBytesRead) 当前进度:\(percent)%") }) // { (request, response, data, error) in // // let fileManager = NSFileManager.defaultManager() // let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, // inDomains: .UserDomainMask)[0] // let pathComponent = response!.suggestedFilename // print(directoryURL.URLByAppendingPathComponent(pathComponent!)) // print(response) // // } } func defaultShow(){ HUDProgtess = MBProgressHUD.showHUDAddedTo(self.view, animated: true) HUDProgtess.labelText = "正在同步请稍等....." //背景渐变效果 HUDProgtess.dimBackground = true } func hiddenHUD() { HUDProgtess.mode = MBProgressHUDMode.CustomView HUDProgtess.customView = UIImageView(image: UIImage(named: "yes")!) HUDProgtess.labelText = "这是自定义视图" //延迟隐藏 HUDProgtess.hide(true, afterDelay: 1) } //MARK:popViewControllerDelegate @IBAction func popobuttonAction(sender: UIButton) { popViewController.collectionSeletctNmuber(10) let pop = popViewController() pop.delegate = self pop.modalPresentationStyle = .Popover pop.popoverPresentationController?.delegate = self pop.popoverPresentationController?.sourceView = popbutton pop.popoverPresentationController?.sourceRect = CGRectZero pop.popoverPresentationController?.sourceRect = popbutton.bounds pop.preferredContentSize = CGSizeMake(300, 400) pop.popoverPresentationController?.permittedArrowDirections = .Up self.presentViewController(pop, animated: true, completion: nil) } func popViewControllerPhotosArray(photosImage: UIImage) { self.textImageVIew.image = photosImage print(photosImage.size.width) } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func toJSONString(dict:NSMutableDictionary!)->NSString{ let data = try?NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted) let strJson=NSString(data: data!, encoding: NSUTF8StringEncoding) return strJson! } } /* // 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. } */
gpl-3.0
ed569d69f89fa3e1c72a6717fc513493
31.349315
127
0.645141
5.08944
false
false
false
false
zhouhao27/WOWMarkSlider
Example/Tests/Tests.swift
1
1163
// https://github.com/Quick/Quick import Quick import Nimble import WOWMarkSlider class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
ccb8bb868e2381f251e58bfb0c377110
22.14
60
0.359551
5.483412
false
false
false
false
FirasAKAK/FInAppNotifications
FNotificationVoicePlayerExtensionView.swift
1
5995
// // FNotificationVoicePlayerExtensionView.swift // FInAppNotification // // Created by Firas Al Khatib Al Khalidi on 7/5/17. // Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved. // import UIKit import AVFoundation class FNotificationVoicePlayerExtensionView: FNotificationExtensionView { var audioPlayer : AVPlayer! var timeObserver : Any? var didPlayRecording : (()-> Void)? override var height : CGFloat{ return 100 } var dataUrl: String!{ didSet{ guard dataUrl != nil else { return } audioPlayer = AVPlayer(playerItem: AVPlayerItem(asset: AVAsset(url: URL(fileURLWithPath: dataUrl)))) NotificationCenter.default.addObserver(self, selector: #selector(itemDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: audioPlayer.currentItem!) timeSlider.minimumValue = 0 timeSlider.maximumValue = Float(audioPlayer.currentItem!.asset.duration.seconds) timeSlider.value = Float(audioPlayer.currentTime().seconds) timeSlider.isEnabled = true playPauseButton.isEnabled = true addTimeObserver() timeLabel.text = initialTimeString let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped)) addGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer.delegate = self } } func viewTapped(){ } deinit { NotificationCenter.default.removeObserver(self) } @IBOutlet weak var timeSlider : UISlider! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var timeLabel: UILabel! var didFinishPlaying = false @objc private func itemDidFinishPlaying(){ timeSlider.setValue(0, animated: true) playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) audioPlayer.currentItem?.seek(to: CMTime(seconds: 0, preferredTimescale: 1), completionHandler: { (completed) in self.didFinishPlaying = true self.timeLabel.text = self.initialTimeString }) } private var initialTimeString: String{ let time = Int(audioPlayer.currentItem!.asset.duration.seconds) let minutes = time/60 let seconds = time-(minutes*60) var timeString = "" if minutes < 10{ timeString = "0\(minutes)" } else{ timeString = "\(minutes)" } if seconds < 10{ timeString = timeString + ":0\(seconds)" } else{ timeString = timeString + ":\(seconds)" } return timeString } private var currentTimeString: String{ let time = Int(audioPlayer.currentItem!.currentTime().seconds) let minutes = time/60 let seconds = time-(minutes*60) var timeString = "" if minutes < 10{ timeString = "0\(minutes)" } else{ timeString = "\(minutes)" } if seconds < 10{ timeString = timeString + ":0\(seconds)" } else{ timeString = timeString + ":\(seconds)" } if audioPlayer.rate == 0 && seconds == 0{ return initialTimeString } return timeString } override func awakeFromNib() { super.awakeFromNib() addPlayPauseButtonBorder() } private func addPlayPauseButtonBorder(){ playPauseButton.layer.cornerRadius = 5 playPauseButton.layer.masksToBounds = true playPauseButton.layer.borderColor = UIColor.white.cgColor playPauseButton.layer.borderWidth = 1 } private func addTimeObserver(){ timeObserver = audioPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1), queue: DispatchQueue.main) { (time) in if !self.timeSlider.isHighlighted{ DispatchQueue.main.async { guard self.audioPlayer != nil else{ return } self.timeSlider.value = Float(self.audioPlayer.currentTime().seconds) self.timeLabel.text = self.currentTimeString } } } } @IBAction func timeSliderValueChanged(_ sender: UISlider) { guard audioPlayer != nil else{ return } var wasPlaying = false if audioPlayer.rate != 0{ audioPlayer.pause() wasPlaying = true } if timeObserver != nil{ audioPlayer.removeTimeObserver(timeObserver!) } audioPlayer.currentItem?.seek(to: CMTime(seconds: Double(sender.value)+0.5, preferredTimescale: 1), completionHandler: { (Bool) in guard self.audioPlayer != nil else{ return } self.addTimeObserver() self.timeLabel.text = self.currentTimeString if wasPlaying{ self.audioPlayer.play() self.playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } }) } @IBAction func playPauseButtonPressed(_ sender: UIButton) { didPlayRecording?() didPlayRecording = nil if audioPlayer.rate != 0{ audioPlayer.pause() playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) } else{ audioPlayer.play() playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } } } extension FNotificationVoicePlayerExtensionView: UIGestureRecognizerDelegate{ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } }
mit
a3e0d4b5706c8020a01becc518d4ca64
36
189
0.602436
5.385445
false
false
false
false
rockbruno/SlidingGradientView
SlidingGradientView/Sources/SlidingProperties.swift
1
372
import UIKit public struct SlidingProperties { let fromX: CGFloat let toX: CGFloat let animationDuration: TimeInterval public init(fromX: CGFloat = 0, toX: CGFloat = UIScreen.main.bounds.width * 1.2, animationDuration: TimeInterval = 0.7) { self.fromX = fromX self.toX = toX self.animationDuration = animationDuration } }
mit
2c2e917233e46b180c9501ff2ed27800
27.615385
125
0.674731
4.536585
false
false
false
false
mamouneyya/TheSkillsProof
Pods/p2.OAuth2/Sources/iOS/OAuth2WebViewController.swift
1
7025
// // OAuth2WebViewController.swift // OAuth2 // // Created by Pascal Pfiffner on 7/15/14. // Copyright 2014 Pascal Pfiffner // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit /** A simple iOS web view controller that allows you to display the login/authorization screen. */ public class OAuth2WebViewController: UIViewController, UIWebViewDelegate { /// Handle to the OAuth2 instance in play, only used for debug lugging at this time. var oauth: OAuth2? /// The URL to load on first show. public var startURL: NSURL? { didSet(oldURL) { if nil != startURL && nil == oldURL && isViewLoaded() { loadURL(startURL!) } } } /// The URL string to intercept and respond to. var interceptURLString: String? { didSet(oldURL) { if nil != interceptURLString { if let url = NSURL(string: interceptURLString!) { interceptComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) } else { oauth?.logIfVerbose("Failed to parse URL \(interceptURLString), discarding") interceptURLString = nil } } else { interceptComponents = nil } } } var interceptComponents: NSURLComponents? /// Closure called when the web view gets asked to load the redirect URL, specified in `interceptURLString`. Return a Bool indicating /// that you've intercepted the URL. var onIntercept: ((url: NSURL) -> Bool)? /// Called when the web view is about to be dismissed. var onWillDismiss: ((didCancel: Bool) -> Void)? /// Assign to override the back button, shown when it's possible to go back in history. Will adjust target/action accordingly. public var backButton: UIBarButtonItem? { didSet { if let backButton = backButton { backButton.target = self backButton.action = "goBack:" } } } var cancelButton: UIBarButtonItem? /// Our web view. var webView: UIWebView? /// An overlay view containing a spinner. var loadingView: UIView? init() { super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - View Handling override public func loadView() { edgesForExtendedLayout = .All extendedLayoutIncludesOpaqueBars = true automaticallyAdjustsScrollViewInsets = true super.loadView() view.backgroundColor = UIColor.whiteColor() cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:") navigationItem.rightBarButtonItem = cancelButton // create a web view let web = UIWebView() web.translatesAutoresizingMaskIntoConstraints = false web.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal web.delegate = self view.addSubview(web) let views = ["web": web] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[web]|", options: [], metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[web]|", options: [], metrics: nil, views: views)) webView = web } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let web = webView where !web.canGoBack { if nil != startURL { loadURL(startURL!) } else { web.loadHTMLString("There is no `startURL`", baseURL: nil) } } } func showHideBackButton(show: Bool) { if show { let bb = backButton ?? UIBarButtonItem(barButtonSystemItem: .Rewind, target: self, action: "goBack:") navigationItem.leftBarButtonItem = bb } else { navigationItem.leftBarButtonItem = nil } } func showLoadingIndicator() { // TODO: implement } func hideLoadingIndicator() { // TODO: implement } func showErrorMessage(message: String, animated: Bool) { NSLog("Error: \(message)") } // MARK: - Actions public func loadURL(url: NSURL) { webView?.loadRequest(NSURLRequest(URL: url)) } func goBack(sender: AnyObject?) { webView?.goBack() } func cancel(sender: AnyObject?) { dismiss(asCancel: true, animated: nil != sender ? true : false) } func dismiss(animated animated: Bool) { dismiss(asCancel: false, animated: animated) } func dismiss(asCancel asCancel: Bool, animated: Bool) { webView?.stopLoading() if nil != self.onWillDismiss { self.onWillDismiss!(didCancel: asCancel) } dismissViewControllerAnimated(animated, completion: nil) } // MARK: - Web View Delegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if nil == onIntercept { return true } // we compare the scheme and host first, then check the path (if there is any). Not sure if a simple string comparison // would work as there may be URL parameters attached if let url = request.URL where url.scheme == interceptComponents?.scheme && url.host == interceptComponents?.host { let haveComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) if let hp = haveComponents?.path, ip = interceptComponents?.path where hp == ip || ("/" == hp + ip) { return !onIntercept!(url: url) } } return true } public func webViewDidStartLoad(webView: UIWebView) { if "file" != webView.request?.URL?.scheme { showLoadingIndicator() } } /* Special handling for Google's `urn:ietf:wg:oauth:2.0:oob` callback */ public func webViewDidFinishLoad(webView: UIWebView) { if let scheme = interceptComponents?.scheme where "urn" == scheme { if let path = interceptComponents?.path where path.hasPrefix("ietf:wg:oauth:2.0:oob") { if let title = webView.stringByEvaluatingJavaScriptFromString("document.title") where title.hasPrefix("Success ") { oauth?.logIfVerbose("Creating redirect URL from document.title") let qry = title.stringByReplacingOccurrencesOfString("Success ", withString: "") if let url = NSURL(string: "http://localhost/?\(qry)") { onIntercept?(url: url) return } else { oauth?.logIfVerbose("Failed to create a URL with query parts \"\(qry)\"") } } } } hideLoadingIndicator() showHideBackButton(webView.canGoBack) } public func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { if NSURLErrorDomain == error?.domain && NSURLErrorCancelled == error?.code { return } // do we still need to intercept "WebKitErrorDomain" error 102? if nil != loadingView { showErrorMessage(error?.localizedDescription ?? "Unknown web view load error", animated: true) } } }
mit
785108fe0c373c9d46cc19391425b859
28.028926
141
0.703488
4.009703
false
false
false
false
gottesmm/swift
test/SILGen/addressors.swift
3
28277
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-stdlib -emit-sil %s | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-stdlib -emit-silgen %s | %FileCheck %s -check-prefix=SILGEN import Swift func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } struct A { var base: UnsafeMutablePointer<Int32> = someValidPointer() subscript(index: Int32) -> Int32 { unsafeAddress { return UnsafePointer(base) } unsafeMutableAddress { return base } } } // CHECK-LABEL: sil hidden @_T010addressors1AV9subscripts5Int32VAFcflu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A): // CHECK: [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base // CHECK: [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer) // CHECK: return [[T1]] : $UnsafePointer<Int32> // CHECK-LABEL: sil hidden @_T010addressors1AV9subscripts5Int32VAFcfau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A): // CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*A, #A.base // CHECK: [[BASE:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: return [[BASE]] : $UnsafeMutablePointer<Int32> // CHECK-LABEL: sil hidden @_T010addressors5test0yyF : $@convention(thin) () -> () { func test0() { // CHECK: [[A:%.*]] = alloc_stack $A // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[T1:%.*]] = metatype $@thin A.Type // CHECK: [[AVAL:%.*]] = apply [[T0]]([[T1]]) // CHECK: store [[AVAL]] to [[A]] var a = A() // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AV9subscripts5Int32VAFcflu : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[Z:%.*]] = load [[T3]] : $*Int32 let z = a[10] // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AV9subscripts5Int32VAFcfau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[A]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: load // CHECK: sadd_with_overflow_Int{{32|64}} // CHECK: store {{%.*}} to [[T3]] a[5] += z // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AV9subscripts5Int32VAFcfau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[A]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: store {{%.*}} to [[T3]] a[3] = 6 } // CHECK-LABEL: sil hidden @_T010addressors5test1s5Int32VyF : $@convention(thin) () -> Int32 func test1() -> Int32 { // CHECK: [[CTOR:%.*]] = function_ref @_T010addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[T0:%.*]] = metatype $@thin A.Type // CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thin A.Type) -> A // CHECK: [[ACCESSOR:%.*]] = function_ref @_T010addressors1AV9subscripts5Int32VAFcflu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = load [[T1]] : $*Int32 // CHECK: return [[T2]] : $Int32 return A()[0] } let uninitAddr = UnsafeMutablePointer<Int32>.allocate(capacity: 1) var global: Int32 { unsafeAddress { return UnsafePointer(uninitAddr) } // CHECK: sil hidden @_T010addressors6globals5Int32Vflu : $@convention(thin) () -> UnsafePointer<Int32> { // CHECK: [[T0:%.*]] = global_addr @_T010addressors10uninitAddrSpys5Int32VGv : $*UnsafeMutablePointer<Int32> // CHECK: [[T1:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = struct $UnsafePointer<Int32> ([[T2]] : $Builtin.RawPointer) // CHECK: return [[T3]] : $UnsafePointer<Int32> } func test_global() -> Int32 { return global } // CHECK: sil hidden @_T010addressors11test_globals5Int32VyF : $@convention(thin) () -> Int32 { // CHECK: [[T0:%.*]] = function_ref @_T010addressors6globals5Int32Vflu : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T1:%.*]] = apply [[T0]]() : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T4:%.*]] = load [[T3]] : $*Int32 // CHECK: return [[T4]] : $Int32 // Test that having generated trivial accessors for something because // of protocol conformance doesn't force us down inefficient access paths. protocol Subscriptable { subscript(i: Int32) -> Int32 { get set } } struct B : Subscriptable { subscript(i: Int32) -> Int32 { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } // CHECK: sil hidden @_T010addressors6test_ByAA1BVzF : $@convention(thin) (@inout B) -> () { // CHECK: bb0([[B:%.*]] : $*B): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 0 // CHECK: [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[RHS:%.*]] = integer_literal $Builtin.Int32, 7 // CHECK: [[T0:%.*]] = function_ref @_T010addressors1BV9subscripts5Int32VAFcfau // CHECK: [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[B]]) // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // Accept either of struct_extract+load or load+struct_element_addr. // CHECK: load // CHECK: [[T1:%.*]] = builtin "or_Int32" // CHECK: [[T2:%.*]] = struct $Int32 ([[T1]] : $Builtin.Int32) // CHECK: store [[T2]] to [[ADDR]] : $*Int32 func test_B(_ b: inout B) { b[0] |= 7 } // Test that we handle abstraction difference. struct CArray<T> { var storage: UnsafeMutablePointer<T> subscript(index: Int) -> T { unsafeAddress { return UnsafePointer(storage) + index } unsafeMutableAddress { return storage + index } } } func id_int(_ i: Int32) -> Int32 { return i } // CHECK-LABEL: sil hidden @_T010addressors11test_carrays5Int32VAA6CArrayVyAdDcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: bb0([[ARRAY:%.*]] : $*CArray<(Int32) -> Int32>): func test_carray(_ array: inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: [[T0:%.*]] = function_ref @_T010addressors6CArrayV9subscriptxSicfau : // CHECK: [[T1:%.*]] = apply [[T0]]<(Int32) -> Int32>({{%.*}}, [[ARRAY]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<(Int32) -> Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*@callee_owned (@in Int32) -> @out Int32 // CHECK: store {{%.*}} to [[T3]] : array[0] = id_int // CHECK: [[T0:%.*]] = load [[ARRAY]] // CHECK: [[T1:%.*]] = function_ref @_T010addressors6CArrayV9subscriptxSicflu : // CHECK: [[T2:%.*]] = apply [[T1]]<(Int32) -> Int32>({{%.*}}, [[T0]]) // CHECK: [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<(Int32) -> Int32>, #UnsafePointer._rawValue // CHECK: [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to [strict] $*@callee_owned (@in Int32) -> @out Int32 // CHECK: [[T5:%.*]] = load [[T4]] return array[1](5) } // rdar://17270560, redux struct D : Subscriptable { subscript(i: Int32) -> Int32 { get { return i } unsafeMutableAddress { return someValidPointer() } } } // Setter. // SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DV9subscripts5Int32VAFcfs // SILGEN: bb0([[VALUE:%.*]] : $Int32, [[I:%.*]] : $Int32, [[SELF:%.*]] : $*D): // SILGEN: debug_value [[VALUE]] : $Int32 // SILGEN: debug_value [[I]] : $Int32 // SILGEN: debug_value_addr [[SELF]] // SILGEN: [[T0:%.*]] = function_ref @_T010addressors1DV9subscripts5Int32VAFcfau{{.*}} // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF]]) // SILGEN: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // SILGEN: assign [[VALUE]] to [[ADDR]] : $*Int32 // materializeForSet. // SILGEN: sil hidden [transparent] @_T010addressors1DV9subscripts5Int32VAFcfm // SILGEN: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[I:%.*]] : $Int32, [[SELF:%.*]] : $*D): // SILGEN: [[T0:%.*]] = function_ref @_T010addressors1DV9subscripts5Int32VAFcfau // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF]]) // SILGEN: [[ADDR_TMP:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[ADDR_TMP]] // SILGEN: [[PTR:%.*]] = address_to_pointer [[ADDR]] // SILGEN: [[OPT:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // SILGEN: [[T2:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[OPT]] : $Optional<Builtin.RawPointer>) // SILGEN: return [[T2]] : func make_int() -> Int32 { return 0 } func take_int_inout(_ value: inout Int32) {} // CHECK-LABEL: sil hidden @_T010addressors6test_ds5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32 // CHECK: bb0([[ARRAY:%.*]] : $*D): func test_d(_ array: inout D) -> Int32 { // CHECK: [[T0:%.*]] = function_ref @_T010addressors8make_ints5Int32VyF // CHECK: [[V:%.*]] = apply [[T0]]() // CHECK: [[T0:%.*]] = function_ref @_T010addressors1DV9subscripts5Int32VAFcfau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[ARRAY]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: store [[V]] to [[ADDR]] : $*Int32 array[0] = make_int() // CHECK: [[FN:%.*]] = function_ref @_T010addressors14take_int_inoutys5Int32VzF // CHECK: [[T0:%.*]] = function_ref @_T010addressors1DV9subscripts5Int32VAFcfau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[ARRAY]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: apply [[FN]]([[ADDR]]) take_int_inout(&array[1]) // CHECK: [[T0:%.*]] = load [[ARRAY]] // CHECK: [[T1:%.*]] = function_ref @_T010addressors1DV9subscripts5Int32VAFcfg // CHECK: [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]]) // CHECK: return [[T2]] return array[2] } struct E { var value: Int32 { unsafeAddress { return someValidPointer() } nonmutating unsafeMutableAddress { return someValidPointer() } } } // CHECK-LABEL: sil hidden @_T010addressors6test_eyAA1EVF // CHECK: bb0([[E:%.*]] : $E): // CHECK: [[T0:%.*]] = function_ref @_T010addressors1EV5values5Int32Vfau // CHECK: [[T1:%.*]] = apply [[T0]]([[E]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] // CHECK: store {{%.*}} to [[T3]] : $*Int32 func test_e(_ e: E) { e.value = 0 } class F { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) final var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK: sil hidden @_T010addressors1FC5values5Int32Vflo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) { // CHECK: sil hidden @_T010addressors1FC5values5Int32Vfao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) { func test_f0(_ f: F) -> Int32 { return f.value } // CHECK: sil hidden @_T010addressors7test_f0s5Int32VAA1FCF : $@convention(thin) (@owned F) -> Int32 { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1FC5values5Int32Vflo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: strong_release [[SELF]] : $F // CHECK: return [[VALUE]] : $Int32 func test_f1(_ f: F) { f.value = 14 } // CHECK: sil hidden @_T010addressors7test_f1yAA1FCF : $@convention(thin) (@owned F) -> () { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14 // CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1FC5values5Int32Vfao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: strong_release [[SELF]] : $F class G { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK: sil hidden @_T010addressors1GC5values5Int32Vfg : $@convention(method) (@guaranteed G) -> Int32 { // CHECK: bb0([[SELF:%0]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vflo : $@convention(method) (@guaranteed G) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: return [[VALUE]] : $Int32 // CHECK: sil hidden @_T010addressors1GC5values5Int32Vfs : $@convention(method) (Int32, @guaranteed G) -> () { // CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vfao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // materializeForSet for G.value // CHECK-LABEL: sil hidden @_T010addressors1GC5values5Int32Vfm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed G) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $G): // Call the addressor. // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vfao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // Get the address. // CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]] // CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]] // Initialize the callback storage with the owner. // CHECK: [[T0:%.*]] = alloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: store [[T2]] to [[T0]] : $*Builtin.NativeObject // CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]] // Set up the callback. // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T010addressors1GC5values5Int32VfmytfU_ : // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // Epilogue. // CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[RESULT]] // materializeForSet callback for G.value // CHECK-LABEL: sil hidden @_T010addressors1GC5values5Int32VfmytfU_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout G, @thick G.Type) -> () { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*G, [[SELFTYPE:%3]] : $@thick G.Type): // CHECK: [[T0:%.*]] = project_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: [[OWNER:%.*]] = load [[T0]] // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: dealloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer class H { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) final var value: Int32 { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } // CHECK-LABEL: sil hidden @_T010addressors1HC5values5Int32Vflp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) { // CHECK-LABEL: sil hidden @_T010addressors1HC5values5Int32VfaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) { func test_h0(_ f: H) -> Int32 { return f.value } // CHECK-LABEL: sil hidden @_T010addressors7test_h0s5Int32VAA1HCF : $@convention(thin) (@owned H) -> Int32 { // CHECK: bb0([[SELF:%0]] : $H): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1HC5values5Int32Vflp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: strong_release [[SELF]] : $H // CHECK: return [[VALUE]] : $Int32 func test_h1(_ f: H) { f.value = 14 } // CHECK: sil hidden @_T010addressors7test_h1yAA1HCF : $@convention(thin) (@owned H) -> () { // CHECK: bb0([[SELF:%0]] : $H): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14 // CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1HC5values5Int32VfaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: strong_release [[SELF]] : $H class I { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } // CHECK-LABEL: sil hidden @_T010addressors1IC5values5Int32Vfg : $@convention(method) (@guaranteed I) -> Int32 { // CHECK: bb0([[SELF:%0]] : $I): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32Vflp : $@convention(method) (@guaranteed I) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: return [[VALUE]] : $Int32 // CHECK-LABEL: sil hidden @_T010addressors1IC5values5Int32Vfs : $@convention(method) (Int32, @guaranteed I) -> () { // CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $I): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32VfaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-LABEL: sil hidden @_T010addressors1IC5values5Int32Vfm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed I) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $I): // Call the addressor. // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32VfaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // Pull out the address. // CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]] // CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]] // Initialize the callback storage with the owner. // CHECK: [[T0:%.*]] = alloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: store [[T2]] to [[T0]] : $*Optional<Builtin.NativeObject> // CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]] // Set up the callback. // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T010addressors1IC5values5Int32VfmytfU_ : // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // Epilogue. // CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[RESULT]] // materializeForSet callback for I.value // CHECK-LABEL: sil hidden @_T010addressors1IC5values5Int32VfmytfU_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout I, @thick I.Type) -> () { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*I, [[SELFTYPE:%3]] : $@thick I.Type): // CHECK: [[T0:%.*]] = project_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: [[OWNER:%.*]] = load [[T0]] // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: dealloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer struct RecInner { subscript(i: Int32) -> Int32 { mutating get { return i } } } struct RecMiddle { var inner: RecInner } class RecOuter { var data: UnsafeMutablePointer<RecMiddle> = UnsafeMutablePointer.allocate(capacity: 100) final var middle: RecMiddle { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } func test_rec(_ outer: RecOuter) -> Int32 { return outer.middle.inner[0] } // This uses the mutable addressor. // CHECK-LABEL: sil hidden @_T010addressors8test_recs5Int32VAA8RecOuterCF : $@convention(thin) (@owned RecOuter) -> Int32 { // CHECK: function_ref @_T010addressors8RecOuterC6middleAA0B6MiddleVfaP // CHECK: struct_element_addr {{.*}} : $*RecMiddle, #RecMiddle.inner // CHECK: function_ref @_T010addressors8RecInnerV9subscripts5Int32VAFcfg
apache-2.0
64dd75388e76a6ff9a203856b436584a
54.336595
211
0.632422
3.322797
false
true
false
false
bartekchlebek/SwiftHelpers
Example/Pods/Nimble/Sources/Nimble/Matchers/HaveCount.swift
1
2786
import Foundation // The `haveCount` matchers do not print the full string representation of the collection value, // instead they only print the type name and the expected count. This makes it easier to understand // the reason for failed expectations. See: https://github.com/Quick/Nimble/issues/308. // The representation of the collection content is provided in a new line as an `extendedMessage`. /// A Nimble matcher that succeeds when the actual Collection's count equals /// the expected value public func haveCount<T: Collection>(_ expectedValue: T.IndexDistance) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(actualValue.count)" failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))" return result } else { return false } } } /// A Nimble matcher that succeeds when the actual collection's count equals /// the expected value public func haveCount(_ expectedValue: Int) -> MatcherFunc<NMBCollection> { return MatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(actualValue.count)" failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))" return result } else { return false } } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func haveCountMatcher(_ expected: NSNumber) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection}), location: location) return try! haveCount(expected.intValue).matches(expr, failureMessage: failureMessage) } else if let actualValue = actualValue { failureMessage.postfixMessage = "get type of NSArray, NSSet, NSDictionary, or NSHashTable" failureMessage.actualValue = "\(classAsString(type(of: actualValue)))" } return false } } } #endif
mit
7f3ca2c32257a07e9ec51b7261a9f0c5
47.877193
126
0.683417
5.527778
false
false
false
false
grandiere/box
box/View/GridVirus/VGridVirusLanding.swift
1
4819
import UIKit class VGridVirusLanding:UIView { private weak var controller:CGridVirus! private weak var layoutOptionsLeft:NSLayoutConstraint! private let kImageTop:CGFloat = 160 private let kImageHeight:CGFloat = 80 private let kLabelHorizontalMargin:CGFloat = 10 private let kLabelHeight:CGFloat = 150 private let kOptionsWidth:CGFloat = 260 private let kOptionsHeight:CGFloat = 34 init(controller:CGridVirus) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller MSession.sharedInstance.settings?.energy?.tryUpdateEnergy() guard let energy:Int16 = MSession.sharedInstance.settings?.energy?.amount else { return } let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:17), NSForegroundColorAttributeName:UIColor.white] let attributesSubtitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:17), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.7)] let attributesEnergy:[String:AnyObject] = [ NSFontAttributeName:UIFont.numeric(size:20), NSForegroundColorAttributeName:UIColor.white] let rawStringEnergy:String = "\(self.controller.model.kEnergyRequired)" let rawCurrentEnergy:String = "\(energy)" let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("VGridVirus_labelTitle", comment:""), attributes:attributesTitle) let stringSubtitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("VGridVirus_labelSubtitle", comment:""), attributes:attributesSubtitle) let stringEnergy:NSAttributedString = NSAttributedString( string:rawStringEnergy, attributes:attributesEnergy) let stringCurrent:NSAttributedString = NSAttributedString( string:rawCurrentEnergy, attributes:attributesEnergy) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringEnergy) mutableString.append(stringSubtitle) mutableString.append(stringCurrent) let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.image = #imageLiteral(resourceName: "assetGenericVirusEgg") let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.numberOfLines = 0 label.textAlignment = NSTextAlignment.center label.attributedText = mutableString let options:VGridVirusOptions = VGridVirusOptions( controller:self.controller) addSubview(imageView) addSubview(label) addSubview(options) NSLayoutConstraint.topToTop( view:imageView, toView:self, constant:kImageTop) NSLayoutConstraint.height( view:imageView, constant:kImageHeight) NSLayoutConstraint.equalsHorizontal( view:imageView, toView:self) NSLayoutConstraint.topToBottom( view:label, toView:imageView) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelHorizontalMargin) NSLayoutConstraint.topToBottom( view:options, toView:label) NSLayoutConstraint.height( view:options, constant:kOptionsHeight) layoutOptionsLeft = NSLayoutConstraint.leftToLeft( view:options, toView:self) NSLayoutConstraint.width( view:options, constant:kOptionsWidth) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainWidth:CGFloat = width - kOptionsWidth let marginLeft:CGFloat = remainWidth / 2.0 layoutOptionsLeft.constant = marginLeft super.layoutSubviews() } }
mit
dcdc6f52aa633c224f762c167e172601
34.433824
81
0.643079
5.912883
false
false
false
false
rectinajh/leetCode_Swift
MinWindow/MinWindow.swift
1
4538
// // MinWindow.swift // MinWindow // // Created by hua on 16/9/21. // Copyright © 2016年 212. All rights reserved. // import Foundation /* https://leetcode.com/problems/minimum-window-substring/ #76 Minimum Window Substring Level: hard Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". 给定一个字符串S和一个字符串T。找出S中最小的窗口包含了S中所有的字符。 Note: If there is no such window in S that covers all characters in T, return the emtpy string "". If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 思路: 首先我们需要记录T中的字符,因为每个字符可能出现多次,所以我们需要记录该字符对应的个数。不妨使用256位的数组当做哈希表。统计T中每个字符出现的次数。然后,我们使用两个指针,初始化时第一个指针指向了S中的第一个元素,然后让第二个指针从第一个指针的位置开始往后扫描,直到找到能够了T中所有的字符,然后往后移动第一个指针来缩小这个窗口,截止条件是不能满足T中所有的字符出现的次数。此时继续往后移动第二个指针。一直到第二个指针移动到字符串末尾。 可以利用两个指针扫描(两个指针分别为start,i),以S = “e b a d b a c c b”(忽略空格),T = “abc”为例: 0 1 2 3 4 5 6 7 8 初始化 start = i = 0 i 逐渐往后扫描S直到窗口S[start…i]包含所有T的字符,此时i = 6(字符c的位置) 缩减窗口:此时我们注意到窗口并不是最小的,需要调整 start 来缩减窗口。缩减规则为:如果S[start]不在T中 或者 S[start]在T中但是删除后窗口依然可以包含T中的所有字符,那么start = start+1, 直到不满足上述两个缩减规则。缩减后i即为窗口的起始位置,此例中从e开始窗口中要依次删掉e、b、a、d,start最后等于4 ,那么得到一个窗口大小为6-4+1 = 3 start = start+1(此时窗口肯定不会包含所有的T中的字符),跳转到步骤2继续寻找下一个窗口。本例中还以找到一个窗口start = 5,i = 8,比上个窗口大,因此最终的最小窗口是S[4…6] */ private extension String { subscript (index: Int) -> Character { return self.characters[self.startIndex.advancedBy(index)] } } class Solution { static func minWindow(s: String, t: String) -> String { if s.isEmpty || t.isEmpty { return "" } var count = t.characters.count var charCountDict: Dictionary<Character, Int> = Dictionary() var charFlagDict: Dictionary<Character, Bool> = Dictionary() for ii in 0 ..< count { if let charCount = charCountDict[t[ii]] { charCountDict[t[ii]] = charCount + 1 } else { charCountDict[t[ii]] = 1 } charFlagDict[t[ii]] = true } var i = -1 var j = 0 var minLen = Int.max var minIdx = 0 while i < s.characters.count && j < s.characters.count { if count > 0 { i += 1 if i == s.characters.count { continue } if let charCount = charCountDict[s[i]] { charCountDict[s[i]] = charCount - 1 } else { charCountDict[s[i]] = -1 } if charFlagDict[s[i]] == true && charCountDict[s[i]] >= 0 { count -= 1 } } else { if minLen > i - j + 1 { minLen = i - j + 1 minIdx = j } if let charCount = charCountDict[s[j]] { charCountDict[s[j]] = charCount + 1 } else { charCountDict[s[j]] = 1 } if charFlagDict[s[j]] == true && charCountDict[s[j]] > 0 { count += 1 } j += 1 } } if minLen == Int.max { return "" } let range : NSRange = NSMakeRange(minIdx, minLen) let range1 : NSString = s return range1.substringWithRange(range) } }
mit
99721f32bc70c3cdee644da5dbceb1bb
30.168142
220
0.556376
3.242173
false
false
false
false
ivanbruel/SwipeIt
Pods/MarkdownKit/MarkdownKit/Classes/Elements/MarkdownItalic.swift
1
466
// // MarkdownItalic.swift // Pods // // Created by Ivan Bruel on 18/07/16. // // import UIKit public class MarkdownItalic: MarkdownCommonElement { private static let regex = "(\\s+|^)(\\*|_)(.+?)(\\2)" public var font: UIFont? public var color: UIColor? public var regex: String { return MarkdownItalic.regex } public init(font: UIFont? = nil, color: UIColor? = nil) { self.font = font?.italic() self.color = color } }
mit
9eff979c3b28927a620f7983abbf960b
16.259259
59
0.609442
3.40146
false
false
false
false
lllyyy/LY
ATBluetooth-master(swift4蓝牙连接)/ATBluetooth/DeviceVc.swift
1
3520
// // DeviceVc.swift // ATBluetooth // // Created by ZGY on 2017/11/16. //Copyright © 2017年 macpro. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2017/11/16 下午2:37 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit class DeviceVc: UIViewController { //MARK: - Attributes var device: ATBleDevice? override func viewDidLoad() { super.viewDidLoad() // Print(device?.state) } //MARK: - Override //MARK: - Initial Methods //MARK: - Delegate //MARK: - Target Methods @IBAction func sendAction(_ sender: UIButton) { switch sender.tag { case 666: // let data = Data.init(bytes: [0x12]) let data = Data.init(bytes: [0x82]) // device?.writeData(data) ATBlueToothContext.default.writeData(data, type: ATCharacteristicWriteType.withResponse, block: { (result) in Print(result) }) break case 777: ATBlueToothContext.default.disconnectDevice() break case 888: ATBlueToothContext.default.reconnectDevice(device?.uuid) break default: break } } //MARK: - Notification Methods //MARK: - KVO Methods //MARK: - UITableViewDelegate, UITableViewDataSource //MARK: - Privater Methods //MARK: - Setter Getter Methods //MARK: - Life cycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) atBlueTooth.connect(device) self.title = device?.state?.description device?.delegate = self // updatedATBleDeviceState((device?.state)!, error: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } deinit { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension DeviceVc:ATBleDeviceStateDelegate { func updatedIfWriteSuccess(_ result: Result<Any>?) { guard result != nil else { return } switch result! { case .Success(let value): // print(String.init(data: value!, encoding: String.Encoding.ascii)) // Print(String.init(data: value!, encoding: String.Encoding.utf8)) Print(value) case .Failure(let error): Print(error) } } func updatedATBleDeviceState(_ state: ATBleDeviceState, error: Error?) { DispatchQueue.main.async { self.title = "\(state.description)" Print(state.description) } } }
mit
79acb57b977aa15149a7263b64ebcf8e
23.061644
119
0.559066
4.604194
false
false
false
false
SAP/IssieBoard
EducKeyboard/DetailViewController.swift
1
12762
// // DetailViewController.swift // IssieKeyboard // // Created by Sasson, Kobi on 3/17/15. // Copyright (c) 2015 Sasson, Kobi. All rights reserved. // import UIKit import QuartzCore class DetailViewController: UIViewController, UIPopoverPresentationControllerDelegate, UITextViewDelegate { @IBOutlet weak var colorPalette: UIView! @IBOutlet var ToggleKeyboard: UITextField! @IBOutlet var PreviewKeyboard: UIButton! @IBOutlet var RowColPicker: UISegmentedControl! @IBOutlet var TemplatePicker: UIStepper! @IBOutlet var itemValue: UITextView! var TemplateType = ["My Configuration", "Template1 - Yellow", "Template2 - Orange", "Template3", "Template4"] var configItem: ConfigItem? { didSet { self.configureView() } } @IBAction func TemplatePickerTapped(sender: UIStepper) { TapRecognize(sender) itemValue.text = TemplateType[Int(sender.value)] configItem?.value = TemplateType[Int(sender.value)] } @IBAction func TapRecognize(sender: AnyObject) { ToggleKeyboard.resignFirstResponder() itemValue.resignFirstResponder() } @IBAction func ChangedMode(sender: UISegmentedControl) { configItem?.value = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex) TapRecognize(sender) } @IBAction func PreviewKeyboardClicked(sender: UIButton) { ToggleKeyboard.becomeFirstResponder() } func configureView() { if let toggle = self.ToggleKeyboard { toggle.hidden = true } if let item: ConfigItem = self.configItem { if let valueField = self.itemValue { if let palette = self.colorPalette { if let modePicker = self.RowColPicker { valueField.layer.borderWidth = 1.3 self.title = item.title switch item.type { case .String: valueField.userInteractionEnabled = true palette.hidden = true if(item.title != "Visible Keys"){ valueField.text = item.value as! String } else if(item.title == "Visible Keys"){ if((item.value as! String) != ""){ valueField.text = item.value as! String } } modePicker.hidden = true TemplatePicker.hidden = true case .Color: TemplatePicker.hidden = true palette.hidden = false valueField.userInteractionEnabled = false valueField.backgroundColor = item.value as? UIColor modePicker.hidden = true case .Picker: TemplatePicker.hidden = true valueField.userInteractionEnabled = true valueField.hidden = true palette.hidden = true modePicker.hidden = false case .FontPicker: valueField.userInteractionEnabled = true TemplatePicker.hidden = true valueField.hidden = true palette.hidden = true modePicker.hidden = true case .Templates: TemplatePicker.value = 0 valueField.userInteractionEnabled = false TemplatePicker.hidden = false valueField.hidden = false palette.hidden = true modePicker.hidden = true } } } } } else { TemplatePicker.hidden = true colorPalette.hidden = true itemValue.hidden = true RowColPicker.hidden = true } self.initColorRainbow() } func updateColor(color: UIColor) { if let valueField = self.itemValue { if let item: ConfigItem = self.configItem { valueField.backgroundColor = color item.value = color } } } func textViewDidEndEditing(textView: UITextView){ if let detail: ConfigItem = self.configItem { if let valueField = self.itemValue { if(valueField.text.isEmptyOrWhiteSpace && configItem?.title == "Visible Keys") { detail.value = "אבגדהוזחטיכלמנסעןפצקרשתםףךץ1234567890.,?!'•_\\|~<>$€£[]{}#%^*+=.,?!'\"-/:;()₪&@"; } else { detail.value = valueField.text } } } } override func viewDidLoad() { super.viewDidLoad() self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func displayColor(sender:UIButton){ var r:CGFloat = 0,g:CGFloat = 0,b:CGFloat = 0 var a:CGFloat = 0 var h:CGFloat = 0,s:CGFloat = 0,l:CGFloat = 0 let color = sender.backgroundColor! if color.getHue(&h, saturation: &s, brightness: &l, alpha: &a){ if color.getRed(&r, green: &g, blue: &b, alpha: &a){ let colorText = NSString(format: "HSB: %4.2f,%4.2f,%4.2f RGB: %4.2f,%4.2f,%4.2f", Float(h),Float(s),Float(b),Float(r),Float(g),Float(b)) self.updateColor(color) } } } func initColorRainbow(){ var buttonFrame = CGRect(x: 0, y: 10, width: 60, height: 60) var i:CGFloat = 1.0 let ClassicColorsLabel :UILabel = UILabel(frame: buttonFrame) ClassicColorsLabel.text = "Classic Colors" ClassicColorsLabel.font = UIFont.boldSystemFontOfSize(CGFloat(20)) ClassicColorsLabel.textColor = UIColor.blackColor() ClassicColorsLabel.sizeToFit() if let view = self.colorPalette{ view.addSubview(ClassicColorsLabel) } buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height*0.5 makeClassicColorsButtons(buttonFrame) buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height makeUIColorsButtons(buttonFrame) buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height + 10 let RainbowColorsLabel :UILabel = UILabel(frame: buttonFrame) RainbowColorsLabel.text = "Rainbow Colors" RainbowColorsLabel.font = UIFont.boldSystemFontOfSize(CGFloat(20)) RainbowColorsLabel.textColor = UIColor.blackColor() RainbowColorsLabel.sizeToFit() if let view = self.colorPalette{ view.addSubview(RainbowColorsLabel) } buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height*0.5 while i > 0.5{ makeRainbowButtons(buttonFrame, sat: i ,bright: 1.0) i = i - 0.2 buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height } buttonFrame.origin.y = buttonFrame.origin.y + 10 let BWColorsLabel :UILabel = UILabel(frame: buttonFrame) BWColorsLabel.text = "B&W Colors" BWColorsLabel.font = UIFont.boldSystemFontOfSize(CGFloat(20)) BWColorsLabel.textColor = UIColor.blackColor() BWColorsLabel.sizeToFit() if let view = self.colorPalette{ view.addSubview(BWColorsLabel) } buttonFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height*0.5 makeBWColorsButtons(buttonFrame) } func makeUIColorsButtons(buttonFrame:CGRect){ var myButtonFrame = buttonFrame var colorsArray: [UIColor] = [UIColor.blackColor(), UIColor.darkGrayColor(),UIColor.grayColor(),UIColor.lightGrayColor(), UIColor.whiteColor(), UIColor.brownColor(), UIColor.orangeColor(), UIColor.yellowColor(),UIColor.blueColor(), UIColor.purpleColor(), UIColor.greenColor()] for i in 0..<11{ let color = colorsArray[i] let aButton = UIButton(frame: myButtonFrame) myButtonFrame.origin.x = myButtonFrame.size.width + myButtonFrame.origin.x aButton.backgroundColor = color aButton.layer.borderColor = UIColor.whiteColor().CGColor aButton.layer.borderWidth = 1 if let view = self.colorPalette{ view.addSubview(aButton) } aButton.addTarget(self, action: "displayColor:", forControlEvents: UIControlEvents.TouchUpInside) } } func makeClassicColorsButtons(buttonFrame:CGRect){ var myButtonFrame = buttonFrame var stringColorArray :[String] = ["C70A0A","FF00BB","C800FF","4400FF","0080FF","00DDFF","11D950","EDED21","FF9500","FF6200","C27946"] for i in 0..<11{ let color = hexStringToUIColor(stringColorArray[i]) let aButton = UIButton(frame: myButtonFrame) myButtonFrame.origin.x = myButtonFrame.size.width + myButtonFrame.origin.x aButton.backgroundColor = color aButton.layer.borderColor = UIColor.whiteColor().CGColor aButton.layer.borderWidth = 1 if let view = self.colorPalette{ view.addSubview(aButton) } aButton.addTarget(self, action: "displayColor:", forControlEvents: UIControlEvents.TouchUpInside) } } func makeBWColorsButtons(buttonFrame:CGRect){ var myButtonFrame = buttonFrame var i :CGFloat = 0 while i < 22{ let hue:CGFloat = CGFloat(i) / 22.0 let color = UIColor(hue: hue, saturation: 0, brightness: hue, alpha: 1.0) let aButton = UIButton(frame: myButtonFrame) myButtonFrame.origin.x = myButtonFrame.size.width + myButtonFrame.origin.x aButton.backgroundColor = color aButton.layer.borderColor = UIColor.whiteColor().CGColor aButton.layer.borderWidth = 1 if let view = self.colorPalette{ view.addSubview(aButton) } aButton.addTarget(self, action: "displayColor:", forControlEvents: UIControlEvents.TouchUpInside) i = i + 2 } } func makeRainbowButtons(buttonFrame:CGRect, sat:CGFloat, bright:CGFloat){ var myButtonFrame = buttonFrame for i in 0..<11{ let hue:CGFloat = CGFloat(i) / 11.0 let color = UIColor(hue: hue, saturation: sat, brightness: bright, alpha: 1.0) let aButton = UIButton(frame: myButtonFrame) myButtonFrame.origin.x = myButtonFrame.size.width + myButtonFrame.origin.x aButton.backgroundColor = color aButton.layer.borderColor = UIColor.whiteColor().CGColor aButton.layer.borderWidth = 1 if let view = self.colorPalette{ view.addSubview(aButton) } aButton.addTarget(self, action: "displayColor:", forControlEvents: UIControlEvents.TouchUpInside) } } func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(cString.startIndex.advancedBy(1)) } if (cString.characters.count != 6) { return UIColor.grayColor() } var rgbValue:UInt32 = 0 NSScanner(string: cString).scanHexInt(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
apache-2.0
27952a0c38a91633324833c19d016c62
37.453172
284
0.550597
5.117813
false
false
false
false
zalando/MapleBacon
MapleBaconTests/DownloaderTests.swift
2
2825
// // Copyright © 2020 Schnaub. All rights reserved. // @testable import MapleBacon import XCTest final class DownloaderTests: XCTestCase { private static let url = URL(string: "https://example.com/mapleBacon.png")! func testDownload() { let expectation = self.expectation(description: #function) let downloader = Downloader<Data>(sessionConfiguration: .dummyDataProviding) _ = downloader.fetch(Self.url) { response in switch response { case .success(let data): XCTAssertNotNil(data) case .failure: XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testInvalidData() { let expectation = self.expectation(description: #function) let downloader = Downloader<UIImage>(sessionConfiguration: .dummyDataProviding) _ = downloader.fetch(Self.url) { response in switch response { case .success: XCTFail() case .failure(let error): XCTAssertNotNil(error) } expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testFailure() { let expectation = self.expectation(description: #function) let downloader = Downloader<Data>(sessionConfiguration: .failed) _ = downloader.fetch(Self.url) { response in switch response { case .success: XCTFail() case .failure(let error): XCTAssertNotNil(error) } expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testConcurrentDownloads() { let downloader = Downloader<Data>(sessionConfiguration: .dummyDataProviding) let firstExpectation = expectation(description: "first") _ = downloader.fetch(Self.url) { response in switch response { case .success(let data): XCTAssertNotNil(data) case .failure: XCTFail() } firstExpectation.fulfill() } let secondExpectation = expectation(description: "second") _ = downloader.fetch(Self.url) { response in switch response { case .success(let data): XCTAssertNotNil(data) case .failure: XCTFail() } secondExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testCancel() { let expectation = self.expectation(description: #function) let downloader = Downloader<Data>(sessionConfiguration: .failed) let downloadTask = downloader.fetch(Self.url) { response in switch response { case .failure(let error as DownloaderError): XCTAssertEqual(error, .canceled) case .success, .failure: XCTFail() } expectation.fulfill() } XCTAssertNotNil(downloadTask) downloadTask.cancel() waitForExpectations(timeout: 5, handler: nil) } }
mit
5aa00beb5c67a13aa998fe228cd714fd
24.441441
83
0.655807
4.621931
false
true
false
false
mlilback/MJLCommon
Sources/MJLCommon/ToolbarItemHandler.swift
1
3622
// // ToolbarItemHandler.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // // This file should only be included in macOS targets #if os(macOS) import Cocoa //import ClientCore #endif @available(macOS 10.12, *) protocol ToolbarItemHandler : class { ///called by a top level controller for each toolbar item no one has claimed func handlesToolbarItem(_ item: NSToolbarItem) -> Bool ///should be called in viewDidAppear for lazy loaded views to hookup to toolbar items func hookupToToolbarItems(_ handler: ToolbarItemHandler, window: NSWindow) } @available(macOS 10.12, *) protocol ToolbarDelegatingOwner : class { //should be called when views have loaded func assignHandlers(_ rootController: NSViewController, items: [NSToolbarItem]) ///called by hookupToolbarItems so a lazy-loaded controller can hook up items it supports func assignUnclaimedToolbarItems(_ toolbar: NSToolbar, handler: ToolbarItemHandler) } @available(macOS 10.12, *) extension ToolbarItemHandler { func hookupToToolbarItems(_ handler: ToolbarItemHandler, window: NSWindow) { //find owner if let owner: ToolbarDelegatingOwner = _firstChildViewController(window.contentViewController!) { owner.assignUnclaimedToolbarItems(window.toolbar!, handler: handler) } } } @available(macOS 10.12, *) extension ToolbarDelegatingOwner { func assignUnclaimedToolbarItems(_ toolbar: NSToolbar, handler: ToolbarItemHandler) { for item in toolbar.items where item.action == nil { _ = handler.handlesToolbarItem(item) } } func assignHandlers(_ rootController: NSViewController, items: [NSToolbarItem]) { //find every ToolbarItemHandler in rootController let handlers = recursiveFlatMap(rootController, children: { $0.children }, transform: { $0 as? ToolbarItemHandler }) //loop through toolbar items looking for the first handler that handles the item for anItem in items { for aHandler in handlers { if aHandler.handlesToolbarItem(anItem) { break; } } } } } //this subclass allows a closure to be injected for validation @available(macOS 10.12, *) class ValidatingToolbarItem: NSToolbarItem { typealias ToolbarValidationHandler = (ValidatingToolbarItem) -> Void var validationHandler: ToolbarValidationHandler? override func validate() { self.validationHandler?(self) } } @available(macOS 10.12, *) fileprivate func _firstChildViewController<T>(_ rootController: NSViewController) -> T? { return firstRecursiveDescendent(rootController, children: { return $0.children }, filter: { return $0 is T }) as? T } /// Use the following code in a NSWindowController subclass that is the toolbar's delegate /// Need to schedule setting up toolbar handlers, but don't want to do it more than once // fileprivate var toolbarSetupScheduled = false //When the first toolbar item is loaded, queue a closure to call assignHandlers from the ToolbarDelegatingOwner protocol(default implementation) that assigns each toolbar item to the appropriate ToolbarItemHandler (normally a view controller) // func toolbarWillAddItem(_ notification: Notification) { // //schedule assigning handlers after toolbar items are loaded // if !toolbarSetupScheduled { // DispatchQueue.main.async { // self.assignHandlers(self.contentViewController!, items: (self.window?.toolbar?.items)!) // } // toolbarSetupScheduled = true // } // let item: NSToolbarItem = ((notification as NSNotification).userInfo!["item"] as? NSToolbarItem)! // if item.itemIdentifier == "status", // let sview = item.view as? AppStatusView // { // statusView = sview // } // }
isc
1470c64c697abf37afaf164b3d6c05f6
35.575758
243
0.754764
4.100793
false
false
false
false
darofar/lswc
p3-angrybirdsgestures/p3-angrybirdsgestures/TrajectoryView.swift
1
3338
// // TrajectoryView.swift // p3-angrybirdsgestures // // Created by Danny Fonseca on 1/5/15. // Copyright (c) 2015 LSWC 2015. All rights reserved. // import UIKit class TrajectoryView: UIView { //declarations var dataSource: TrajectoryViewDataSource! var distanceToTarget: Double = 300.0{ didSet { setNeedsDisplay() } } let IMGSIZE = 50.0 @IBInspectable var birdImage : UIImage! @IBInspectable var pigImage : UIImage! @IBInspectable var backgroundImage : UIImage! var lineWidth: Double = 3 var lineColor: UIColor = UIColor.blueColor() /** * Draw bird with fixed size given by IMGSIZE */ private func drawBird(){ let y = CGFloat(viewHeight(IMGSIZE)) let rect = CGRectMake(5, y,CGFloat(IMGSIZE), CGFloat(IMGSIZE)) birdImage.drawInRect(rect) } /** * Draw pig with fixed size given by IMGSIZE. */ private func drawPig(){ let x = CGFloat(distanceToTarget) let y = CGFloat(viewHeight(IMGSIZE)) let rect = CGRectMake(x, y,CGFloat(IMGSIZE), CGFloat(IMGSIZE)) pigImage.drawInRect(rect) } /** * Draw background image */ private func drawBackground(){ let x = CGFloat(0) let y = CGFloat(0) let rect = CGRectMake(x, y, self.bounds.size.width, self.bounds.size.height) backgroundImage.drawInRect(rect) } /** * Check if the trayectory hit the target. * - If is a hit change color to red * - If is a miss change the color to blue. */ private func checkHit(){ let endTime = dataSource.endTime() var finalPos = dataSource.positionAt(endTime) if((finalPos.x >= distanceToTarget ) && ( finalPos.x <= (distanceToTarget + IMGSIZE)) ) { lineColor = UIColor.greenColor() } else { lineColor = UIColor.blueColor() } } /** * Redraw the frame in custom way. */ override func drawRect(rect: CGRect) { if(dataSource == nil) { return; } //self.sendSubviewToBack(backgroundImage) drawBackground() drawBird() drawPig() //posisionning the path let path = UIBezierPath() let startTime = dataSource.startTime() let endTime = dataSource.endTime() var point = dataSource.positionAt(startTime) path.moveToPoint(CGPointMake(CGFloat(point.x), CGFloat(viewHeight(point.y)))) //advance time an draw point by point for var t=startTime ; t < endTime ; t += 0.1 { point = dataSource.positionAt(t) path.addLineToPoint(CGPointMake(CGFloat(point.x),CGFloat(viewHeight(point.y)))) } //give line color and stroke path.lineWidth = CGFloat(lineWidth) lineColor.setStroke() path.stroke() //now check hit so maybe we should change color. checkHit() } //Convert the y-axis private func viewHeight(y: Double) -> Double{ return Double(self.bounds.size.height) - y } func newDistanceToTarget(distancePercentage: Double) { distanceToTarget = (distancePercentage) * ( Double(self.bounds.size.width) - 2*IMGSIZE - 15) + IMGSIZE + 10 } }
apache-2.0
70b4239a9c4bbdd99190293474a36c84
28.026087
116
0.595566
4.257653
false
false
false
false
adevelopers/PeriodicTableView
PeriodicTable/PeriodicTable/AppDelegate.swift
1
771
// // AppDelegate.swift // PeriodicTable // // Created by Kirill Khudyakov on 19.09.17. // Copyright © 2017 adeveloper. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().backIndicatorImage = #imageLiteral(resourceName: "button-back") UINavigationBar.appearance().backgroundColor = UIColor.black UINavigationBar.appearance().backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "button-back") return true } }
mit
97bdd681d4aad60991d82722af714495
28.615385
123
0.711688
4.967742
false
false
false
false
tuannme/Up
Up+/Up+/View/SpinnerSwift.swift
1
1310
// // SpinnerSwift.swift // Up+ // // Created by Nguyen Manh Tuan on 2/26/17. // Copyright © 2017 Dreamup. All rights reserved. // import UIKit import NVActivityIndicatorView class SpinnerSwift{ let spinner = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 60, height: 60), type: .ballSpinFadeLoader, color: .white, padding: 0) private let blueView = UIView(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) var isPlaying = false static let sharedInstance:SpinnerSwift = { let instance = SpinnerSwift() instance.spinner.center = (UIApplication.shared.keyWindow?.center)! let background = UIView(frame:instance.blueView.frame) background.backgroundColor = UIColor.black.withAlphaComponent(0.8) instance.blueView.addSubview(background) instance.blueView.addSubview(instance.spinner) return instance }() private func setSpinner() { } func startAnimating(){ stopAnimating() spinner.startAnimating() UIApplication.shared.keyWindow?.addSubview(blueView) } func stopAnimating(){ blueView.removeFromSuperview() spinner.stopAnimating() } }
mit
eb9f3e1e80d157469edb43e501746390
25.18
145
0.648587
4.592982
false
false
false
false
duongsonthong/waveFormLibrary
waveFormLibrary/ControllerWF.swift
2
1388
// // parentTest.swift // // Created by SSd on 11/3/16. // import UIKit class ControllerWF: UIView { var i : Int = 0 var mWaveForm : WaveForm? var playButton : UIButton? override init(frame: CGRect) { super.init(frame: frame) mWaveForm = WaveForm(frame: frame, deletgate: self) let playButtonRect = CGRect(x: frame.size.width/2-50, y: frame.size.height-100, width: 100, height: 100) playButton = UIButton(frame: playButtonRect) playButton?.backgroundColor = UIColor.gray playButton?.setTitle("play", for: .normal) playButton?.addTarget(self, action: #selector(self.clickPlay), for: .touchUpInside) addSubview(mWaveForm!) addSubview(playButton!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func clickPlay(){ mWaveForm!.setNewPosition(_position: 100) mWaveForm!.setNeedsDisplay()// if I click button, waveForm draw new line at new position 100 } } extension ControllerWF : WaveFormProtocol { func waveformDraw(){ if i < 2 { print("callback waveformDraw") i+=1 mWaveForm!.setNewPosition(_position: i) mWaveForm!.setNeedsDisplay() // the problem here.. waveForm not call draw(:) to redraw line with new position } } }
mit
412617d52d482ff2b338b8631f9c1559
29.844444
121
0.631844
4.106509
false
false
false
false
SereivoanYong/Charts
Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift
1
2531
// // TriangleShapeRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class TriangleShapeRenderer : NSObject, IShapeRenderer { open func renderShape( context: CGContext, dataSet: IScatterChartDataSet, viewPortHandler: ViewPortHandler, point: CGPoint, color: UIColor) { let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 context.setFillColor(color.cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf)) context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf)) if shapeHoleSize > 0.0 { context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) } context.closePath() context.fillPath() if shapeHoleSize > 0.0 && shapeHoleColor != nil { context.setFillColor(shapeHoleColor!.cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.closePath() context.fillPath() } } }
apache-2.0
0abacff99b220db6f339f8e12c9c45dc
37.938462
124
0.619123
4.635531
false
false
false
false
venmo/Static
Example/CustomTableViewCell.swift
2
1468
import UIKit import Static final class CustomTableViewCell: UITableViewCell, Cell { // MARK: - Properties private lazy var centeredLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.textColor = .white label.translatesAutoresizingMaskIntoConstraints = false return label }() // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = .gray contentView.addSubview(centeredLabel) NSLayoutConstraint.activate([ centeredLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), centeredLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 8), centeredLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), centeredLabel.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: 8), centeredLabel.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -8) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - CellType func configure(row: Row) { centeredLabel.text = row.text accessibilityIdentifier = row.accessibilityIdentifier } }
mit
855cfa5540964ac8ecb11ef11af1f98d
31.622222
113
0.694823
5.518797
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Playgrounds/Functions 2.playground/Pages/Section 2 - Function Composition.xcplaygroundpage/Contents.swift
2
12036
//: [Previous](@previous) import UIKit import PlaygroundSupport //: ![Functions Part 2](banner.png) //: # Functions Part 2 - Section 2 - Functional Programming Examples //: Version 3 - updated for Swift 3 //: //: For Xcode 8 //: //: Updated 24th November 2016 //: //: This playground is designed to support the materials of the lecure "Functions 2". //: In this playground, I am going to build up a simple example of functional programming. We will meet first class functions, function types, Currying and function composition. //: ## Define types //: To make the code much easier to follow, it is common to define type alias. `Point2D` is a Tulpe where as `Transform2D` is a function. Remember, don't think of functions as a simply function pointer (esp. you C programmers out there!). Think of it more as an object, where the data are 'captured' and copied or referenced within, and where the functions can operate on that data. You might say it's rather like an instance of a class. typealias Point2D = (x: Double, y: Double) //2D point in a Tuple typealias Transform2D = (Point2D) -> Point2D //Function type //: ## Create transforms //: These are functions that return other (nested) functions. A few key points here: //: * The type of all __returned__ functions are purposely identical `Point2D->Point2D`, that is, accepts a single Point2D input, and returns a single Point2D output. I call this type `Transform2D` as they all transform a Point2D from one location to another. //: * These functions accept different types. These are the parameters intended to be 'captured' by the nested functions which are subsequently returned. //: ### Translate point (addition) //: //: The nested functions captures `offset`, an additional Point2D (2D vector) used in subsequent calculations. //: As the `offset` parameter is not mutated outside the nested function, then a copy is said to be captured. //: Note that *it is the nested **function** that is returned*. This function takes a 2D Point as a parameter and returns a new point. It uses the *captured* `offset` to perform the calculation. func translate(_ offset: Point2D) -> Transform2D { func tx(_ point: Point2D) -> Point2D { //Capture offset let off = offset //Calculate and return new point return (x: point.x + off.x, y: point.y + off.y) } return tx } //: ![Translate function](translate.png) //: ### Scale //: //: Scale both elements by a common scalar (stretch radially) //: //: Again, the nested function captures a copy of the scaling factor provided by the enslosing scope. func scaleTransform(_ scale: Double) -> Transform2D { func tx(_ point: Point2D) -> Point2D { let s = scale return (x: point.x * s, y: point.y * s) } return tx } //: ![Scale function](scale.png) //: ### Rotate about the origin. //: //: Note a slight difference here. //: * The generating outer function is passed the angle of rotation as a parameter //: * I've chosen to precalculate cos and sin functions needed for rotations. I've done this as I plan to apply this function multiple times and don't want to keep recalculating them. //: * Is `cos_ø` and `sin_ø` that are captured by the nested function and returned. func rotate(_ angleInDegrees: Double) -> Transform2D { let π = M_PI let radians = π * angleInDegrees / 180.0 let cos_ø = cos(radians) let sin_ø = sin(radians) // The transform is a rotation func rotate (_ point : Point2D) -> Point2D { //cos_ø and sin_ø are 'captured' inside this closure let newX = cos_ø * point.x + sin_ø * point.y let newY = -sin_ø * point.x + cos_ø * point.y return (x: newX, y: newY) } return rotate } //: If I had only planned to perform a single rotation, I might have done this differently and calculated `cos_ø` and `sin_ø` within the nested function. This was the expensive `cos` and `sin` functions would only be performed if/when actually needed (lazily). //: ![Rotate about the origin function](rotate.png) //: //: ### Negate //: //: Used later in the advanced task. //: func negate(_ p: Point2D) -> Point2D { let minus_p = (x: -p.x, y: -p.y) return minus_p } //: ## Function composition //: //: ![Compose function](compose.png) //: //: The objective here is to make function composition behave rather like a UNIX pipe. Functions are performed left to right, with the output of each providing the input to the next //: //: Where two functions are to be applied, one to the output of the other, then we can create a higher-order function to perform this for us. //: func composeTransform(_ f1: @escaping Transform2D, _ f2: @escaping Transform2D) -> Transform2D { func tx(_ point: Point2D) -> Point2D { return f2(f1(point)) } return tx } //: ### To make it resemble a UNIX pipe, I've created a custom operator |-> . Note the associativity is critcal //: infix operator |-> : AdditionPrecedence func |-> (f1: @escaping Transform2D, f2: @escaping Transform2D) -> Transform2D { func tx(_ point: Point2D) -> Point2D { return f2(f1(point)) } return tx } //: ## Testing //: ### Test 1 - first apply individual transforms //: Constants let offset = (x: 50.0, y: 50.0) let scale = 2.0 let rotation = -90.0 //: Generate the functions, capturing the parameters provided let translate1 = translate(offset) let scale1 = scaleTransform(scale) let rotate1 = rotate(rotation) //: Test point let p1 : Point2D = (x: 20.0, y: 20.0) //: Calculate the position after each transform let p2 = translate1(p1) let p3 = scale1(p2) let p4 = rotate1(p3) //: Dictionary of points (Label : Coordinate) used for plotting let points1 = ["A" : p1, "B" : p2, "C" : p3, "D" : p4] //: Plot each point on a 2D graph //Wrapper function around PlotView initialiser let f = CGRect(x: 0.0, y: 0.0, width: 400.0, height: 400.0) //Common to all func PlotViewWithPoints(_ p : [String : Point2D]) -> UIView { return PlotView(frame: f, points: p) //Capture f } let plot1 = PlotViewWithPoints(points1) //: ### Test 2 - Composite Function //: Generate a composite function using the custom operator let cf = translate(offset) |-> scaleTransform(scale) |-> rotate(rotation) //let cf = composeTransform(composeTransform(translate1,scale1),rotate1) //: Apply the composite function to the original point p1 let p5 = cf(p1) //: Plot, showing the points A and D are eqivalent to the previous plot let points2 = ["A" : p1, "D" : p5] let plot2 = PlotViewWithPoints(points2) //: ### Test 3 - Use the composite function to rotate one point around another //: Create some points let sun : Point2D = Point2D(x : 100.0, y: 100.0) let planet : Point2D = Point2D(x : 40.0, y: 70.0) //: Generate a composite function for a 90 degree rotation about the sun let minusSun = negate(sun) let orbit45 = translate(minusSun) |-> rotate(90.0) |-> translate(sun) //: Apply the function to another point let planet45 = orbit45(planet) //: Plot let points3 = ["Sun" : sun, "Planet" : planet, "Planet+90" : planet45] let plot3 = PlotViewWithPoints(points3) //: ## Advanced task - write an *Orbit function* //: This is not covered in the lecture. I have left this to you experiment with //: //: Rotate about another point a given number of degrees //: Both the centre and angle of rotation need to be provided and captured //: This version uses Currying so that only one parameter is ever passed func orbit(center : Point2D) -> ((Double) -> Transform2D) { let minusCenter = negate(center) func R(_ angle : Double) -> Transform2D { let tx = translate(minusCenter) |-> rotate(angle) |-> translate(center) return tx } return R } //: So does this version, but it uses the alternative syntax and is easier to read func orbit_nicecurry(_ center : Point2D, _ angle: Double) -> Transform2D { let minusCenter = negate(center) let tx = translate(minusCenter) |-> rotate(angle) |-> translate(center) return tx } //: This version is not curried - which is ok as well if you don't want partial evaluation func orbit_notcurried(_ center : Point2D, angle: Double) -> Transform2D { let minusCenter = negate(center) let tx = translate(minusCenter) |-> rotate(angle) |-> translate(center) return tx } //: ### Test 4 - Orbit function (uses the curried version) let newPosition = orbit(center: sun)(90.0)(planet) //Curried version let points4 = ["Sun" : sun, "Planet" : planet, "Planet+90" : newPosition] let plot4 = PlotViewWithPoints(points3) //: ### Test 5 - Orbit function with partial evaluation //: What is interesting with the Curried version is that you can prepare partially incomplete orbits. This allows partially evaulated orbits to be passed to other code. //: For example: let solarOrbit = orbit(center : sun) //: We can now apply different angles around the sun var trans = [Transform2D]() //Array of functions (all with captured data of course!) //for (var ß = 0.0; ß<360.0; ß+=60.0) { for ß in stride(from: 0.0, to: 360.0, by: 60.0) { let tx = solarOrbit(ß) trans.append(tx) } //: Now we can apply this to different planets let earth = Point2D(x: 50.0, y: 50.0) let mercury = Point2D(x: 70.0, y: 75.0) var planetOrbits = [String : Point2D]() for (idx,f) in trans.enumerated() { planetOrbits["e\(idx)"] = f(x: earth.x, y: earth.y) planetOrbits["m\(idx)"] = f(x: mercury.x, y: mercury.y) } let plot5 = PlotViewWithPoints(planetOrbits) //: I hope you enjoyed this. I certainly had fun creating it. //: This only begins to cover Functional Programming (FP) as I understand it (I'm very much still learning). Until Swift, I'd never considered using FP. From what I've seen, I can already see some benefits, but I've also got mixed feelings. //: //: * There is something intellectually enjoyable about FP. It's hard to write, but very rewarding when you get it to work. Is fun enough justification? Well, nothing wrong with having fun of course. //: * There are those who claim FP is 'superior', and others who are more sceptical. //: * Some say it makes you a better programmer even if you don't use it all the time. //: //: I encourage students to be guarded, critical and open-minded when it comes to big claims you might read or hear. //: //: * There is nothing to say you must learn to use FP. I've seen nothing in the Apple frameworks or documentation that seem to demand it beyond passing functions as parameters (nice way to create call backs essentially). //: * Don't feel alone if you find it totally confusing or off-putting. //: * I've seen plenty of FP code that is incomprehensible (to me at least) - mostly in other languages. //: * It is helpful to recognise it and learning to understand it in case you have to work with FP code written by other people. //: * Writing in this style might be 'fun' and give us an intellectual reward, but speaking personally, I hope I am also self-aware enough to not do this *just* to get the thrill from cracking the puzzle! //: * Swift supports both imperitive and FP styles, and they can be mixed in the same project of course //: * If FP means you create more expressive code, maybe this is a good reason to use it //: * If FP means you write more testable code, again, maybe this is a good reason to use it //: * If FP means you write safer code (e.g. concurrent code), this is probably a good reason to use it //: * FP may or may not be more efficient (I've no idea which + it might change as the language evolves) - if you're writing CPU intensive code, benchmark carefully! //: * If you have to bend FP to solve a problem that is more simply/naturally solved with imperitive styles (e.g. GUI code), then I envy your spare time ;o) //: //: Swift may have a reasonably low entry point for learning to code, but a high ceiling if you want to master it in its entirity. Considerable effort seems to have gone into keeping Swift syntax clean and easy to read, even when writing FP. //: What ever style you use, happy coding and don't forget to get enough sleep! //: [Next](@next)
mit
4aa52e1bd67d4e25e31a6726a379dcbd
41.765125
437
0.703337
3.640412
false
false
false
false
biohazardlover/NintendoEverything
Pods/SwiftSoup/Sources/Tag.swift
1
11589
// // Tag.swift // SwiftSoup // // Created by Nabil Chatbi on 15/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation open class Tag: Hashable { // map of known tags static var tags: Dictionary<String, Tag> = { do { return try Tag.initializeMaps() } catch { preconditionFailure("This method must be overridden") } return Dictionary<String, Tag>() }() fileprivate var _tagName: String fileprivate var _tagNameNormal: String fileprivate var _isBlock: Bool = true // block or inline fileprivate var _formatAsBlock: Bool = true // should be formatted as a block fileprivate var _canContainBlock: Bool = true // Can this tag hold block level tags? fileprivate var _canContainInline: Bool = true // only pcdata if not fileprivate var _empty: Bool = false // can hold nothing e.g. img fileprivate var _selfClosing: Bool = false // can self close (<foo />). used for unknown tags that self close, without forcing them as empty. fileprivate var _preserveWhitespace: Bool = false // for pre, textarea, script etc fileprivate var _formList: Bool = false // a control that appears in forms: input, textarea, output etc fileprivate var _formSubmit: Bool = false // a control that can be submitted in a form: input etc public init(_ tagName: String) { self._tagName = tagName self._tagNameNormal = tagName.lowercased() } /** * Get this tag's name. * * @return the tag's name */ open func getName() -> String { return self._tagName } open func getNameNormal() -> String { return self._tagNameNormal } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". Case insensitive. * @param settings used to control tag name sensitivity * @return The tag, either defined or new generic. */ open static func valueOf(_ tagName: String, _ settings: ParseSettings)throws->Tag { var tagName = tagName var tag: Tag? = Tag.tags[tagName] if (tag == nil) { tagName = settings.normalizeTag(tagName) try Validate.notEmpty(string: tagName) tag = Tag.tags[tagName] if (tag == nil) { // not defined: create default; go anywhere, do anything! (incl be inside a <p>) tag = Tag(tagName) tag!._isBlock = false tag!._canContainBlock = true } } return tag! } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>. * @return The tag, either defined or new generic. */ open static func valueOf(_ tagName: String)throws->Tag { return try valueOf(tagName, ParseSettings.preserveCase) } /** * Gets if this is a block tag. * * @return if block tag */ open func isBlock() -> Bool { return _isBlock } /** * Gets if this tag should be formatted as a block (or as inline) * * @return if should be formatted as block or inline */ open func formatAsBlock() -> Bool { return _formatAsBlock } /** * Gets if this tag can contain block tags. * * @return if tag can contain block tags */ open func canContainBlock() -> Bool { return _canContainBlock } /** * Gets if this tag is an inline tag. * * @return if this tag is an inline tag. */ open func isInline() -> Bool { return !_isBlock } /** * Gets if this tag is a data only tag. * * @return if this tag is a data only tag */ open func isData() -> Bool { return !_canContainInline && !isEmpty() } /** * Get if this is an empty tag * * @return if this is an empty tag */ open func isEmpty() -> Bool { return _empty } /** * Get if this tag is self closing. * * @return if this tag should be output as self closing. */ open func isSelfClosing() -> Bool { return _empty || _selfClosing } /** * Get if this is a pre-defined tag, or was auto created on parsing. * * @return if a known tag */ open func isKnownTag() -> Bool { return Tag.tags[_tagName] != nil } /** * Check if this tagname is a known tag. * * @param tagName name of tag * @return if known HTML tag */ open static func isKnownTag(_ tagName: String) -> Bool { return Tag.tags[tagName] != nil } /** * Get if this tag should preserve whitespace within child text nodes. * * @return if preserve whitepace */ public func preserveWhitespace() -> Bool { return _preserveWhitespace } /** * Get if this tag represents a control associated with a form. E.g. input, textarea, output * @return if associated with a form */ public func isFormListed() -> Bool { return _formList } /** * Get if this tag represents an element that should be submitted with a form. E.g. input, option * @return if submittable with a form */ public func isFormSubmittable() -> Bool { return _formSubmit } @discardableResult func setSelfClosing() -> Tag { _selfClosing = true return self } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static public func ==(lhs: Tag, rhs: Tag) -> Bool { let this = lhs let o = rhs if (this === o) {return true} if (type(of:this) != type(of:o)) {return false} let tag: Tag = o if (lhs._tagName != tag._tagName) {return false} if (lhs._canContainBlock != tag._canContainBlock) {return false} if (lhs._canContainInline != tag._canContainInline) {return false} if (lhs._empty != tag._empty) {return false} if (lhs._formatAsBlock != tag._formatAsBlock) {return false} if (lhs._isBlock != tag._isBlock) {return false} if (lhs._preserveWhitespace != tag._preserveWhitespace) {return false} if (lhs._selfClosing != tag._selfClosing) {return false} if (lhs._formList != tag._formList) {return false} return lhs._formSubmit == tag._formSubmit } public func equals(_ tag: Tag) -> Bool { return self == tag } /// The 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. public var hashValue: Int { return _tagName.hashValue ^ _isBlock.hashValue ^ _formatAsBlock.hashValue ^ _canContainBlock.hashValue ^ _canContainInline.hashValue ^ _empty.hashValue ^ _selfClosing.hashValue ^ _preserveWhitespace.hashValue ^ _formList.hashValue ^ _formSubmit.hashValue } open func toString() -> String { return _tagName } // internal static initialisers: // prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources private static let blockTags: [String] = [ "html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame", "noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins", "del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th", "td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main", "svg", "math" ] private static let inlineTags: [String] = [ "object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q", "sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup", "option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track", "summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track", "data", "bdi" ] private static let emptyTags: [String] = [ "meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track" ] private static let formatAsInlineTags: [String] = [ "title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style", "ins", "del", "s" ] private static let preserveWhitespaceTags: [String] = [ "pre", "plaintext", "title", "textarea" // script is not here as it is a data node, which always preserve whitespace ] // todo: I think we just need submit tags, and can scrub listed private static let formListedTags: [String] = [ "button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" ] private static let formSubmitTags: [String] = [ "input", "keygen", "object", "select", "textarea" ] static private func initializeMaps()throws->Dictionary<String, Tag> { var dict = Dictionary<String, Tag>() // creates for tagName in blockTags { let tag = Tag(tagName) dict[tag._tagName] = tag } for tagName in inlineTags { let tag = Tag(tagName) tag._isBlock = false tag._canContainBlock = false tag._formatAsBlock = false dict[tag._tagName] = tag } // mods: for tagName in emptyTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._canContainBlock = false tag?._canContainInline = false tag?._empty = true } for tagName in formatAsInlineTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formatAsBlock = false } for tagName in preserveWhitespaceTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._preserveWhitespace = true } for tagName in formListedTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formList = true } for tagName in formSubmitTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formSubmit = true } return dict } }
mit
f5adb1e239823100a2aafac62b33935c
33.284024
262
0.570331
3.961709
false
false
false
false
xwu/swift
test/Generics/unify_superclass_types_4.swift
1
1787
// RUN: %target-typecheck-verify-swift -requirement-machine=on -dump-requirement-machine 2>&1 | %FileCheck %s // Note: The GSB fails this test, because it doesn't implement unification of // superclass type constructor arguments. class Base<T> {} protocol Q { associatedtype T } class Derived<TT : Q> : Base<TT.T> {} protocol P1 { associatedtype X : Base<A1> associatedtype A1 } protocol P2 { associatedtype X : Derived<A2> associatedtype A2 : Q } func sameType<T>(_: T.Type, _: T.Type) {} func takesBase<U>(_: Base<U>.Type, _: U.Type) {} func takesDerived<U : Q>(_: Derived<U>.Type, _: U.Type) {} func unifySuperclassTest<T : P1 & P2>(_: T) { sameType(T.A1.self, T.A2.T.self) takesBase(T.X.self, T.A1.self) takesDerived(T.X.self, T.A2.self) } // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> // CHECK-NEXT: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:X].[superclass: Derived<τ_0_0> with <τ_0_0.[P2:A2]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[layout: _NativeClass] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[superclass: Base<τ_0_0> with <τ_0_0.[P1:A1]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P2:A2].[Q:T] => τ_0_0.[P1:A1] // CHECK-NEXT: } // CHECK-NEXT: Homotopy generators: { // CHECK: } // CHECK-NEXT: Property map: { // CHECK-NEXT: [P1:X] => { layout: _NativeClass superclass: [superclass: Base<τ_0_0> with <[P1:A1]>] } // CHECK-NEXT: [P2:A2] => { conforms_to: [Q] } // CHECK-NEXT: [P2:X] => { layout: _NativeClass superclass: [superclass: Derived<τ_0_0> with <[P2:A2]>] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P1 P2] } // CHECK-NEXT: τ_0_0.[P1&P2:X] => { layout: _NativeClass superclass: [superclass: Derived<τ_0_0> with <τ_0_0.[P2:A2]>] } // CHECK-NEXT: }
apache-2.0
dba4cf27e02c8c8edf6b158b84082d42
33.647059
122
0.614383
2.386486
false
false
false
false
Hodglim/hacking-with-swift
Project-18/iAds/ViewController.swift
1
1198
// // ViewController.swift // iAds // // Created by Darren Hodges on 24/06/2016. // Copyright © 2016 Darren Hodges. All rights reserved. // import UIKit import iAd class ViewController: UIViewController, ADBannerViewDelegate { var bannerView: ADBannerView! override func viewDidLoad() { super.viewDidLoad() bannerView = ADBannerView(adType: .Banner) bannerView.translatesAutoresizingMaskIntoConstraints = false bannerView.delegate = self bannerView.hidden = true view.addSubview(bannerView) let viewsDictionary = ["bannerView": bannerView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: [], metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: [], metrics: nil, views: viewsDictionary)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bannerViewDidLoadAd(banner: ADBannerView!) { bannerView.hidden = false } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { bannerView.hidden = true } }
mit
ed65eb498ed8584ec7c914dcf871b154
24.468085
140
0.756892
4.336957
false
false
false
false
eleks/digital-travel-book
src/Swift/Weekend In Lviv/Data Model/WLPlace.swift
1
680
// // WLPlace.swift // Weekend In Lviv // // Created by Admin on 19.06.14. // Copyright (c) 2014 rnd. All rights reserved. // import Foundation class WLPlace : NSObject { var title:String = "" var placeText:String = "" var placeTopImagePath:String = "" var placeMenuImagePath:String = "" var listImagePath:String = "" var placesTextBlocks:[WLTextBlock] = [] var placesPointBlocks:[WLPointBlock] = [] var placeAudioPath:String = "" var placeFavourite:Bool = false var moIdentificator:NSNumber = 0 }
mit
6a3e948c7cf69343c5bbc93683d19b69
27.375
51
0.532353
4.171779
false
false
false
false
XLabKC/Badger
Badger/Badger/HeaderCell.swift
1
1630
import UIKit protocol HeaderCellDelegate: class { func headerCellButtonPressed(cell: HeaderCell) } class HeaderCell : BorderedCell { @IBOutlet weak var headerLabel: UILabel! @IBOutlet weak var headerButton: UIButton! @IBOutlet weak var buttonConstraint: NSLayoutConstraint! weak var delegate: HeaderCellDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.selectionStyle = .None } override func awakeFromNib() { self.showButton = false } var title: String? { get { return self.headerLabel.text } set(title) { self.headerLabel.text = title } } var labelColor: UIColor! { get { return self.headerLabel.textColor } set(color) { self.headerLabel.textColor = color } } var buttonText: String? { get { return self.headerButton.titleForState(.Normal) } set(title) { self.headerButton.setTitle(title, forState: .Normal) self.showButton = true } } var showButton: Bool { get { return !self.headerButton.hidden } set(show) { self.headerButton.hidden = !show } } var buttonInset: CGFloat { get { return self.buttonConstraint.constant } set(value) { self.buttonConstraint.constant = value } } @IBAction func buttonPressed(sender: AnyObject) { self.delegate?.headerCellButtonPressed(self) } }
gpl-2.0
13504b40fa1844dcb54517d8d712ba01
21.342466
64
0.573006
4.794118
false
false
false
false
pietro82/TransitApp
TransitApp/Utils.swift
1
1278
// // Utils.swift // TransitApp // // Created by Pietro Santececca on 24/01/17. // Copyright © 2017 Tecnojam. All rights reserved. // import Foundation struct Utils { static func convertToTime(seconds: Double) -> String { return convertToTime(seconds: Int(seconds)) } static func convertToTime(seconds: Int) -> String { let hour = seconds / 3600 let minute = (seconds % 3600) / 60 var time = "" if hour > 0 { time += "\(hour) h " } if minute > 0 { time += "\(minute) min" } return time } static func convertToTime(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.string(from: date) } static func convertToString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "E, dd MMM, HH:mm" return dateFormatter.string(from: date) } static func convertToDate(string: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-ddEEEEHH:mm:ssZZZ" return dateFormatter.date(from: string) } }
mit
980086585cfe0ceafa7d943aea126b3e
24.54
62
0.575568
4.285235
false
false
false
false
cotkjaer/SilverbackFramework
SilverbackFramework/CGFloat.swift
1
1919
// // CGFloat.swift // Pods // // Created by Christian Otkjær on 20/04/15. // // import CoreGraphics // MARK: - Equals public let CGFloatZero = CGFloat(0.0) extension CGFloat { public func isEqualWithin(precision: CGFloat, to: CGFloat) -> Bool { return abs(self - to) < abs(precision) } } public func equalsWithin(precision: CGFloat, f1: CGFloat, to f2: CGFloat) -> Bool { return abs(f1 - f2) < abs(precision) } public func * (rhs: CGFloat, lhs: Int) -> CGFloat { return rhs * CGFloat(lhs) } public func * (rhs: Int, lhs: CGFloat) -> CGFloat { return CGFloat(rhs) * lhs } public func += (inout rhs: CGFloat, lhs: Int) { rhs += CGFloat(lhs) } public func -= (inout rhs: CGFloat, lhs: Int) { rhs += CGFloat(lhs) } public func *= (inout rhs: CGFloat, lhs: Int) { rhs *= CGFloat(lhs) } public func /= (inout rhs: CGFloat, lhs: Int) { rhs /= CGFloat(lhs) } //MARK: - Angles public let π = CGFloat(M_PI) public let π2 = π * 2 internal let sin60 : CGFloat = 0.866025403784439 public extension CGFloat { /// Normalizes self to be in ]-π;π] public var normalizedRadians: CGFloat { return self - ( ceil( self / π2 - 0.5 ) ) * π2 } } /// Normalizes angle to be in ]-π;π] public func normalizeRadians(radians: CGFloat) -> CGFloat { return radians - ( ceil( radians / π2 - 0.5 ) ) * π2 } //MARK: - Random extension CGFloat { /** Create a random CGFloat - parameter lower: bounds - parameter upper: bounds :return: random number CGFloat */ public static func random(lower lower: CGFloat, upper: CGFloat) -> CGFloat { let r = CGFloat(arc4random(UInt32)) / CGFloat(UInt32.max) return (r * (upper - lower)) + lower } } public extension CGFloat { public func format(format: String? = "") -> String { return String(format: "%\(format)f", self) } }
mit
638280e5d668b0a2676ed3027079ecf7
17.514563
81
0.613005
3.265411
false
false
false
false
wireapp/wire-ios-data-model
Source/Notifications/SnapshotCenter.swift
1
4738
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireUtilities struct Snapshot { let attributes: [String: NSObject?] let toManyRelationships: [String: Int] let toOneRelationships: [String: NSManagedObjectID] } protocol Countable { var count: Int { get } } extension NSOrderedSet: Countable {} extension NSSet: Countable {} public class SnapshotCenter { private unowned var managedObjectContext: NSManagedObjectContext internal var snapshots: [NSManagedObjectID: Snapshot] = [:] public init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext } func createSnapshots(for insertedObjects: Set<NSManagedObject>) { insertedObjects.forEach { if $0.objectID.isTemporaryID { try? managedObjectContext.obtainPermanentIDs(for: [$0]) } let newSnapshot = createSnapshot(for: $0) snapshots[$0.objectID] = newSnapshot } } func updateSnapshot(for object: NSManagedObject) { snapshots[object.objectID] = createSnapshot(for: object) } func createSnapshot(for object: NSManagedObject) -> Snapshot { let attributes = Array(object.entity.attributesByName.keys) let relationships = object.entity.relationshipsByName let attributesDict = attributes.mapToDictionaryWithOptionalValue {object.primitiveValue(forKey: $0) as? NSObject} let toManyRelationshipsDict: [String: Int] = relationships.mapKeysAndValues(keysMapping: {$0}, valueMapping: { (key, relationShipDescription) in guard relationShipDescription.isToMany else { return nil } return (object.primitiveValue(forKey: key) as? Countable)?.count }) let toOneRelationshipsDict: [String: NSManagedObjectID] = relationships.mapKeysAndValues(keysMapping: {$0}, valueMapping: { (key, relationshipDescription) in guard !relationshipDescription.isToMany else { return nil } return (object.primitiveValue(forKey: key) as? NSManagedObject)?.objectID }) return Snapshot( attributes: attributesDict, toManyRelationships: toManyRelationshipsDict, toOneRelationships: toOneRelationshipsDict ) } /// Before merging the sync into the ui context, we create a snapshot of all changed objects /// This function compares the snapshot values to the current ones and returns all keys and new values where the value changed due to the merge func extractChangedKeysFromSnapshot(for object: ZMManagedObject) -> Set<String> { guard let snapshot = snapshots[object.objectID] else { if object.objectID.isTemporaryID { try? managedObjectContext.obtainPermanentIDs(for: [object]) } // create new snapshot let newSnapshot = createSnapshot(for: object) snapshots[object.objectID] = newSnapshot // return all keys as changed return Set(newSnapshot.attributes.keys) .union(newSnapshot.toManyRelationships.keys) .union(newSnapshot.toOneRelationships.keys) } var changedKeys = Set<String>() snapshot.attributes.forEach { let currentValue = object.primitiveValue(forKey: $0) as? NSObject if currentValue != $1 { changedKeys.insert($0) } } snapshot.toManyRelationships.forEach { guard let count = (object.value(forKey: $0) as? Countable)?.count, count != $1 else { return } changedKeys.insert($0) } snapshot.toOneRelationships.forEach { guard (object.value(forKey: $0) as? NSManagedObject)?.objectID != $1 else { return } changedKeys.insert($0) } // Update snapshot if changedKeys.count > 0 { snapshots[object.objectID] = createSnapshot(for: object) } return changedKeys } func clearAllSnapshots() { snapshots = [:] } }
gpl-3.0
8f8bc0c0fc997050bbf013143e533d37
37.836066
165
0.669059
4.889577
false
false
false
false
rohan1989/FacebookOauth2Swift
FacebookOauth2Swift/FacebookManager/FacebookManager.swift
1
4664
// // FacebookManager.swift // FacebookOauth2Swift // // Created by Rohan Sonawane on 04/12/16. // Copyright © 2016 Rohan Sonawane. All rights reserved. // import UIKit import OAuthSwift /** Facebook Manager Constants. - consumerKey: Facebook application ID. - consumerSecret: Facebook application secret. - authorizeUrl: Authentication URL. - accessTokenUrl: Access Token URL. - responseType: Type of response expected. - callbackURL: Use same URL as redirect URI on facebook. - scopePublicProfile: User permission to access public profile. - scopeUserPhotos: User permission to access photos. - state: Query string. - facebookPhotosURL: URL to get facebook photos. - pageLimit: Pagination limit. - pageOffset: Pagination offset. */ struct FacebookManagerConstants { static let consumerKey = "203995400058678" static let consumerSecret = "e7d2a81537e097023fc84ea9e94d74b5" static let authorizeUrl = "https://www.facebook.com/dialog/oauth" static let accessTokenUrl = "https://graph.facebook.com/oauth/access_token" static let responseType = "code" static let callbackURL = "https://oauthswift.herokuapp.com/callback/facebook" static let scopePublicProfile = "public_profile" static let scopeUserPhotos = "user_photos" static let state = "fb" static let facebookPhotosURL = "https://graph.facebook.com/me/photos/uploaded?fields=images" static let pageLimit = "10000" static let pageOffset = "0" } open class FacebookManager: NSObject { /** Facebook authentication and get user photos @param viewController A viewcontroller who's calling this function. Used for SafariURLHandler. @param completionWithPhotos Gets photos array and error @return None. */ func loginWithFacebookAndGetPhotos(viewController:Any, completionWithPhotos: @escaping (_ photosArray: Array<Any>?, _ error:NSError?) -> Void) { let oauthswift = OAuth2Swift( consumerKey: FacebookManagerConstants.consumerKey, consumerSecret: FacebookManagerConstants.consumerSecret, authorizeUrl: FacebookManagerConstants.authorizeUrl, accessTokenUrl: FacebookManagerConstants.accessTokenUrl, responseType: FacebookManagerConstants.responseType ) oauthswift.authorizeURLHandler = SafariURLHandler(viewController: viewController as! UIViewController, oauthSwift: oauthswift) let _ = oauthswift.authorize( withCallbackURL: URL(string: FacebookManagerConstants.callbackURL)!, scope: "\(FacebookManagerConstants.scopePublicProfile), \(FacebookManagerConstants.scopeUserPhotos)", state: FacebookManagerConstants.state, success: { credential, response, parameters in self.getFacebookPhotos(oauthswift, completionWithPhotos: {photosArray, error in if photosArray?.count != nil{ completionWithPhotos(photosArray, NSError(domain: "", code: 222, userInfo: nil)) } else{ completionWithPhotos(nil, NSError(domain: (error?.localizedDescription)!, code: 111, userInfo: nil)) } }) }, failure: { error in completionWithPhotos(nil, NSError(domain: error.localizedDescription, code: 111, userInfo: nil)) } ) } // MARK: ---------- Private Functions ---------- /** Get facebook photos @param oauthswift OAuth2Swift object to make a valid request to facebook using an access token @param completionWithPhotos Gets photos array and error @return None. */ private func getFacebookPhotos(_ oauthswift: OAuth2Swift, completionWithPhotos: @escaping (_ photosArray: Array<Any>?, _ error:NSError?) -> Void) { let parameters :Dictionary = ["limit":FacebookManagerConstants.pageLimit, "offset":FacebookManagerConstants.pageOffset] let _ = oauthswift.client.get(FacebookManagerConstants.facebookPhotosURL, parameters: parameters, headers: nil, success: { response in let responseData = response.data //parse facebook response let parsingManager = ParsingManager() parsingManager.parseFacebookPhotos(responseData: responseData, completionWithPhotos: {photosArray, error in completionWithPhotos(photosArray!, error) }) }, failure: { error in completionWithPhotos(nil, NSError(domain: error.localizedDescription, code: 111, userInfo: nil)) }) } }
mit
91b6284a2ba6d44f602e14612f8d6657
40.633929
221
0.678748
4.955367
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/SideImageDesignable.swift
5
3002
// // Created by Jake Lin on 12/8/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit /// Protocol for designing side image public protocol SideImageDesignable { /** * The left image */ var leftImage: UIImage? { get set } /** * Left padding of the left image, default value is CGFloat.nan */ var leftImageLeftPadding: CGFloat { get set } /** * Right padding of the left image, default value is CGFloat.nan */ var leftImageRightPadding: CGFloat { get set } /** * Top padding of the left image, default value is CGFloat.nan */ var leftImageTopPadding: CGFloat { get set } /** * The right image */ var rightImage: UIImage? { get set } /** * Left padding of the right image, default value is CGFloat.nan */ var rightImageLeftPadding: CGFloat { get set } /** * Right padding of the right image, default value is CGFloat.nan */ var rightImageRightPadding: CGFloat { get set } /** * Top padding of the right image, default value is CGFloat.nan */ var rightImageTopPadding: CGFloat { get set } } public extension SideImageDesignable where Self: UITextField { public func configureImages() { configureLeftImage() configureRightImage() } } fileprivate extension SideImageDesignable where Self: UITextField { func configureLeftImage() { guard let leftImage = leftImage else { return } let sideView = makeSideView(with: leftImage, leftPadding: leftImageLeftPadding, rightPadding: leftImageRightPadding, topPadding: leftImageTopPadding) leftViewMode = .always leftView = sideView } func configureRightImage() { guard let rightImage = rightImage else { return } let sideView = makeSideView(with: rightImage, leftPadding: rightImageLeftPadding, rightPadding: rightImageRightPadding, topPadding: rightImageTopPadding) rightViewMode = .always rightView = sideView } func makeSideView(with image: UIImage, leftPadding: CGFloat, rightPadding: CGFloat, topPadding: CGFloat) -> UIView { let imageView = UIImageView(image: image) // If not set, use 0 as default value var leftPaddingValue: CGFloat = 0.0 if !leftPadding.isNaN { leftPaddingValue = leftPadding } // If not set, use 0 as default value var rightPaddingValue: CGFloat = 0.0 if !rightPadding.isNaN { rightPaddingValue = rightPadding } // If does not specify `topPadding`, then center it in the middle if topPadding.isNaN { imageView.frame.origin = CGPoint(x: leftPaddingValue, y: (bounds.height - imageView.bounds.height) / 2) } else { imageView.frame.origin = CGPoint(x: leftPaddingValue, y: topPadding) } let padding = rightPaddingValue + imageView.bounds.size.width + leftPaddingValue let sideView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: bounds.height)) sideView.addSubview(imageView) return sideView } }
gpl-3.0
b7b14ce7b477dd52348f4a56f12a99c0
27.311321
157
0.685438
4.540091
false
false
false
false
VidyasagarMSC/NearBY
NearBY-iOS/CognitiveConcierge/WhitePathIconBarButtonItem.swift
1
1670
/** * 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 UIKit class WhitePathIconBarButtonItem: UIBarButtonItem { let moreWhitePathButton = UIButton() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() setupPathIconButton() } func goToPath() { if let currentVC = Utils.getCurrentViewController() { _ = currentVC.navigationController?.popViewController(animated: true) } } private func getWhitePathIconButton() -> UIButton { moreWhitePathButton.setImage(UIImage(named: "path_white"), for: .normal) moreWhitePathButton.addTarget(self, action: #selector(WhitePathIconBarButtonItem.goToPath), for: .touchUpInside) moreWhitePathButton.frame = CGRect(x: 11.8, y: 33.5, width: 6, height: 12.2) // Set opacity moreWhitePathButton.alpha = 0.45 return moreWhitePathButton } private func setupPathIconButton() { self.customView = getWhitePathIconButton() } }
apache-2.0
ac32256678a4e22308b85fa72eb2d4e1
29.363636
120
0.675449
4.429708
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/CardsAnimator.swift
5
5327
// // Created by Tom Baranes on 01/05/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class CardsAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var fromDirection: TransitionAnimationType.Direction public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) { self.transitionDuration = transitionDuration fromDirection = direction switch fromDirection { case .backward: self.transitionAnimationType = .cards(direction: .backward) self.reverseAnimationType = .cards(direction: .forward) default: self.transitionAnimationType = .cards(direction: .forward) self.reverseAnimationType = .cards(direction: .backward) } super.init() } } extension CardsAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext: transitionContext) guard let fromView = tempfromView, let toView = tempToView, let containerView = tempContainerView else { transitionContext.completeTransition(true) return } if fromDirection == .forward { executeForwardAnimation(transitionContext: transitionContext, containerView: containerView, fromView: fromView, toView: toView) } else { executeBackwardAnimation(transitionContext: transitionContext, containerView: containerView, fromView: fromView, toView: toView) } } } // MARK: - Forward private extension CardsAnimator { func executeBackwardAnimation(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { let frame = fromView.frame var offScreenFrame = frame offScreenFrame.origin.y = offScreenFrame.height toView.frame = offScreenFrame containerView.insertSubview(toView, aboveSubview: fromView) let t1 = firstTransform() let t2 = secondTransformWithView(view: fromView) UIView.animateKeyframes(withDuration: transitionDuration, delay: 0.0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.4) { fromView.layer.transform = t1 fromView.alpha = 0.6 } UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.4) { fromView.layer.transform = t2 } UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.2) { toView.frame = toView.frame.offsetBy(dx: 0.0, dy: -30.0) } UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 0.2) { toView.frame = frame } }) { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Reverse private extension CardsAnimator { func executeForwardAnimation(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { let frame = fromView.frame toView.frame = frame let scale = CATransform3DIdentity toView.layer.transform = CATransform3DScale(scale, 0.6, 0.6, 1) toView.alpha = 0.6 containerView.insertSubview(toView, belowSubview: fromView) var frameOffScreen = frame frameOffScreen.origin.y = frame.height let t1 = firstTransform() UIView.animateKeyframes(withDuration: transitionDuration, delay: 0.0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.5) { fromView.frame = frameOffScreen } UIView.addKeyframe(withRelativeStartTime: 0.35, relativeDuration: 0.35) { toView.layer.transform = t1 toView.alpha = 1.0 } UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25) { toView.layer.transform = CATransform3DIdentity } }) { _ in if transitionContext.transitionWasCancelled { toView.layer.transform = CATransform3DIdentity toView.alpha = 1.0 } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Helper private extension CardsAnimator { func firstTransform() -> CATransform3D { var t1 = CATransform3DIdentity t1.m34 = 1.0 / -900 t1 = CATransform3DScale(t1, 0.95, 0.95, 1) t1 = CATransform3DRotate(t1, 15.0 * .pi / 180.0, 1, 0, 0) return t1 } func secondTransformWithView(view: UIView) -> CATransform3D { var t2 = CATransform3DIdentity t2.m34 = firstTransform().m34 t2 = CATransform3DTranslate(t2, 0, view.frame.size.height * -0.08, 0) t2 = CATransform3DScale(t2, 0.8, 0.8, 1) return t2 } }
gpl-3.0
1485ec478b5ed69e4e70b05b9a967be0
33.36129
147
0.719114
4.717449
false
false
false
false
lotz84/__.swift
__.swift/Functions/__Functions.swift
1
4302
// // __Functions.swift // __.swift // // Copyright (c) 2014 Tatsuya Hirose // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension __ { // partial apply to function which takes 2 variables public class func partial<T, U, V>(f: (T, U) -> V, _ arg: T ) -> ( U -> V ) { return { f(arg, $0) } } // partially act to function which takes 3 variables public class func partial<T, U, V, W>(f: (T, U, V) -> W, _ arg: T ) -> ( (U, V) -> W ) { return { f(arg, $0, $1) } } // partially act to function which takes 4 variables public class func partial<T, U, V, W, X>(f: (T, U, V, W) -> X, _ arg: T ) -> ( (U, V, W) -> X ) { return { f(arg, $0, $1, $2) } } // partially act to function which takes 5 variables public class func partial<T, U, V, W, X, Y>(f: (T, U, V, W, X) -> Y, _ arg: T ) -> ( (U, V, W, X) -> Y ) { return { f(arg, $0, $1, $2, $3) } } // partially act to function which takes 6 variables public class func partial<T, U, V, W, X, Y, Z>(f: (T, U, V, W, X, Y) -> Z, _ arg: T ) -> ( (U, V, W, X, Y) -> Z ) { return { f(arg, $0, $1, $2, $3, $4) } } // partially act to function which takes 7 variables public class func partial<T, U, V, W, X, Y, Z, A>(f: (T, U, V, W, X, Y, Z) -> A, _ arg: T ) -> ( (U, V, W, X, Y, Z) -> A ) { return { f(arg, $0, $1, $2, $3, $4, $5) } } // This is amazing memoize function in [Advanced Swift](https://developer.apple.com/videos/wwdc/2014/?id=404) public class func memoize<T: Hashable, U>(body: (T->U, T) -> U ) -> T -> U { var memo : [T:U] = [:] var result: (T -> U)! result = { x in if let q = memo[x] { return q } let r = body(result, x) memo[x] = r return r } return result } public class func throttle<T, U>(f: T -> U, wait: Double) -> T -> U? { var lastFiredTime: Double? func executor(arg: T) -> U? { let now = __.now() if lastFiredTime == nil || (now - lastFiredTime! > wait) { lastFiredTime = now return f(arg) } else { return nil } } return executor } public class func once<T, U>(f: T-> U) -> T -> U? { var isExecuted = false func executor(arg: T) -> U? { if isExecuted { return nil } else { isExecuted = true return f(arg) } } return executor } public class func after<T, U>(count: Int, function: T -> U ) -> T -> U? { var now = 0 func executor(arg:T) -> U? { now += 1 return now < count ? nil : function(arg) } return executor } public class func now() -> Double { return NSDate().timeIntervalSince1970 } public class func wrap<T, U, V, W>(f: T -> U, withWrapper wrapper:(T -> U , V) -> W)(arg: V) -> W { return wrapper(f, arg) } public class func compose<T, U, V>(g: U -> V, _ f: T -> U)(x: T) -> V { return g(f(x)) } }
mit
4d8bff5426979c3726aacde46636f965
34.858333
128
0.532078
3.455422
false
false
false
false
fluidsonic/JetPack
Sources/Extensions/Foundation/NSRange.swift
1
3039
import Foundation public extension NSRange { static let notFound = NSRange(location: NSNotFound, length: 0) init(forString string: String) { let indices = string.indices self.init(range: indices.startIndex ..< indices.endIndex, inString: string) } init(range: Range<String.Index>?, inString string: String) { if let range = range { let location = NSRange.locationForIndex(range.lowerBound, inString: string) let endLocation = NSRange.locationForIndex(range.upperBound, inString: string) self.init(location: location, length: location.distance(to: endLocation)) } else { self.init(location: NSNotFound, length: 0) } } func clamped(to limits: NSRange) -> NSRange { if location == NSNotFound || limits.location == NSNotFound { return .notFound } let endLocation = self.endLocation if endLocation <= limits.location { return NSRange(location: limits.location, length: 0) } let endLocationLimit = limits.endLocation if endLocationLimit <= location { return NSRange(location: endLocationLimit, length: 0) } let clampedLocation = location.coerced(atLeast: limits.location) let clampedEndLocation = endLocation.coerced(atMost: endLocationLimit) return NSRange(location: clampedLocation, length: clampedEndLocation - clampedLocation) } func endIndexInString(_ string: String) -> String.Index? { return NSRange.indexForLocation(NSMaxRange(self), inString: string) } var endLocation: Int { guard location != NSNotFound else { return NSNotFound } return location + length } fileprivate static func indexForLocation(_ location: Int, inString string: String) -> String.Index? { if location == NSNotFound { return nil } let utf16 = string.utf16 return utf16.index(utf16.startIndex, offsetBy: location, limitedBy: utf16.endIndex)?.samePosition(in: string) } fileprivate static func locationForIndex(_ index: String.Index, inString string: String) -> Int { let utf16 = string.utf16 guard let utf16Index = index.samePosition(in: utf16) else { return NSNotFound } return utf16.distance(from: utf16.startIndex, to: utf16Index) } func rangeInString(_ string: String) -> Range<String.Index>? { if let startIndex = startIndexInString(string), let endIndex = endIndexInString(string) { return startIndex ..< endIndex } return nil } func startIndexInString(_ string: String) -> String.Index? { return NSRange.indexForLocation(location, inString: string) } func toCountableRange() -> CountableRange<Int>? { return Range(self).map { $0.lowerBound ..< $0.upperBound } } } extension NSRange: Sequence { public typealias Iterator = CountableRange<Int>.Iterator public func makeIterator() -> Iterator { guard location != NSNotFound else { return (0 ..< 0).makeIterator() } return (location ..< (location + length)).makeIterator() } } public extension Range where Bound == Int { func toNSRange() -> NSRange { return NSRange(location: lowerBound, length: upperBound - lowerBound) } }
mit
99213a03fd50218a82ad43c359509e3e
22.742188
111
0.720303
3.841972
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/PartialViews/SearchBar/SFSearchBar.swift
2
7211
// // SFSearchBar.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 03/11/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kOKSearchBarCustomSearchIconTraillingOffset = -15.0 let kOKSearchBarCustomSearchIconBottomOffset = -10.0 class SFSearchBar: UISearchBar, UISearchBarDelegate { var isCancelShown: Bool required init?(coder aDecoder: NSCoder) { self.isCancelShown = true super.init(coder: aDecoder) self.commonInit() } func setDelegate(delegate: UISearchBarDelegate) { super.delegate = self _externalDelegate = delegate } override var text: String? { get { return super.text } set { super.text = newValue self.setIsShownCustomSearchIcon(isShown: false) } } // MARK: // MARK: Internal // MARK: var _customSearchIconImageView: UIImageView? weak var _externalDelegate: AnyObject? func setIsShownCustomSearchIcon(isShown: Bool) { if isShown { UIView.animate(withDuration: 0.2, delay:0.2, options: UIViewAnimationOptions.curveEaseIn, animations: { [weak self] in self?._customSearchIconImageView?.alpha = 1.0 }, completion: nil) } else { self._customSearchIconImageView?.alpha = 0 } } internal func commonInit() { // Adjust search style self.backgroundColor = UIColor.clear self.backgroundImage = UIImage() // Customize cancel color UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = kColorGreen let searchBarIconImage: UIImage = UIImage(named: "iconSearchBar")! _customSearchIconImageView = UIImageView.init(image: searchBarIconImage) // Change search bar icon. Using a workaround: // 1. Hide search icon UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).leftViewMode = UITextFieldViewMode.never // For changing cursor color //[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:kColorBlueLight]; // 2. Add search image as subView self.addSubview(_customSearchIconImageView!) // 3. Add needed constraints _ = _customSearchIconImageView?.viewAddBottomSpace(CGFloat(kOKSearchBarCustomSearchIconBottomOffset), containerView: self) _ = _customSearchIconImageView?.viewAddTrailingSpace(CGFloat(kOKSearchBarCustomSearchIconTraillingOffset), containerView: self) // Change search bar icon //[_searchBar setImage:customSearcBarIconImage forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; UITextField.appearance(whenContainedInInstancesOf: [SFSearchBar.self]).textColor = kColorGreen UITextField.appearance(whenContainedInInstancesOf: [SFSearchBar.self]).backgroundColor = kColorGrayLight2 } // MARK: Forwarding events func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { var result: Bool = true result = (_externalDelegate?.searchBarShouldBeginEditing(searchBar))! return result } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { self.setIsShownCustomSearchIcon(isShown: false) if (self.isCancelShown) { self.setShowsCancelButton(true, animated: true) } _externalDelegate?.searchBarTextDidBeginEditing(searchBar) } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { var result = true result = (_externalDelegate?.searchBarShouldEndEditing(searchBar))! return result } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { // Search bar shows clear button even after resign first responder if there's a text // Therefore we won't show search icon on top if let text = searchBar.text { if text.characters.count == 0 { self.setIsShownCustomSearchIcon(isShown: true) } } self.setShowsCancelButton(false, animated: true) _externalDelegate?.searchBarTextDidEndEditing(searchBar) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { _externalDelegate?.searchBarSearchButtonClicked(searchBar) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.text = "" self.setShowsCancelButton(false, animated: true) _externalDelegate?.searchBarCancelButtonClicked(searchBar) } func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) { _externalDelegate?.searchBarResultsListButtonClicked(searchBar) } func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) { _externalDelegate?.searchBarBookmarkButtonClicked(searchBar) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { _externalDelegate?.searchBar(searchBar, textDidChange: searchText) } func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { var result: Bool = true result = (_externalDelegate?.searchBar(searchBar, shouldChangeTextIn: range, replacementText: text))! return result } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { _externalDelegate?.searchBar(searchBar, selectedScopeButtonIndexDidChange: selectedScope) } }
mit
ab029bb000938e7441660535be49a3d8
33.658654
135
0.65335
5.519908
false
false
false
false
fr500/RetroArch
pkg/apple/OnScreenKeyboard/EmulatorKeyboardView.swift
6
11524
// // EmulatorKeyboard.swift // // Created by Yoshi Sugawara on 7/30/20. // // TODO: shift key should change the label of the keys to uppercase (need callback mechanism?) // pan gesture to outer edges of keyboard view for better dragging @objc protocol EmulatorKeyboardKeyPressedDelegate: AnyObject { func keyDown(_ key: KeyCoded) func keyUp(_ key: KeyCoded) } @objc protocol EmulatorKeyboardModifierPressedDelegate: AnyObject { func modifierPressedWithKey(_ key: KeyCoded, enable: Bool) func isModifierEnabled(key: KeyCoded) -> Bool } protocol EmulatorKeyboardViewDelegate: AnyObject { func toggleAlternateKeys() func refreshModifierStates() func updateTransparency(toAlpha alpha: Float) } class EmulatorKeyboardView: UIView { static var keyboardBackgroundColor = UIColor.systemGray6.withAlphaComponent(0.5) static var keyboardCornerRadius = 6.0 static var keyboardDragColor = UIColor.systemGray static var keyCornerRadius = 6.0 static var keyBorderWidth = 1.0 static var rowSpacing = 12.0 static var keySpacing = 8.0 static var keyNormalFont = UIFont.systemFont(ofSize: 12) static var keyPressedFont = UIFont.boldSystemFont(ofSize: 24) static var keyNormalBackgroundColor = UIColor.systemGray4.withAlphaComponent(0.5) static var keyNormalBorderColor = keyNormalBackgroundColor static var keyNormalTextColor = UIColor.label static var keyPressedBackgroundColor = UIColor.systemGray2 static var keyPressedBorderColor = keyPressedBackgroundColor static var keyPressedTextColor = UIColor.label static var keySelectedBackgroundColor = UIColor.systemGray2.withAlphaComponent(0.8) static var keySelectedBorderColor = keySelectedBackgroundColor static var keySelectedTextColor = UIColor.label var viewModel = EmulatorKeyboardViewModel(keys: [[KeyCoded]]()) { didSet { setupWithModel(viewModel) } } var modifierButtons = Set<EmulatorKeyboardButton>() weak var delegate: EmulatorKeyboardViewDelegate? private lazy var keyRowsStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .equalCentering stackView.spacing = Self.rowSpacing return stackView }() private lazy var alternateKeyRowsStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .equalCentering stackView.spacing = Self.rowSpacing stackView.isHidden = true return stackView }() let dragMeView: UIView = { let view = UIView(frame: .zero) view.backgroundColor = EmulatorKeyboardView.keyboardDragColor view.translatesAutoresizingMaskIntoConstraints = false view.widthAnchor.constraint(equalToConstant: 80).isActive = true view.heightAnchor.constraint(equalToConstant: 2).isActive = true let outerView = UIView(frame: .zero) outerView.backgroundColor = .clear outerView.translatesAutoresizingMaskIntoConstraints = false outerView.addSubview(view) view.centerXAnchor.constraint(equalTo: outerView.centerXAnchor).isActive = true view.centerYAnchor.constraint(equalTo: outerView.centerYAnchor).isActive = true outerView.heightAnchor.constraint(equalToConstant: 20).isActive = true outerView.widthAnchor.constraint(equalToConstant: 100).isActive = true return outerView }() private var pressedKeyViews = [UIControl: UIView]() convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = Self.keyboardBackgroundColor layer.cornerRadius = Self.keyboardCornerRadius layoutMargins = UIEdgeInsets(top: 16, left: 4, bottom: 16, right: 4) insetsLayoutMarginsFromSafeArea = false addSubview(keyRowsStackView) keyRowsStackView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true keyRowsStackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor, constant: 4.0).isActive = true keyRowsStackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor, constant: -4.0).isActive = true addSubview(alternateKeyRowsStackView) alternateKeyRowsStackView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true alternateKeyRowsStackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor, constant: 4.0).isActive = true alternateKeyRowsStackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor, constant: -4.0).isActive = true addSubview(dragMeView) dragMeView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true dragMeView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } @objc private func keyPressed(_ sender: EmulatorKeyboardButton) { if sender.key.keyCode == 9000 { // hack for now return } if !sender.key.isModifier { // make a "stand-in" for our key, and scale up key let view = UIView() view.backgroundColor = EmulatorKeyboardView.keyPressedBackgroundColor view.layer.cornerRadius = EmulatorKeyboardView.keyCornerRadius view.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] view.frame = sender.convert(sender.bounds, to: self) addSubview(view) var tx = 0.0 let ty = sender.bounds.height * -1.20 if let window = self.window { let rect = sender.convert(sender.bounds, to:window) if rect.maxX > window.bounds.width * 0.9 { tx = sender.bounds.width * -0.5 } if rect.minX < window.bounds.width * 0.1 { tx = sender.bounds.width * 0.5 } } sender.superview!.bringSubviewToFront(sender) sender.transform = CGAffineTransform(translationX:tx, y:ty).scaledBy(x:2, y:2) pressedKeyViews[sender] = view } viewModel.keyPressed(sender.key) } @objc private func keyCancelled(_ sender: EmulatorKeyboardButton) { sender.transform = .identity if let view = pressedKeyViews[sender] { view.removeFromSuperview() pressedKeyViews.removeValue(forKey: sender) } } @objc private func keyReleased(_ sender: EmulatorKeyboardButton) { sender.transform = .identity if sender.key.keyCode == 9000 { delegate?.toggleAlternateKeys() return } if let view = pressedKeyViews[sender] { view.removeFromSuperview() pressedKeyViews.removeValue(forKey: sender) } sender.isSelected = viewModel.modifierKeyToggleStateForKey(sender.key) viewModel.keyReleased(sender.key) self.delegate?.refreshModifierStates() } func setupWithModel(_ model: EmulatorKeyboardViewModel) { for row in model.keys { let keysInRow = createKeyRow(keys: row) keyRowsStackView.addArrangedSubview(keysInRow) } if let altKeys = model.alternateKeys { for row in altKeys { let keysInRow = createKeyRow(keys: row) alternateKeyRowsStackView.addArrangedSubview(keysInRow) } } if !model.isDraggable { dragMeView.isHidden = true } } func toggleKeysStackView() { if viewModel.alternateKeys != nil { keyRowsStackView.isHidden.toggle() alternateKeyRowsStackView.isHidden.toggle() refreshModifierStates() } } func refreshModifierStates() { modifierButtons.forEach{ button in button.isSelected = viewModel.modifierKeyToggleStateForKey(button.key) } } private func createKey(_ keyCoded: KeyCoded) -> UIButton { let key = EmulatorKeyboardButton(key: keyCoded) if let imageName = keyCoded.keyImageName { key.tintColor = EmulatorKeyboardView.keyNormalTextColor key.setImage(UIImage(systemName: imageName), for: .normal) if let highlightedImageName = keyCoded.keyImageNameHighlighted { key.setImage(UIImage(systemName: highlightedImageName), for: .highlighted) key.setImage(UIImage(systemName: highlightedImageName), for: .selected) } } else { key.setTitle(keyCoded.keyLabel, for: .normal) key.titleLabel?.font = EmulatorKeyboardView.keyNormalFont key.setTitleColor(EmulatorKeyboardView.keyNormalTextColor, for: .normal) key.setTitleColor(EmulatorKeyboardView.keySelectedTextColor, for: .selected) key.setTitleColor(EmulatorKeyboardView.keyPressedTextColor, for: .highlighted) } key.translatesAutoresizingMaskIntoConstraints = false key.widthAnchor.constraint(equalToConstant: (25 * CGFloat(keyCoded.keySize.rawValue))).isActive = true key.heightAnchor.constraint(equalToConstant: 35).isActive = true key.backgroundColor = EmulatorKeyboardView.keyNormalBackgroundColor key.layer.borderWidth = EmulatorKeyboardView.keyBorderWidth key.layer.borderColor = EmulatorKeyboardView.keyNormalBorderColor.cgColor key.layer.cornerRadius = EmulatorKeyboardView.keyCornerRadius key.addTarget(self, action: #selector(keyPressed(_:)), for: .touchDown) key.addTarget(self, action: #selector(keyReleased(_:)), for: .touchUpInside) key.addTarget(self, action: #selector(keyReleased(_:)), for: .touchUpOutside) key.addTarget(self, action: #selector(keyCancelled(_:)), for: .touchCancel) if keyCoded.isModifier { modifierButtons.update(with: key) } return key } private func createKeyRow(keys: [KeyCoded]) -> UIStackView { let subviews: [UIView] = keys.enumerated().map { index, keyCoded -> UIView in if keyCoded is SpacerKey { let spacer = UIView() spacer.widthAnchor.constraint(equalToConstant: 25.0 * CGFloat(keyCoded.keySize.rawValue)).isActive = true spacer.heightAnchor.constraint(equalToConstant: 25.0).isActive = true return spacer } else if let sliderKey = keyCoded as? SliderKey { sliderKey.keyboardView = self return sliderKey.createView() } return createKey(keyCoded) } let stack = UIStackView(arrangedSubviews: subviews) stack.axis = .horizontal stack.distribution = .fill stack.spacing = 8 return stack } } extension UIImage { static func dot(size:CGSize, color:UIColor) -> UIImage { return UIGraphicsImageRenderer(size: size).image { context in context.cgContext.setFillColor(color.cgColor) context.cgContext.fillEllipse(in: CGRect(origin:.zero, size:size)) } } }
gpl-3.0
b2eecbd93dd3103dcce4c9377e8c5984
39.720848
135
0.675547
5.016979
false
false
false
false
justindarc/firefox-ios
AccountTests/FxALoginStateMachineTests.swift
2
13681
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import Account import Foundation import FxA import Shared import XCTest class MockFxALoginClient: FxALoginClient { // Fixed per mock client, for testing. let kA = Data.randomOfLength(UInt(KeyLength))! let wrapkB = Data.randomOfLength(UInt(KeyLength))! func keyPair() -> Deferred<Maybe<KeyPair>> { let keyPair: KeyPair = RSAKeyPair.generate(withModulusSize: 512) return Deferred(value: Maybe(success: keyPair)) } func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAKeysResponse(kA: kA, wrapkB: wrapkB) return Deferred(value: Maybe(success: response)) } func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxASignResponse(certificate: "certificate") return Deferred(value: Maybe(success: response)) } func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = [FxAScopedKeyDataResponse(scope: scope, identifier: scope, keyRotationSecret: "0000000000000000000000000000000000000000000000000000000000000000", keyRotationTimestamp: 1510726317123)] return Deferred(value: Maybe(success: response)) } } // A mock client that fails locally (i.e., cannot connect to the network). class MockFxALoginClientWithoutNetwork: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } } // A mock client that responds to keys and sign with 401 errors. class MockFxALoginClientAfterPasswordChange: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to keys with 400/104 (needs verification responses). class MockFxALoginClientBeforeVerification: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.remote(RemoteError(code: 400, errno: 104, error: "Unverified", message: "Unverified message", info: "Unverified info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 400, errno: 104, error: "Unverified", message: "Unverified message", info: "Unverified info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to sign with 503/999 (unknown server error). class MockFxALoginClientDuringOutage: MockFxALoginClient { override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.remote(RemoteError(code: 503, errno: 999, error: "Unknown", message: "Unknown error", info: "Unknown err info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 503, errno: 999, error: "Unknown", message: "Unknown error", info: "Unknown err info")) return Deferred(value: Maybe(failure: response)) } } class FxALoginStateMachineTests: XCTestCase { let marriedState = FxAStateTests.stateForLabel(FxAStateLabel.married) as! MarriedState override func setUp() { super.setUp() self.continueAfterFailure = false } func withMachine(_ client: FxALoginClient, callback: (FxALoginStateMachine) -> Void) { let stateMachine = FxALoginStateMachine(client: client) callback(stateMachine) } func withMachineAndClient(_ callback: (FxALoginStateMachine, MockFxALoginClient) -> Void) { let client = MockFxALoginClient() withMachine(client) { stateMachine in callback(stateMachine, client) } } func testAdvanceWhenInteractionRequired() { // The simple cases are when we get to Separated and Doghouse. There's nothing to do! // We just have to wait for user interaction. for stateLabel in [FxAStateLabel.separated, FxAStateLabel.doghouse] { let e = expectation(description: "Wait for login state machine.") let state = FxAStateTests.stateForLabel(stateLabel) withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label, stateLabel) e.fulfill() } } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedBeforeVerified() { // Advancing from engaged before verified stays put. let e = self.expectation(description: "Wait for login state machine.") let engagedState = (FxAStateTests.stateForLabel(.engagedBeforeVerified) as! EngagedBeforeVerifiedState) withMachine(MockFxALoginClientBeforeVerification()) { stateMachine in stateMachine.advance(fromState: engagedState, now: engagedState.knownUnverifiedAt).upon { newState in XCTAssertEqual(newState.label.rawValue, engagedState.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedAfterVerified() { // Advancing from an Engaged state correctly XORs the keys. withMachineAndClient { stateMachine, client in // let unwrapkB = Bytes.generateRandomBytes(UInt(KeyLength)) let unwrapkB = client.wrapkB // This way we get all 0s, which is easy to test. let engagedState = (FxAStateTests.stateForLabel(.engagedAfterVerified) as! EngagedAfterVerifiedState).withUnwrapKey(unwrapkB) let e = self.expectation(description: "Wait for login state machine.") stateMachine.advance(fromState: engagedState, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { XCTAssertEqual(newState.kSync.hexEncodedString, "ec830aefab7dc43c66fb56acc16ed3b723f090ae6f50d6e610b55f4675dcbefba1351b80de8cbeff3c368949c34e8f5520ec7f1d4fa24a0970b437684259f946") XCTAssertEqual(newState.kXCS, "66687aadf862bd776c8fc18b8e9f8e20") } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedAfterVerifiedWithoutNetwork() { // Advancing from engaged after verified, but during outage, stays put. withMachine(MockFxALoginClientWithoutNetwork()) { stateMachine in let engagedState = FxAStateTests.stateForLabel(.engagedAfterVerified) let e = self.expectation(description: "Wait for login state machine.") stateMachine.advance(fromState: engagedState, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, engagedState.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromCohabitingAfterVerifiedDuringOutage() { // Advancing from engaged after verified, but during outage, stays put. let e = self.expectation(description: "Wait for login state machine.") let state = (FxAStateTests.stateForLabel(.cohabitingAfterKeyPair) as! CohabitingAfterKeyPairState) withMachine(MockFxALoginClientDuringOutage()) { stateMachine in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, state.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromCohabitingAfterVerifiedWithoutNetwork() { // Advancing from cohabiting after verified, but when the network is not available, stays put. let e = self.expectation(description: "Wait for login state machine.") let state = (FxAStateTests.stateForLabel(.cohabitingAfterKeyPair) as! CohabitingAfterKeyPairState) withMachine(MockFxALoginClientWithoutNetwork()) { stateMachine in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, state.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarried() { // Advancing from a healthy Married state is easy. let e = self.expectation(description: "Wait for login state machine.") withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: 0).upon { newState in XCTAssertEqual(newState.label, FxAStateLabel.married) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedWithExpiredCertificate() { // Advancing from a Married state with an expired certificate gets back to Married. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneWeekInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh certificate. XCTAssertLessThan(self.marriedState.certificateExpiresAt, now) XCTAssertGreaterThan(newState.certificateExpiresAt, now) } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedWithExpiredKeyPair() { // Advancing from a Married state with an expired keypair gets back to Married too. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneMonthInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh key pair (and certificate, but we don't verify that). XCTAssertLessThan(self.marriedState.keyPairExpiresAt, now) XCTAssertGreaterThan(newState.keyPairExpiresAt, now) } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedAfterPasswordChange() { // Advancing from a Married state with a 401 goes to Separated if it needs a new certificate. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneDayInMilliseconds + 1 withMachine(MockFxALoginClientAfterPasswordChange()) { stateMachine in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.separated.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } }
mpl-2.0
b3e51d3f1610b586ac12aecd2c9c1f6b
49.113553
206
0.679117
4.998539
false
true
false
false
thankmelater23/MyFitZ
MyFitZ/CreationUITableViewCell.swift
1
1268
// CreationUITableViewCell.swift // // My_Fitz // // Created by Andre Villanueva on 4/3/15. // Copyright (c) 2015 BangBangStudios. All rights reserved. // import UIKit //MARK: -CreationUITableViewCell Class class CreationUITableViewCell: UITableViewCell{ //MARK: -Outlets @IBOutlet var textInputCellLabel: UILabel! @IBOutlet var textInputCellTextField: UITextField! //MARK: -View Methods @objc func configure(text: String?, labelString: String!, tag: Int){ textInputCellTextField.text = String() textInputCellTextField.placeholder = labelString textInputCellLabel.text = labelString self.textInputCellTextField.tag = tag self.textInputCellTextField.clearButtonMode = UITextFieldViewMode.unlessEditing self.customizeView() } @objc func borderCustomization(){ // self.layer.cornerRadius = self.frame.size.width / 10 self.contentMode = UIViewContentMode.scaleToFill self.clipsToBounds = true self.layer.borderWidth = 2 self.layer.borderColor = Stitching.cgColor } @objc func customizeView(){ self.backgroundColor = FloorTexture self.borderCustomization() } }
mit
89071e98cac9b98dc300079b9cdecce2
25.978723
87
0.667981
4.80303
false
false
false
false
apple/swift-tools-support-core
Sources/TSCBasic/OrderedSet.swift
2
4027
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// An ordered set is an ordered collection of instances of `Element` in which /// uniqueness of the objects is guaranteed. public struct OrderedSet<E: Hashable>: Equatable, Collection { public typealias Element = E public typealias Index = Int #if swift(>=4.1.50) public typealias Indices = Range<Int> #else public typealias Indices = CountableRange<Int> #endif private var array: [Element] private var set: Set<Element> /// Creates an empty ordered set. public init() { self.array = [] self.set = Set() } /// Creates an ordered set with the contents of `array`. /// /// If an element occurs more than once in `element`, only the first one /// will be included. public init(_ array: [Element]) { self.init() for element in array { append(element) } } // MARK: Working with an ordered set /// The number of elements the ordered set stores. public var count: Int { return array.count } /// Returns `true` if the set is empty. public var isEmpty: Bool { return array.isEmpty } /// Returns the contents of the set as an array. public var contents: [Element] { return array } /// Returns `true` if the ordered set contains `member`. public func contains(_ member: Element) -> Bool { return set.contains(member) } /// Adds an element to the ordered set. /// /// If it already contains the element, then the set is unchanged. /// /// - returns: True if the item was inserted. @discardableResult public mutating func append(_ newElement: Element) -> Bool { let inserted = set.insert(newElement).inserted if inserted { array.append(newElement) } return inserted } /// Remove and return the element at the beginning of the ordered set. public mutating func removeFirst() -> Element { let firstElement = array.removeFirst() set.remove(firstElement) return firstElement } /// Remove and return the element at the end of the ordered set. public mutating func removeLast() -> Element { let lastElement = array.removeLast() set.remove(lastElement) return lastElement } /// Remove all elements. public mutating func removeAll(keepingCapacity keepCapacity: Bool) { array.removeAll(keepingCapacity: keepCapacity) set.removeAll(keepingCapacity: keepCapacity) } /// Remove the given element. /// /// - returns: An element equal to member if member is contained in the set; otherwise, nil. @discardableResult public mutating func remove(_ element: Element) -> Element? { let _removedElement = set.remove(element) guard let removedElement = _removedElement else { return nil } let idx = array.firstIndex(of: element)! array.remove(at: idx) return removedElement } } extension OrderedSet: ExpressibleByArrayLiteral { /// Create an instance initialized with `elements`. /// /// If an element occurs more than once in `element`, only the first one /// will be included. public init(arrayLiteral elements: Element...) { self.init(elements) } } extension OrderedSet: RandomAccessCollection { public var startIndex: Int { return contents.startIndex } public var endIndex: Int { return contents.endIndex } public subscript(index: Int) -> Element { return contents[index] } } public func == <T>(lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool { return lhs.contents == rhs.contents } extension OrderedSet: Hashable where Element: Hashable { }
apache-2.0
f04ed1cc9aec3371e805e213c5d52e3b
29.976923
96
0.657065
4.66088
false
false
false
false
frranck/asm2c
Sources/Parser.swift
1
27186
// // Parser.swift // asm2c // import Foundation import Expression // Proc -> 'Proc' Label ProcPrimaryExpression Label 'Endp' // ProcPrimaryExpression = Line | ProcPrimaryExpression Line // // DataLine -> Label DataSymbol DataPrimaryExpression | DataSymbol DataPrimaryExpression // DataPrimaryExpression -> PrimaryExpression | DataPrimaryExpression ',' PrimaryExpression // // // | Number 'dup' '(' Expression ')' // // // DataSymbol -> 'db' | 'dw' | 'dd' // // Expression -> PrimaryExpression Operator Expression | PrimaryExpression // | Operator PrimaryExpression // PrimaryExpression -> Identifier | Number | '(' Expression ')' | Registry | DataString | '[' Expression ']' // // Operator -> '*' | '/' | '+' | '-' | offset // // // simplified version of pointer: // // Pointeur -> Identifier | Identifier Operator OffsetExpression | '[' Pointeur ']' // OffsetExpression -> PrimaryOffsetExpression | PrimaryOffsetExpression Operator OffsetExpression // PrimaryOffsetExpression -> Number | '(' OffsetExpression ')' // // // // Line -> // Instruction1Line | Instruction2Line | JmpInstructionLine | LabelLine | DataLine | Instruction0Line // // Instruction0Line -> 'Ret' // // Instruction1Line -> // <instruction 1> Qualifier? Expression // // Instruction2 -> // Instruction2Token Qualifier? Expression Comma Expression // // Call -> // CallToken Label // // JmpInstruction -> // JumpInstructionToken Label // // Expression -> // PrimaryExpression Operator Expression | PrimaryExpression // // PrimaryExpression -> Identifier | Number | Variable | Register | ( Expression ) | [ Expression] | Offset [ Expression] | Label enum Errors: Error { case WrongExpressionBeforeDup case UnexpectedToken case UnexpectedToken2(Token) case UndefinedOperator(String) case UnexpectedRegister(String) case ExpectedCharacter(Character) case ExpectedExpression case ExpectedToken(Token) case ExpectedKeyword(String) case ExpectedArgumentList case ExpectedFunctionName case ExpectedInstruction case ExpectedRegister case ErrorParsing(String) } class Parser { let defaultSelector: String = "ds" var labelsnoCase = true let tokens: [(Token,Int, String)] var equ = [equNode]() var errorNumber = 0 var index = 0 var dummyIndex = 0 var line = 0 //var currentSizeDirective: SizeDirective = .unknown var currentSelector: String init(tokens: [(Token,Int, String)]) { self.tokens = tokens self.currentSelector = defaultSelector } func peekCurrentToken() -> Token { if index >= tokens.count { return .EOF } return tokens[index].0 } func peekCurrentTokenLineNumber() -> Int? { if index >= tokens.count { return nil } return tokens[index].1 } func currentLineNumber() -> Int { if index >= tokens.count { return 9999999 } return tokens[index].1 } func popCurrentToken() -> Token { if index >= tokens.count { return .EOF } let token = tokens[index] index = index + 1 return token.0 } func parseNumber() throws -> ExprNode { guard case let Token.Number(value) = popCurrentToken() else { throw Errors.UnexpectedToken } return NumberNode(value: value) } func parseRegister() throws -> RegisterNode { switch popCurrentToken() { case Token.Register( let value): return RegisterNode(value: value.lowercased(), size: .dword, isH: false) case Token.Register16(let value): switch value.lowercased() { case "ax": return RegisterNode(value: "eax", size: .word, isH: false) case "bx": return RegisterNode(value: "ebx", size: .word, isH: false) case "cx": return RegisterNode(value: "ecx", size: .word, isH: false) case "dx": return RegisterNode(value: "edx", size: .word, isH: false) case "si": return RegisterNode(value: "esi", size: .word, isH: false) case "di": return RegisterNode(value: "edi", size: .word, isH: false) case "bp": return RegisterNode(value: "ebp", size: .word, isH: false) case "cs": return RegisterNode(value: "cs", size: .word, isH: false) case "ds": return RegisterNode(value: "ds", size: .word, isH: false) case "es": return RegisterNode(value: "es", size: .word, isH: false) case "fs": return RegisterNode(value: "fs", size: .word, isH: false) case "gs": return RegisterNode(value: "gs", size: .word, isH: false) case "ss": return RegisterNode(value: "ss", size: .word, isH: false) default: throw Errors.UnexpectedRegister(value) // return RegisterNode(value: value.lowercased(), size: .word, isH: false) } case Token.Register8h(let value): switch value.lowercased() { case "ah": return RegisterNode(value: "eax", size: .byte, isH: true) case "bh": return RegisterNode(value: "ebx", size: .byte, isH: true) case "ch": return RegisterNode(value: "ecx", size: .byte, isH: true) case "dh": return RegisterNode(value: "edx", size: .byte, isH: true) default: throw Errors.UnexpectedRegister(value) } case Token.Register8l(let value): switch value.lowercased() { case "al": return RegisterNode(value: "eax", size: .byte, isH: false) case "bl": return RegisterNode(value: "ebx", size: .byte, isH: false) case "cl": return RegisterNode(value: "ecx", size: .byte, isH: false) case "dl": return RegisterNode(value: "edx", size: .byte, isH: false) default: throw Errors.UnexpectedRegister(value) } default: throw Errors.UnexpectedToken } } func parseParens() throws -> ExprNode { guard case Token.ParensOpen = popCurrentToken() else { throw Errors.ExpectedCharacter("(") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } guard case Token.ParensClose = popCurrentToken() else { throw Errors.ExpectedCharacter(")") } return ParenthesisNode(node: exp) } func parseBraquet() throws -> ExprNode { guard case Token.BraquetOpen = popCurrentToken() else { throw Errors.ExpectedCharacter("[") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } guard case Token.BraquetClose = popCurrentToken() else { throw Errors.ExpectedCharacter("]") } return BraquetNode(expr: exp) } func parseOffset() throws -> ExprNode { guard case Token.Offset = popCurrentToken() else { throw Errors.ExpectedKeyword("Offset") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } return OffsetNode(expr: exp) } let operatorPrecedence: [String: Int] = [ "+": 20, "-": 20, "*": 40, "/": 40 ] func getCurrentTokenPrecedence() throws -> Int { guard index < tokens.count else { return -1 } /* guard case .Label = peekCurrentToken() else { return 60 } */ guard case let Token.Operator(op) = peekCurrentToken() else { return -1 } guard let precedence = operatorPrecedence[op] else { throw Errors.UndefinedOperator(op) } return precedence } func parseDataString() throws -> [NumberNode] { var nodes = [NumberNode]() guard case let Token.DataString(value) = popCurrentToken() else { throw Errors.UnexpectedToken } let start = value.index(value.startIndex, offsetBy: 1) let end = value.index(value.endIndex, offsetBy: -1) let myRange:Range = start..<end let stringFound = value.substring(with: myRange) for code in String(stringFound).utf8 { nodes.append(NumberNode(value: Int(code))) } ; if (stringFound.count != nodes.count) { print("Warning string \(stringFound) size!=characters.count\n"); let error="Error string <\(stringFound)> size!=characters.count prob a file encoding issue. (Did you converted your 8bit charset to utfxx?) \n"; print(error) throw Errors.ErrorParsing(error) } return nodes; } func parseDupDataContent() throws -> [ExprNode] { var nodes = [ExprNode]() guard case Token.ParensOpen = popCurrentToken() else { throw Errors.ExpectedToken(.ParensOpen) } let currentLine = currentLineNumber() while (index < tokens.count && currentLine == currentLineNumber()) { switch (peekCurrentToken()) { case Token.ParensClose: _ = popCurrentToken() return nodes; case .Comma: _ = popCurrentToken() default: if let node = try parseExpression() { nodes.append(node) } else { print("error parsing dup inside?") } } } return nodes } func evaluateExpr(expr: ExprNode) -> Int { let expression = Expression("\(expr)") guard let result = try? expression.evaluate() else { print("ERROR: evaluateExpr: \(expr)") //TODO fail properly. return -1 } return Int(result) } func parseDup(dupSize: ExprNode) throws -> [ExprNode] { var evaluateDupsize: Int; var nodes = [ExprNode]() let nodesToCopy = try parseDupDataContent() evaluateDupsize = evaluateExpr(expr: dupSize) for _ in 1...evaluateDupsize { _ = nodesToCopy.map { nodes.append( $0 ) } } return nodes; } func parseExpression() throws -> ExprNode? { switch peekCurrentToken() { case .Operator(_): guard case let Token.Operator(op) = popCurrentToken() else { throw Errors.UnexpectedToken } switch (peekCurrentToken()) { case .Number: return try parseBinaryOp(node: ParenthesisNode (node: BinaryOpNode(op: op, lhs: NumberNode(value: 0), rhs: try parseNumber()))) default: break; } default: break } guard let node = try parsePrimary() else { return nil } return try parseBinaryOp(node: node) } func parsePrimary() throws -> ExprNode? { switch (peekCurrentToken()) { case .Register: return try parseRegister() case .Register16: let node = try parseRegister() guard case .DotDot = peekCurrentToken() else { // to skip cs: es: ds: return node } self.currentSelector = node.value; _ = popCurrentToken() return try parsePrimary() case .Register8h: return try parseRegister() case .Register8l: return try parseRegister() case .Label: return try parseLabel() case .Number: return try parseNumber() case .ParensOpen: return try parseParens() case .BraquetOpen: return try parseBraquet() case .Offset: return try parseOffset() case .DataString: var numberValueSmall = 0 var numberValueBig = 0 let dataString = try parseDataString() var multi = 1 _ = dataString.reversed().map { value -> (NumberNode) in numberValueSmall = numberValueSmall + value.value * multi; multi = multi * 256; return value } multi = 1 _ = dataString.map { value -> (NumberNode) in numberValueBig = numberValueBig + value.value * multi; multi = multi * 256; return value } return quoteNumberNode(valueSmall: numberValueSmall, valueBig: numberValueBig) default: return nil } } func parseBinaryOp(node: ExprNode, exprPrecedence: Int = 0) throws -> ExprNode { var lhs = node while true { let tokenPrecedence = try getCurrentTokenPrecedence() if tokenPrecedence < exprPrecedence { return lhs } guard case let Token.Operator(op) = popCurrentToken() else { throw Errors.UnexpectedToken } guard var rhs = try parsePrimary() else { throw Errors.UnexpectedToken } let nextPrecedence = try getCurrentTokenPrecedence() if tokenPrecedence < nextPrecedence { rhs = try parseBinaryOp(node: rhs, exprPrecedence: tokenPrecedence+1) } lhs = BinaryOpNode(op: op, lhs: lhs, rhs: rhs) } } func parseLabel() throws -> LabelNode { guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if labelsnoCase { return LabelNode(name: name.lowercased()) } else { return LabelNode(name: name) } } func parseDataLine(label: String) throws -> DataPrimaryNode { if case let Token.DataSymbol(symbole) = peekCurrentToken() { _ = popCurrentToken() return try parseDataPrimaryExpression(label: label, dataSymbol: symbole) } throw Errors.UnexpectedToken2(peekCurrentToken()) } func parseDataPrimaryExpression(label: String, dataSymbol: String) throws -> DataPrimaryNode { var nodes = [ExprNode]() // print("xxx line:\(label)") let currentLine = currentLineNumber() while (index < tokens.count && currentLine == currentLineNumber()) { // print("parseDataPrimaryExpression found:\(peekCurrentToken())") switch (peekCurrentToken()) { case .DataString: _ = try parseDataString().map { nodes.append($0) } case .Comma: _ = popCurrentToken() case .Dup: _ = popCurrentToken() if let node = nodes.last { nodes.removeLast() _ = try parseDup(dupSize: node).map { nodes.append($0) } } else { throw Errors.WrongExpressionBeforeDup } case .DataSymbol: return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) /* case .Label: print(".Label") return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) */ default: if let node = try parseExpression() { nodes.append(node) } else { // print("parseDataPrimaryExpression not processing \(peekCurrentToken()) as data") return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) } } } return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) } func parseCall() throws -> CallNode { guard case Token.Call = popCurrentToken() else { throw Errors.UnexpectedToken } guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } return CallNode(label: name) } func parseJumpInstruction() throws -> JumpInstruction { guard case let Token.JumpInstruction(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } return JumpInstruction(instruction: instruction, label: name) } func getCurrentSizeDirective() -> SizeDirective { guard case let .Qualifier(name) = peekCurrentToken() else { return .unknown } if let sizeDirective = SizeDirective(rawValue: name.lowercased()) { _ = popCurrentToken() return sizeDirective } else { print("weird sizeDirective: \(name)") return .unknown } } func parseInstruction0() throws -> Instruction0Node { guard case let .Instruction0(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } if (instruction.uppercased()=="REP") { guard case let .Instruction0(instructionRep) = popCurrentToken() else { throw Errors.ExpectedInstruction } return Instruction0Node(instruction: "REP_\(instructionRep)") } return Instruction0Node(instruction: instruction) } func parseInstruction1() throws -> Instruction1Node { guard case let Token.Instruction1(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } var currentSizeDirective = getCurrentSizeDirective() guard let expr = try parseExpression() else { throw Errors.UnexpectedToken } if currentSizeDirective == .unknown { let currentSizeDirectiveFromExpr: SizeDirective = try getCurrentSizeFrom(expr: expr) currentSizeDirective = currentSizeDirectiveFromExpr } return Instruction1Node(instruction: instruction.uppercased(), sizeDirective: currentSizeDirective, selector: currentSelector, operand: expr) } func isInstructionWithDifferentSizeForSourceAndDestination(instruction : String) -> Bool { if instruction.uppercased() == "MOVSX" { return true } if instruction.uppercased() == "MOVZX" { return true } return false } func parseInstruction2() throws -> Instruction2Node { guard case let Token.Instruction2(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } var currentSizeDirectiveDest = getCurrentSizeDirective() var currentSizeDirectiveSource: SizeDirective = .unknown guard let lhs = try parseExpression() else { throw Errors.ExpectedExpression } if currentSizeDirectiveDest == .unknown { let currentSizeDirectiveFromExpr: SizeDirective = try getCurrentSizeFrom(expr: lhs) currentSizeDirectiveDest = currentSizeDirectiveFromExpr } guard case Token.Comma = popCurrentToken() else { throw Errors.UnexpectedToken } currentSizeDirectiveSource = getCurrentSizeDirective() if currentSizeDirectiveDest == .unknown { currentSizeDirectiveDest=currentSizeDirectiveSource } guard var rhs = try parseExpression() else { throw Errors.ExpectedExpression } if instruction.uppercased() == "LEA" { rhs = OffsetNode(expr: rhs) } if let rhs = rhs as? RegisterNode { currentSizeDirectiveSource = rhs.size } if (currentSizeDirectiveSource == .unknown) { currentSizeDirectiveSource = currentSizeDirectiveDest } if (currentSizeDirectiveDest == .unknown) { currentSizeDirectiveDest = currentSizeDirectiveSource } if (isInstructionWithDifferentSizeForSourceAndDestination(instruction: instruction) == true) { if (currentSizeDirectiveDest == currentSizeDirectiveSource) { print("Warning:\(instruction) dest and source size marked as egals, please fix your asm code with a byte ptr or word ptr thing???\n") // TOFIX: Test on DOSBOX if should fail } } return Instruction2Node(instruction: instruction.uppercased(), sizeDirectiveSource: currentSizeDirectiveSource, sizeDirectiveDest: currentSizeDirectiveDest, selector: currentSelector, lhs: lhs, rhs: rhs) } func parseLine() throws -> Any { self.currentSelector = defaultSelector switch peekCurrentToken() { case .Instruction0: return try parseInstruction0() case .Instruction1: return try parseInstruction1() case .Instruction2: return try parseInstruction2() case .JumpInstruction: return try parseJumpInstruction() case .Label: return try parseLabelLine() case .DataSymbol: dummyIndex = dummyIndex + 1 return try parseDataLine(label: "dummy\(dummyIndex)") case .Ret: _ = popCurrentToken() return whateverNode(name: "RET;") case .Call: return try parseCall() default: throw Errors.UnexpectedToken2(peekCurrentToken()) } } // first: main nodes, second: procedures nodes func parseEqu(variableName: String) throws -> ExprNode { if case Token.Equ = peekCurrentToken() { _ = popCurrentToken() guard let equValue = try parseExpression() else { throw Errors.ExpectedExpression } var variableName2 = variableName if labelsnoCase { variableName2 = variableName2.lowercased() } equNameList.append(variableName2) return equNode(name: variableName2, expr: equValue) } throw Errors.UnexpectedToken2(peekCurrentToken()) } func parseLabelLine() throws -> ExprNode { guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if case .DotDot = peekCurrentToken() { _ = popCurrentToken() if labelsnoCase { return GotoLabelNode(name: name.lowercased()) } else { return GotoLabelNode(name: name) } } if case .DataSymbol = peekCurrentToken() { let node = try parseDataLine(label: name) return node } if case .Equ = peekCurrentToken() { return try parseEqu(variableName: name) } if case .Proc = peekCurrentToken() { _ = popCurrentToken() return try parseProcedure(name: name) } throw Errors.UnexpectedToken } func printLine(number lineNumber: Int) { let lineTokens = tokens.filter { $0.1 == lineNumber }.map { $0.0 } let lineString = tokens.filter { $0.1 == lineNumber }.map { $0.2 }.first print("line: <\(lineString)>") print("tokens: <\(lineTokens)>") } func gotoLineAfter(line: Int) { var currentLine = peekCurrentTokenLineNumber() while (currentLine != nil) { if (currentLine! > line) { return } _ = popCurrentToken() currentLine = peekCurrentTokenLineNumber() } } func parseData() -> [DataPrimaryNode] { var data = [DataPrimaryNode]() index = 0 while index < tokens.count { let lineNumber = currentLineNumber() do { switch peekCurrentToken() { case .DataSymbol: dummyIndex = dummyIndex + 1 if let node = try? parseDataLine(label: "dummy\(dummyIndex)") { data.append(node) } case .Label: guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if case .DataSymbol = peekCurrentToken() { var labelName = name if labelsnoCase { labelName = labelName.lowercased() } if let node = try? parseDataLine(label: labelName) { data.append(node) // dataPrimaryNodesMap[node.name] = node } } default: gotoLineAfter(line: lineNumber) break } } catch { gotoLineAfter(line: lineNumber) } } index = 0 return data } func parseProcedure(name: String) throws -> ProcedureNode { var nodes = [Any]() while index < tokens.count { let lineNumber = currentLineNumber() do { //print("parseProcedure parsing <\(peekCurrentToken())>") if case .Endp = peekCurrentToken() { _ = popCurrentToken() break; } let node = try parseLine() if let node = node as? equNode { equ.append(node) } //print("parseProcedure: \(name) adding: \(node)") nodes.append(node) } catch { print("error parsing proc line: \(lineNumber)\n") printLine(number:lineNumber) let lineNumber = currentLineNumber() errorNumber = errorNumber + 1 gotoLineAfter(line: lineNumber) } } //print("parseProcedure: \(name) return: \(nodes)") return ProcedureNode(name: name, nodes:nodes); } func parse() throws -> ([Any],[equNode],Int) { var main = [Any]() index = 0 equ = [] while index < tokens.count { let lineNumber = currentLineNumber() do { let node = try parseLine() if let node = node as? equNode { equ.append(node) } else { main.append(node) } } catch { print("error \(error) parsing line: \(lineNumber)\n") printLine(number:lineNumber) let lineNumber = currentLineNumber() errorNumber = errorNumber + 1 gotoLineAfter(line: lineNumber) } } //main.append(whateverNode(name: "firstRun = 2;goto moveToBackGround;")) return (main,equ,errorNumber) } }
mit
3c2b499f39f0be78524037566f30894e
32.729529
211
0.557971
4.843399
false
false
false
false
onevcat/CotEditor
Tests/StringLineProcessingTests.swift
2
7547
// // StringLineProcessingTests.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2020-03-16. // // --------------------------------------------------------------------------- // // © 2020-2022 1024jp // // 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 // // https://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 CotEditor final class StringLineProcessingTests: XCTestCase { func testMoveLineUp() { let string = """ aa bbbb ccc d eee """ var info: String.EditingInfo? info = string.moveLineUp(in: [NSRange(4, 1)]) XCTAssertEqual(info?.strings, ["bbbb\naa\n"]) XCTAssertEqual(info?.ranges, [NSRange(0, 8)]) XCTAssertEqual(info?.selectedRanges, [NSRange(1, 1)]) info = string.moveLineUp(in: [NSRange(4, 1), NSRange(6, 0)]) XCTAssertEqual(info?.strings, ["bbbb\naa\n"]) XCTAssertEqual(info?.ranges, [NSRange(0, 8)]) XCTAssertEqual(info?.selectedRanges, [NSRange(1, 1), NSRange(3, 0)]) info = string.moveLineUp(in: [NSRange(4, 1), NSRange(9, 0), NSRange(15, 1)]) XCTAssertEqual(info?.strings, ["bbbb\nccc\naa\neee\nd"]) XCTAssertEqual(info?.ranges, [NSRange(0, 17)]) XCTAssertEqual(info?.selectedRanges, [NSRange(1, 1), NSRange(6, 0), NSRange(13, 1)]) info = string.moveLineUp(in: [NSRange(2, 1)]) XCTAssertNil(info) } func testMoveLineDown() { let string = """ aa bbbb ccc d eee """ var info: String.EditingInfo? info = string.moveLineDown(in: [NSRange(4, 1)]) XCTAssertEqual(info?.strings, ["aa\nccc\nbbbb\n"]) XCTAssertEqual(info?.ranges, [NSRange(0, 12)]) XCTAssertEqual(info?.selectedRanges, [NSRange(8, 1)]) info = string.moveLineDown(in: [NSRange(4, 1), NSRange(6, 0)]) XCTAssertEqual(info?.strings, ["aa\nccc\nbbbb\n"]) XCTAssertEqual(info?.ranges, [NSRange(0, 12)]) XCTAssertEqual(info?.selectedRanges, [NSRange(8, 1), NSRange(10, 0)]) info = string.moveLineDown(in: [NSRange(4, 1), NSRange(9, 0), NSRange(13, 1)]) XCTAssertEqual(info?.strings, ["aa\neee\nbbbb\nccc\nd"]) XCTAssertEqual(info?.ranges, [NSRange(0, 17)]) XCTAssertEqual(info?.selectedRanges, [NSRange(8, 1), NSRange(13, 0), NSRange(17, 1)]) info = string.moveLineDown(in: [NSRange(14, 1)]) XCTAssertNil(info) } func testSortLinesAscending() { let string = """ ccc aa bbbb """ var info: String.EditingInfo? info = string.sortLinesAscending(in: NSRange(4, 1)) XCTAssertNil(info) info = string.sortLinesAscending(in: string.nsRange) XCTAssertEqual(info?.strings, ["aa\nbbbb\nccc"]) XCTAssertEqual(info?.ranges, [NSRange(0, 11)]) XCTAssertEqual(info?.selectedRanges, [NSRange(0, 11)]) info = string.sortLinesAscending(in: NSRange(2, 4)) XCTAssertEqual(info?.strings, ["aa\nccc"]) XCTAssertEqual(info?.ranges, [NSRange(0, 6)]) XCTAssertEqual(info?.selectedRanges, [NSRange(0, 6)]) } func testReverseLines() { let string = """ aa bbbb ccc """ var info: String.EditingInfo? info = string.reverseLines(in: NSRange(4, 1)) XCTAssertNil(info) info = string.reverseLines(in: string.nsRange) XCTAssertEqual(info?.strings, ["ccc\nbbbb\naa"]) XCTAssertEqual(info?.ranges, [NSRange(0, 11)]) XCTAssertEqual(info?.selectedRanges, [NSRange(0, 11)]) info = string.reverseLines(in: NSRange(2, 4)) XCTAssertEqual(info?.strings, ["bbbb\naa"]) XCTAssertEqual(info?.ranges, [NSRange(0, 7)]) XCTAssertEqual(info?.selectedRanges, [NSRange(0, 7)]) } func testDeleteDuplicateLine() { let string = """ aa bbbb ccc ccc bbbb """ var info: String.EditingInfo? info = string.deleteDuplicateLine(in: [NSRange(4, 1)]) XCTAssertNil(info) info = string.deleteDuplicateLine(in: [string.nsRange]) XCTAssertEqual(info?.strings, ["", ""]) XCTAssertEqual(info?.ranges, [NSRange(12, 4), NSRange(16, 4)]) XCTAssertNil(info?.selectedRanges) info = string.deleteDuplicateLine(in: [NSRange(10, 4)]) XCTAssertEqual(info?.strings, [""]) XCTAssertEqual(info?.ranges, [NSRange(12, 4)]) XCTAssertNil(info?.selectedRanges) info = string.deleteDuplicateLine(in: [NSRange(9, 1), NSRange(11, 0), NSRange(13, 2)]) XCTAssertEqual(info?.strings, [""]) XCTAssertEqual(info?.ranges, [NSRange(12, 4)]) XCTAssertNil(info?.selectedRanges) } func testDuplicateLine() { let string = """ aa bbbb ccc """ var info: String.EditingInfo? info = string.duplicateLine(in: [NSRange(4, 1)], lineEnding: "\n") XCTAssertEqual(info?.strings, ["bbbb\n"]) XCTAssertEqual(info?.ranges, [NSRange(3, 0)]) XCTAssertEqual(info?.selectedRanges, [NSRange(9, 1)]) info = string.duplicateLine(in: [NSRange(4, 1), NSRange(6, 4)], lineEnding: "\n") XCTAssertEqual(info?.strings, ["bbbb\nccc\n"]) XCTAssertEqual(info?.ranges, [NSRange(3, 0)]) XCTAssertEqual(info?.selectedRanges, [NSRange(13, 1), NSRange(15, 4)]) info = string.duplicateLine(in: [NSRange(4, 1), NSRange(6, 1), NSRange(10, 0)], lineEnding: "\n") XCTAssertEqual(info?.strings, ["bbbb\n", "ccc\n"]) XCTAssertEqual(info?.ranges, [NSRange(3, 0), NSRange(8, 0)]) XCTAssertEqual(info?.selectedRanges, [NSRange(9, 1), NSRange(11, 1), NSRange(19, 0)]) } func testDeleteLine() { let string = """ aa bbbb ccc """ var info: String.EditingInfo? info = string.deleteLine(in: [NSRange(4, 1)]) XCTAssertEqual(info?.strings, [""]) XCTAssertEqual(info?.ranges, [NSRange(3, 5)]) XCTAssertEqual(info?.selectedRanges, [NSRange(3, 0)]) info = string.deleteLine(in: [NSRange(4, 1), NSRange(6, 1), NSRange(10, 0)]) XCTAssertEqual(info?.strings, ["", ""]) XCTAssertEqual(info?.ranges, [NSRange(3, 5), NSRange(8, 3)]) XCTAssertEqual(info?.selectedRanges, [NSRange(3, 0)]) } } // MARK: - private extension NSRange { init(_ location: Int, _ length: Int) { self.init(location: location, length: length) } }
apache-2.0
0bcb8fd9fa32f8c5b8dd0f23398b9a24
31.666667
105
0.555659
4.143877
false
true
false
false
sivaganeshsg/Virtual-Tourist-iOS-App
VirtualTorist/AppDelegate.swift
1
6231
// // AppDelegate.swift // VirtualTorist // // Created by Siva Ganesh on 27/11/15. // Copyright © 2015 Siva Ganesh. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. // self.saveContext() CoreDataStackManager.sharedInstance().saveContext() } /* // Moved to "CoreDataStackManager.swift" file // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.sivaganesh.VirtualTorist" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("VirtualTorist", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } */ }
apache-2.0
817f6932697309d954ec4db0176d8e85
52.247863
291
0.719262
5.82243
false
false
false
false
blinksh/blink
SSHTests/SFTPTests.swift
1
11057
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2021 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import XCTest import BlinkFiles import Combine import Dispatch @testable import SSH extension SSHClientConfig { static let testConfig = SSHClientConfig( user: Credentials.none.user, port: Credentials.port, authMethods: [], loggingVerbosity: .debug ) } extension SSHClient { static func dialWithTestConfig() -> AnyPublisher<SSHClient, Error> { dial(Credentials.none.host, with: .testConfig) } } class SFTPTests: XCTestCase { var cancellableBag: [AnyCancellable] = [] override class func setUp() { SSHInit() } func testRequest() throws { let list = SSHClient .dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap() { try SFTPTranslator(on: $0) } .flatMap() { t -> AnyPublisher<[[FileAttributeKey : Any]], Error> in t.walkTo("~") .flatMap { $0.directoryFilesAndAttributes() } .eraseToAnyPublisher() } .assertNoFailure() .exactOneOutput(test: self) dump(list) XCTAssertNotNil(list) XCTAssertFalse(list!.isEmpty) } func testRead() throws { let expectation = self.expectation(description: "Buffer Written") //var connection: SSHClient? //var sftp: SFTPClient? let cancellable = SSHClient.dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap { try SFTPTranslator(on: $0) } .flatMap { $0.walkTo("linux.tar.xz") } .flatMap { $0.open(flags: O_RDONLY) } .flatMap { $0.read(max: SSIZE_MAX) } .reduce(0, { $0 + $1.count } ) .assertNoFailure() .sink { count in XCTAssertTrue(count == 109078664, "Wrote \(count)") expectation.fulfill() } waitForExpectations(timeout: 15, handler: nil) } func testWriteTo() throws { let expectation = self.expectation(description: "Buffer Written") //var connection: SSHClient? //var sftp: SFTPClient? let buffer = MemoryBuffer(fast: true) var totalWritten = 0 let cancellable = SSHClient.dialWithTestConfig() .flatMap { $0.requestSFTP() } .tryMap { try SFTPTranslator(on: $0) } .flatMap { $0.walkTo("linux.tar.xz") } .flatMap { $0.open(flags: O_RDONLY) }.flatMap() { f -> AnyPublisher<Int, Error> in let file = f as! SFTPFile return file.writeTo(buffer) }.assertNoFailure() .sink(receiveCompletion: { completion in switch completion { case .finished: expectation.fulfill() case .failure(let error): // Problem here is we can have both SFTP and SSHError XCTFail("Crash") } }, receiveValue: { written in totalWritten += written }) waitForExpectations(timeout: 15, handler: nil) XCTAssertTrue(totalWritten == 109078664, "Wrote \(totalWritten)") print("TOTAL \(totalWritten)") } func testWrite() throws { let expectation = self.expectation(description: "Buffer Written") //var connection: SSHClient? //var sftp: SFTPClient? var totalWritten = 0 let gen = RandomInputGenerator(fast: true) let cancellable = SSHClient.dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap() { try SFTPTranslator(on: $0) } .flatMap() { $0.walkTo("/tmp") } .flatMap() { $0.create(name: "newfile", flags: O_WRONLY, mode: S_IRWXU) } .flatMap() { file in return gen.read(max: 5 * 1024 * 1024) .flatMap() { data in return file.write(data, max: data.count) } }.sink(receiveCompletion: { completion in switch completion { case .finished: expectation.fulfill() case .failure(let error): // Problem here is we can have both SFTP and SSHError if let err = error as? SSH.FileError { XCTFail(err.description) } else { XCTFail("Crash") } } }, receiveValue: { written in totalWritten += written }) waitForExpectations(timeout: 15, handler: nil) XCTAssert(totalWritten == 5 * 1024 * 1024, "Did not write all data") } func testWriteToWriter() throws { let expectation = self.expectation(description: "Buffer Written") // var connection: SSHClient? var translator: SFTPTranslator? let buffer = MemoryBuffer(fast: true) var totalWritten = 0 let cancellable = SSHClient.dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap() { try SFTPTranslator(on: $0) } .flatMap() { t -> AnyPublisher<File, Error> in translator = t // TODO Create a random file first, or use one from a previous test. return t.walkTo("linux.tar.xz") .flatMap { $0.open(flags: O_RDONLY) }.eraseToAnyPublisher() }.flatMap() { f -> AnyPublisher<Int, Error> in let file = f as! SFTPFile return translator!.walkTo("/tmp/") .flatMap { $0.create(name: "linux.tar.xz", flags: O_WRONLY, mode: S_IRWXU) } .flatMap() { file.writeTo($0) }.eraseToAnyPublisher() }.sink(receiveCompletion: { completion in switch completion { case .finished: expectation.fulfill() case .failure(let error): // Problem here is we can have both SFTP and SSHError XCTFail("Crash") } }, receiveValue: { written in totalWritten += written }) waitForExpectations(timeout: 15, handler: nil) XCTAssertTrue(totalWritten == 109078664, "Wrote \(totalWritten)") print("TOTAL \(totalWritten)") // TODO Cleanup } // Z Makes sure we run this one last func testZRemove() throws { let expectation = self.expectation(description: "Removed") // var connection: SSHClient? // var sftp: SFTPClient? let buffer = MemoryBuffer(fast: true) var totalWritten = 0 let cancellable = SSHClient.dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap() { try SFTPTranslator(on: $0) } .flatMap() { $0.walkTo("/tmp/linux.tar.xz") } .flatMap() { $0.remove() } .sink(receiveCompletion: { completion in switch completion { case .finished: print("done") case .failure(let error as SSH.FileError): XCTFail(error.description) case .failure(let error): XCTFail("\(error)") } }, receiveValue: { result in XCTAssertTrue(result) expectation.fulfill() }) waitForExpectations(timeout: 5, handler: nil) } // func testMkdir() throws { // let config = SSHClientConfig(user: "carlos", authMethods: [AuthPassword(with: "")]) // let expectation = self.expectation(description: "Removed") // var connection: SSHClient? // var sftp: SFTPClient? // let buffer = MemoryBuffer(fast: true) // var totalWritten = 0 // let cancellable = SSHClient.dial("localhost", with: config) // .flatMap() { conn -> AnyPublisher<SFTPClient, Error> in // print("Received connection") // connection = conn // return conn.requestSFTP() // }.flatMap() { client -> AnyPublisher<SFTPClient, Error> in // return client.walkTo("/tmp/tmpfile") // }.flatMap() { file in // return file.remove() // } // .sink(receiveCompletion: { completion in // switch completion { // case .finished: // print("done") // case .failure(let error): // XCTFail(dump(error)) // } // }, receiveValue: { result in // XCTAssertTrue(result) // expectation.fulfill() // }) // waitForExpectations(timeout: 5, handler: nil) // connection?.close() // } // } func testCopyAsASource() { continueAfterFailure = false // var connection: SSHClient? // var sftp: SFTPClient? let local = Local() try? FileManager.default.removeItem(atPath: "/tmp/test/copy_test") try? FileManager.default.createDirectory(atPath: "/tmp/test", withIntermediateDirectories: true, attributes: nil) let copied = self.expectation(description: "Copied structure") SSHClient.dialWithTestConfig() .flatMap() { $0.requestSFTP() } .tryMap() { try SFTPTranslator(on: $0) } .flatMap() { $0.walkTo("copy_test") } .flatMap() { f -> CopyProgressInfoPublisher in return local.walkTo("/tmp/test").flatMap { $0.copy(from: [f]) }.eraseToAnyPublisher() }.sink(receiveCompletion: { completion in switch completion { case .finished: print("done") copied.fulfill() case .failure(let error): XCTFail("\(error)") } }, receiveValue: { result in dump(result) }).store(in: &cancellableBag) wait(for: [copied], timeout: 30) } func testCopyAsDest() { let local = Local() let connection = SSHClient .dialWithTestConfig() .exactOneOutput(test: self) connection? .requestExec(command: "rm -rf ~/test") .sink(test: self) let translator = connection? .requestSFTP() .tryMap { try SFTPTranslator(on: $0) } .exactOneOutput(test: self) var completion: Any? = nil translator? .walkTo("/home/no-password") .flatMap() { f -> CopyProgressInfoPublisher in local.walkTo("/tmp/test").flatMap { f.copy(from: [$0]) }.eraseToAnyPublisher() }.sink( test: self, receiveCompletion: { completion = $0 } ) assertCompletionFinished(completion) } // Write and read a stat // func testStat() throws { // // } }
gpl-3.0
8d86b13b5bbcd36ceb9a32fd45753766
30.681948
117
0.592566
4.196205
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureDashboard/Sources/FeatureDashboardUI/WalletActionScreen/Custody/Withdrawal/CustodyWithdrawalStateService.swift
1
5578
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import PlatformUIKit import RxCocoa import RxRelay import RxSwift import ToolKit enum WithdrawalError: LocalizedError { private typealias LocalizationFailureIDs = LocalizationConstants.SimpleBuy.Withdrawal.SummaryFailure case unknown case withdrawalLocked var localizedTitle: String { switch self { case .unknown: return LocalizationFailureIDs.Unknown.title case .withdrawalLocked: return LocalizationFailureIDs.WithdrawLocked.title } } var localizedDescription: String { switch self { case .unknown: return LocalizationFailureIDs.Unknown.description case .withdrawalLocked: return LocalizationFailureIDs.WithdrawLocked.description } } } /// The status of the withdrawal after submission enum CustodyWithdrawalStatus: Equatable { /// Default state case unknown /// The withdrawal was successful case successful /// The withdrawal failed case failed(WithdrawalError) } protocol CustodyWithdrawalStateReceiverServiceAPI: AnyObject { /// The action that should be executed, the `next` action /// is coupled with the current state var action: Observable<CustodyWithdrawalStateService.Action> { get } } protocol CustodyWithdrawalStateEmitterServiceAPI: AnyObject { /// A relay for submitting the withdrawal status after submittal. /// This allows the `nextRelay` to be free of nested types and /// forwarding of withdrawal submission status to the summary screen. var completionRelay: BehaviorRelay<CustodyWithdrawalStatus> { get } /// Move to the next state var nextRelay: PublishRelay<Void> { get } /// Move to the previous state var previousRelay: PublishRelay<Void> { get } } typealias CustodyWithdrawalStateServiceAPI = CustodyWithdrawalStateReceiverServiceAPI & CustodyWithdrawalStateEmitterServiceAPI final class CustodyWithdrawalStateService: CustodyWithdrawalStateServiceAPI { // MARK: - Types struct States { /// The actual state of the flow let current: State /// The previous states sorted chronologically let previous: [State] /// The starting state static var start: States { States(current: .start, previous: []) } /// Maps the instance of `States` into a new instance where the appended /// state is the current func states(byAppending state: State) -> States { States( current: state, previous: previous + [current] ) } /// Maps the instance of `States` into a new instance where the last /// state is trimmed off. func statesByRemovingLast() -> States { States( current: previous.last ?? .end, previous: previous.dropLast() ) } } // MARK: - Types enum State { /// The start of the custody-send flow case start /// Custody withdrawal screen case withdrawal /// ~Fin~ case end } enum Action { case next(State) case previous case dismiss } // MARK: - Properties var states: Observable<States> { statesRelay.asObservable() } var currentState: Observable<CustodyWithdrawalStateService.State> { states.map(\.current) } var action: Observable<Action> { actionRelay .observe(on: MainScheduler.instance) } let nextRelay = PublishRelay<Void>() let previousRelay = PublishRelay<Void>() let completionRelay = BehaviorRelay<CustodyWithdrawalStatus>(value: .unknown) private let statesRelay = BehaviorRelay<States>(value: .start) private let actionRelay = PublishRelay<Action>() private let disposeBag = DisposeBag() // MARK: - Setup init() { completionRelay .observe(on: MainScheduler.instance) .filter { $0 != .unknown } .bindAndCatch(weak: self) { (self) in self.next() } .disposed(by: disposeBag) nextRelay .observe(on: MainScheduler.instance) .bindAndCatch(weak: self) { (self) in self.next() } .disposed(by: disposeBag) previousRelay .observe(on: MainScheduler.instance) .bindAndCatch(weak: self) { (self) in self.previous() } .disposed(by: disposeBag) } private func next() { let action: Action var state: State let states = statesRelay.value switch states.current { case .start: state = .withdrawal action = .next(state) case .withdrawal: state = .end action = .dismiss case .end: state = .end action = .dismiss } let nextStates = states.states(byAppending: state) apply(action: action, states: nextStates) } private func previous() { let states = statesRelay.value.statesByRemovingLast() let action: Action switch states.current { case .end, .start: action = .dismiss default: action = .previous } apply(action: action, states: states) } private func apply(action: Action, states: States) { actionRelay.accept(action) statesRelay.accept(states) } }
lgpl-3.0
53472a9520bc1f9d3f3eb1f6d68e0c9b
26.072816
104
0.622736
4.935398
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/ViewModel/Home/HomeCellViewModel.swift
1
1463
// // HomeCellViewModel.swift // MyApp // // Created by asiantech on 8/9/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import MVVM import RealmSwift import RealmS final class HomeCellViewModel: MVVM.ViewModel { // MARK: - Properties var id = 0 var name = "" var price = 0.0 var thumbnail: String? var isLiked = false // MARK: - Init init (item: Item?) { guard let item = item else { return } id = item.id name = item.name price = item.price thumbnail = item.thumbnail isLiked = item.isLiked } // MARK: - Public func tappedLikeButton() { let realm = RealmS() if let item = realm.object(ofType: Item.self, forPrimaryKey: id) { realm.write { item.isLiked = !item.isLiked } } } func addItemToCart() { let realm = RealmS() if let cartItem = realm.object(ofType: CartItem.self, forPrimaryKey: id) { realm.write { cartItem.quantity += 1 } } else { realm.write { let item = CartItem() item.id = id item.name = name item.price = price if let thumbnail = thumbnail { item.thumbnailImage = thumbnail } realm.add(item) } } } }
mit
df1e535e30872c3c83f81ee02aa092ff
22.580645
82
0.508892
4.443769
false
false
false
false
VirgilSecurity/virgil-sdk-pfs-x
Source/Client/Client+CreatingCards.swift
1
4883
// // Client+CreatingCards.swift // VirgilSDKPFS // // Created by Oleksandr Deundiak on 6/19/17. // Copyright © 2017 VirgilSecurity. All rights reserved. // import Foundation import VirgilSDK extension Client { @objc func bootstrapCardsSet(forUserWithCardId cardId: String, longTermCardRequest: CreateEphemeralCardRequest, oneTimeCardsRequests: [CreateEphemeralCardRequest], completion: @escaping ((VSSCard?, [VSSCard]?, Error?)->())) { let context = VSSHTTPRequestContext(serviceUrl: self.serviceConfig.ephemeralServiceURL) let request = BootstrapCardsRequest(ltc: longTermCardRequest.serialize(), otc: oneTimeCardsRequests.map({ $0.serialize() })) let httpRequest = BootstrapCardsHTTPRequest(context: context, recipientId: cardId, request: request) let handler = { (request: VSSHTTPRequest) in guard request.error == nil else { completion(nil, nil, request.error!) return } let request = request as! BootstrapCardsHTTPRequest guard let response = request.bootstrapCardsResponse else { completion(nil, nil, nil) return } do { let otc = try response.otc.map( { dict -> VSSCard in guard let card = VSSCard(dict: dict) else { throw SecureChat.makeError(withCode: .deserializingVirgilCard, description: "Error deserializing virgil card.") } return card }) guard let ltc = VSSCard(dict: response.ltc) else { throw SecureChat.makeError(withCode: .deserializingVirgilCard, description: "Error deserializing virgil card.") } completion(ltc, otc, nil) return } catch { completion(nil, nil, error) return } } httpRequest.completionHandler = handler self.send(httpRequest) } @objc func createLongTermCard(forUserWithCardId cardId: String, longTermCardRequest: CreateEphemeralCardRequest, completion: @escaping ((VSSCard?, Error?)->())) { let context = VSSHTTPRequestContext(serviceUrl: self.serviceConfig.ephemeralServiceURL) let httpRequest = CreateLtcHTTPRequest(context: context, recipientId: cardId, ltc: longTermCardRequest.serialize()) let handler = { (request: VSSHTTPRequest) in guard request.error == nil else { completion(nil, request.error!) return } let request = request as! CreateLtcHTTPRequest guard let response = request.createLtcResponse else { completion(nil, nil) return } guard let ltc = VSSCard(dict: response.ltc) else { completion(nil, SecureChat.makeError(withCode: .deserializingVirgilCard, description: "Error deserializing virgil card.")) return } completion(ltc, nil) return } httpRequest.completionHandler = handler self.send(httpRequest) } @objc func createOneTimeCards(forUserWithCardId cardId: String, oneTimeCardsRequests: [CreateEphemeralCardRequest], completion: @escaping (([VSSCard]?, Error?)->())) { let context = VSSHTTPRequestContext(serviceUrl: self.serviceConfig.ephemeralServiceURL) let httpRequest = UploadOtcHTTPRequest(context: context, recipientId: cardId, otc: oneTimeCardsRequests.map({ $0.serialize() })) let handler = { (request: VSSHTTPRequest) in guard request.error == nil else { completion(nil, request.error!) return } let request = request as! UploadOtcHTTPRequest guard let response = request.uploadOtcResponse else { completion(nil, nil) return } do { let otc = try response.otc.map( { dict -> VSSCard in guard let card = VSSCard(dict: dict) else { throw SecureChat.makeError(withCode: .deserializingVirgilCard, description: "Error deserializing virgil card.") } return card }) completion(otc, nil) return } catch { completion(nil, nil) return } } httpRequest.completionHandler = handler self.send(httpRequest) } }
bsd-3-clause
392d8f7890656cef9148a32399f866ef
38.056
229
0.556944
5.364835
false
false
false
false
yokoe/gotanda
Sources/Gotanda.swift
1
5222
#if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif open class Gotanda { fileprivate var bitmapContext: CGContext? fileprivate var canvasSize: CGSize #if os(OSX) public init(size: CGSize, backgroundColor: CGColor = NSColor.clear.cgColor) { canvasSize = size setup(backgroundColor: backgroundColor) } public convenience init(width: UInt, height: UInt, backgroundColor: CGColor = NSColor.clear.cgColor) { self.init(size: CGSize(width: CGFloat(width), height: CGFloat(height)), backgroundColor: backgroundColor) } public convenience init(image: NSImage) { self.init(size: image.size) var imageRect = NSRect(origin: CGPoint(), size: image.size) guard let cgImage = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) else { fatalError("Failed to create cgimage from image.") } draw(cgImage, mode: .center) } #elseif os(iOS) public init(size: CGSize, backgroundColor: CGColor = UIColor.clear.cgColor) { canvasSize = size setup(backgroundColor: backgroundColor) } public convenience init(width: UInt, height: UInt, backgroundColor: CGColor = UIColor.clear.cgColor) { self.init(size: CGSize(width: CGFloat(width), height: CGFloat(height)), backgroundColor: backgroundColor) } public convenience init(image: UIImage) { self.init(size: image.size) guard let cgImage = image.cgImage else { fatalError("Failed to create cgimage from image.") } draw(cgImage, mode: .center) } #endif private func setup(backgroundColor: CGColor) { let width = UInt(canvasSize.width) let height = UInt(canvasSize.height) let bitsPerComponent = Int(8) let bytesPerRow = 4 * width let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).rawValue bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: bitsPerComponent, bytesPerRow: Int(bytesPerRow), space: colorSpace, bitmapInfo: bitmapInfo) if let context = bitmapContext { context.setFillColor(backgroundColor) context.fill(CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) } else { fatalError("Failed to create bitmap context.") } } @discardableResult open func draw(_ contents: ((_ context: CGContext) -> ())) -> Gotanda { guard let context = bitmapContext else { fatalError("bitmapContext is empty.") } #if os(iOS) UIGraphicsPushContext(context) #endif contents(context) #if os(iOS) UIGraphicsPopContext() #endif return self } public enum ImageScaleMode { case center case centerFill case centerFit } @discardableResult open func draw(_ image: CGImage, mode: ImageScaleMode) -> Gotanda { let imageWidth: CGFloat = CGFloat(image.width) let imageHeight: CGFloat = CGFloat(image.height) var scale: CGFloat switch mode { case .centerFill: let scaleX = canvasSize.width / imageWidth let scaleY = canvasSize.height / imageHeight scale = max(scaleX, scaleY) case .centerFit: let scaleX = canvasSize.width / CGFloat(image.width) let scaleY = canvasSize.height / CGFloat(image.height) scale = min(scaleX, scaleY) case .center: scale = 1 } let scaledWidth = imageWidth * scale let scaledHeight = imageHeight * scale let targetRect = CGRect(x: (canvasSize.width - scaledWidth) * 0.5, y: (canvasSize.height - scaledHeight) * 0.5, width: scaledWidth, height: scaledHeight) draw { (context) in context.draw(image, in: targetRect) } return self } #if os(OSX) open var imageRep: NSBitmapImageRep? { guard let context = bitmapContext else { fatalError("bitmapContext is empty.") } if let newImageRef = context.makeImage() { return NSBitmapImageRep(cgImage: newImageRef) } else { return nil } } open var pngData: Data? { guard let imageRep = imageRep else { print("No image rep.") return nil } return imageRep.representation(using: .png, properties: [:]) } open var nsImage: NSImage? { guard let pngData = pngData else { print("No pngData.") return nil } return NSImage(data: pngData) } #endif #if os(iOS) open var cgImage: CGImage? { return bitmapContext?.makeImage() } open var uiImage: UIImage? { guard let img = cgImage else { return nil } return UIImage(cgImage: img) } #endif }
mit
ee03eea3eda32391a468d819ecc6d9e2
30.841463
194
0.591153
4.968601
false
false
false
false
johnno1962d/swift
test/SILOptimizer/devirt_covariant_return.swift
1
7776
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0 -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | FileCheck %s // Make sure that we can dig all the way through the class hierarchy and // protocol conformances with covariant return types correctly. The verifier // should trip if we do not handle things correctly. // // As a side-test it also checks if all allocs can be promoted to the stack. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return6driverFT_T_ : $@convention(thin) () -> () { // CHECK: bb0 // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: function_ref @unknown1a : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @defenestrate : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @unknown2a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: function_ref @unknown3a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: tuple // CHECK: return @_silgen_name("unknown1a") func unknown1a() -> () @_silgen_name("unknown1b") func unknown1b() -> () @_silgen_name("unknown2a") func unknown2a() -> () @_silgen_name("unknown2b") func unknown2b() -> () @_silgen_name("unknown3a") func unknown3a() -> () @_silgen_name("unknown3b") func unknown3b() -> () @_silgen_name("defenestrate") func defenestrate() -> () class B<T> { // We do not specialize typealias's correctly now. //typealias X = B func doSomething() -> B<T> { unknown1a() return self } // See comment in protocol P //class func doSomethingMeta() { // unknown1b() //} func doSomethingElse() { defenestrate() } } class B2<T> : B<T> { // When we have covariance in protocols, change this to B2. // We do not specialize typealias correctly now. //typealias X = B override func doSomething() -> B2<T> { unknown2a() return self } // See comment in protocol P //override class func doSomethingMeta() { // unknown2b() //} } class B3<T> : B2<T> { override func doSomething() -> B3<T> { unknown3a() return self } } func WhatShouldIDo<T>(_ b : B<T>) -> B<T> { b.doSomething().doSomethingElse() return b } func doSomethingWithB<T>(_ b : B<T>) { } struct S {} func driver() -> () { let b = B<S>() let b2 = B2<S>() let b3 = B3<S>() WhatShouldIDo(b) WhatShouldIDo(b2) WhatShouldIDo(b3) } driver() public class Bear { public init?(fail: Bool) { if fail { return nil } } // Check that devirtualizer can handle convenience initializers, which have covariant optional // return types. // CHECK-LABEL: sil @_TFC23devirt_covariant_return4Bearc // CHECK: checked_cast_br [exact] %{{.*}} : $Bear to $PolarBear // CHECK: upcast %{{.*}} : $Optional<PolarBear> to $Optional<Bear> // CHECK: } public convenience init?(delegateFailure: Bool, failAfter: Bool) { self.init(fail: delegateFailure) if failAfter { return nil } } } final class PolarBear: Bear { override init?(fail: Bool) { super.init(fail: fail) } init?(chainFailure: Bool, failAfter: Bool) { super.init(fail: chainFailure) if failAfter { return nil } } } class Payload { let value: Int32 init(_ n: Int32) { value = n } func getValue() -> Int32 { return value } } final class Payload1: Payload { override init(_ n: Int32) { super.init(n) } } class C { func doSomething() -> Payload? { return Payload(1) } } final class C1:C { // Override base method, but return a non-optional result override func doSomething() -> Payload { return Payload(2) } } final class C2:C { // Override base method, but return a non-optional result of a type, // which is derived from the expected type. override func doSomething() -> Payload1 { return Payload1(2) } } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TTSf4dg___TF23devirt_covariant_return7driver1FCS_2C1Vs5Int32 // CHECK: integer_literal $Builtin.Int32, 2 // CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32) // CHECK-NOT: class_method // CHECK-NOT: function_ref // CHECK: return func driver1(_ c: C1) -> Int32 { return c.doSomething().getValue() } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TTSf4g___TF23devirt_covariant_return7driver3FCS_1CVs5Int32 // CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2): // CHECK-NOT: bb{{.*}}: // check that for C2, we convert the non-optional result into an optional and then cast. // CHECK: enum $Optional // CHECK-NEXT: upcast // CHECK: return func driver3(_ c: C) -> Int32 { return c.doSomething()!.getValue() } public class D { let v: Int32 init(_ n: Int32) { v = n } } public class D1 : D { public func foo() -> D? { return nil } public func boo() -> Int32 { return foo()!.v } } let sD = D(0) public class D2: D1 { // Override base method, but return a non-optional result override public func foo() -> D { return sD } } // Check that the boo call gets properly devirtualized and that // that D2.foo() is inlined thanks to this. // CHECK-LABEL: sil hidden @_TTSf4g___TF23devirt_covariant_return7driver2FCS_2D2Vs5Int32 // CHECK-NOT: class_method // CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2 // CHECK: bb2 // CHECK: global_addr // CHECK: load // CHECK: ref_element_addr // CHECK: bb3 // CHECK: class_method // CHECK: } func driver2(_ d: D2) -> Int32 { return d.boo() } class AA { } class BB : AA { } class CCC { @inline(never) func foo(_ b: BB) -> (AA, AA) { return (b, b) } } class DDD : CCC { @inline(never) override func foo(_ b: BB) -> (BB, BB) { return (b, b) } } class EEE : CCC { @inline(never) override func foo(_ b: BB) -> (AA, AA) { return (b, b) } } // Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type // correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA) // CHECK-LABEL: sil hidden @_TTSf4g_n___TF23devirt_covariant_return37testDevirtOfMethodReturningTupleTypesFTCS_3CCC1bCS_2BB_TCS_2AAS2__ // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE // CHECK: class_method // CHECK: } func testDevirtOfMethodReturningTupleTypes(_ c: CCC, b: BB) -> (AA, AA) { return c.foo(b) } class AAAA { } class BBBB : AAAA { } class CCCC { let a: BBBB var foo : (AAAA, AAAA) { @inline(never) get { return (a, a) } } init(x: BBBB) { a = x } } class DDDD : CCCC { override var foo : (BBBB, BBBB) { @inline(never) get { return (a, a) } } } // Check devirtualization of methods with optional results, where // optional results need to be casted. // CHECK-LABEL: sil @{{.*}}testOverridingMethodWithOptionalResult // CHECK: checked_cast_br [exact] %{{.*}} : $F to $F // CHECK: checked_cast_br [exact] %{{.*}} : $F to $G // CHECK: switch_enum // CHECK: checked_cast_br [exact] %{{.*}} : $F to $H // CHECK: switch_enum public func testOverridingMethodWithOptionalResult(_ f: F) -> (F?, Int)? { return f.foo() } public class F { @inline(never) public func foo() -> (F?, Int)? { return (F(), 1) } } public class G: F { @inline(never) override public func foo() -> (G?, Int)? { return (G(), 2) } } public class H: F { @inline(never) override public func foo() -> (H?, Int)? { return nil } }
apache-2.0
7e288bce3daadda27cb2579a613aecd4
21.344828
176
0.633102
3.162261
false
false
false
false
tyshcr/snippets
snippets/main.swift
1
1623
// // main.swift // snippets // // Created by TYSH, CHRISTOPHER // // import Foundation class snippets: menuDelegate { var options = [1: "callback", 2: "map", 3: "filter", 4: "flatMap", 5: "enumerate", 6: "exit"] init() { menu() } func menu() { var exit = false while !exit { print("- - - - - -") for (key, value) in options.sorted(by: { $0.0 < $1.0 }) { print("[\(key)] \(value)") } let functionId = readLine()! switch functionId { case "1": callback() case "2": map() case "3": filter() case "4": flatMap() case "5": enumerate() case "6": exit = true default: print("No option selected") } } } func callback() { functionWithCallback { (success) in print("Received callback with value: \(success)") } } func map() { print( functionWithMap() ) } func filter() { print( functionWithFilter() ) } func flatMap() { print( functionWithFlatMap() ) } func enumerate() { print( functionWithEnumeration() ) } } let _ = snippets()
mit
ffc5fde2a97aa288f77adf9238d9795b
18.792683
97
0.359211
5.087774
false
false
false
false
alessioros/mobilecodegenerator3
examples/ParkTraining/completed/ios/ParkTraining/ParkTraining/AppDelegate.swift
2
7520
import UIKit import CoreData import WatchConnectivity @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { var window: UIWindow? var session: WCSession? var receivedMessages : [String : String] = [:] func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { //the message contains only a single pair [key:value] //this loop is used to get a reference to that pair for (key,value) in message { //get message content let messageContent = value as! String let parts = messageContent.characters.split{$0 == ","}.map(String.init) let name:String = parts[0] let sets:Double = Double(parts[1])! let reps:Double = Double(parts[2])! let managedContext = self.managedObjectContext let entity = NSEntityDescription.entityForName("Exercise", inManagedObjectContext: managedContext) let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) item.setValue(name, forKey: "name") item.setValue(sets, forKey: "sets") item.setValue(reps, forKey: "reps") do { try managedContext.save() } catch { print("Error") } } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if (WCSession.isSupported()) { self.session = WCSession.defaultSession() self.session!.delegate = self; self.session!.activateSession() print("WCSession activated") } else { print("WCSession is not supported") } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "it.polimi.ParkTraining" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
gpl-3.0
5d9ba8712bcb86cc3a22d01892273473
50.862069
291
0.682181
5.902669
false
false
false
false
Harshvk/T20Exibition
T20Exibition/T20Exibition/ImagePreviewVC.swift
1
2228
// // ImagePreviewVC.swift // T20Exibition // // Created by appinventiv on 18/02/17. // Copyright © 2017 appinventiv. All rights reserved. // import UIKit import AlamofireImage class ImagePreviewVC: UIViewController { //MARK: Properties var imageURL : String! var titleText : String! //MARK: IBOutlets @IBOutlet weak var enlargedImage: UIImageView! @IBOutlet weak var teamTitle: UILabel! //MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.moveView)) enlargedImage.addGestureRecognizer(panGesture) enlargedImage.isUserInteractionEnabled = true let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.zoomView)) enlargedImage.addGestureRecognizer(pinchGesture) } override func viewWillLayoutSubviews() { let url = URL(string: imageURL) enlargedImage.af_setImage(withURL: url!) teamTitle.text = titleText } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(_ animated: Bool) { } func moveView(pan : UIPanGestureRecognizer){ let newPoint = pan.translation(in: self.enlargedImage) switch pan.state { case .began: print("Pan began") case .changed: self.enlargedImage.transform = CGAffineTransform(translationX: newPoint.x, y: newPoint.y) case .ended: print("Pan ended") default: print("default") } } func zoomView(pinch : UIPinchGestureRecognizer){ let newPoint = pinch.scale switch pinch.state { case .began : print("Pinch Began") case .changed : self.enlargedImage.transform = CGAffineTransform(scaleX: newPoint, y: newPoint) case .ended : print("Pinch Ended") default : print("Something Went Wrong") } } }
mit
7e0e72960da92626b232fe2919cf5f03
25.2
103
0.610687
4.970982
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/GPSLocationView.swift
1
3012
// // GPSLocationView.swift // AdvancedMap.Swift // // Created by Aare Undo on 28/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import CoreLocation import UIKit import CartoMobileSDK class GPSLocationView : MapBaseView { var baseLayer: NTCartoOnlineVectorTileLayer! var switchButton: SwitchButton! var projection: NTProjection! let rotationResetButton = RotationResetButton() let scaleBar = ScaleBar() var locationMarker: LocationMarker! convenience init() { self.init(frame: CGRect.zero) initialize() baseLayer = addBaseLayer() infoContent.setText(headerText: Texts.gpsLocationInfoHeader, contentText: Texts.gpsLocationInfoContainer) projection = map.getOptions().getBaseProjection() locationMarker = LocationMarker(mapView: self.map) switchButton = SwitchButton(onImageUrl: "icon_track_location_on.png", offImageUrl: "icon_track_location_off.png") addButton(button: switchButton) rotationResetButton.resetDuration = rotationDuration addSubview(rotationResetButton) scaleBar.map = map addSubview(scaleBar) } override func layoutSubviews() { super.layoutSubviews() let padding: CGFloat = 5 let scaleBarPadding = padding * 3; var width: CGFloat = 50 var height = width var x = frame.width - (width + padding) var y = Device.trueY0() + padding rotationResetButton.frame = CGRect(x: x, y: y, width: width, height: height) width = frame.width / 5 height = 20 y = frame.height - (height + scaleBarPadding) x = frame.width - (width + scaleBarPadding) scaleBar.frame = CGRect(x: x, y: y, width: width, height: height) } override func addRecognizers() { super.addRecognizers() let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.rotationButtonTapped(_:))) rotationResetButton.addGestureRecognizer(recognizer) } override func removeRecognizers() { super.removeRecognizers() rotationResetButton.gestureRecognizers?.forEach(rotationResetButton.removeGestureRecognizer) } let rotationDuration: Float = 0.4 var isRotationInProgress = false @objc func rotationButtonTapped(_ sender: UITapGestureRecognizer) { isRotationInProgress = true map.setRotation(0, durationSeconds: rotationDuration) rotationResetButton.reset() Timer.scheduledTimer(timeInterval: TimeInterval(rotationDuration + 0.1), target: self, selector: #selector(onRotationCompleted), userInfo: nil, repeats: false) } @objc func onRotationCompleted() { isRotationInProgress = false } func resetMapRotation() { map.setRotation(0, durationSeconds: 0.5) } }
bsd-2-clause
c864660e2e4248132f367e2bd2de510f
26.623853
167
0.64995
4.786963
false
false
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/EventSource_CombineLatests.swift
1
8283
// // Copyright (c) 2016-2020 Anton Mironov, Loki // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import Foundation public typealias ES = EventSource public extension ExecutionContext { // MARK: - combineLatest2 /// Combines 2 recent updates into tuple /// You can pass custom executor or use default from Context func combineLatest<ES1: ES, ES2: ES>( _ es1: ES1, _ es2: ES2, executor: Executor? = nil ) -> Channel<(ES1.Update, ES2.Update), (ES1.Success, ES2.Success)> { return CombineLatest2(es1, es2, executor: executor ?? self.executor) .retain(with: self) .producer } // MARK: - combineLatest3 /// Combines recent 3 updates into tuple /// You can pass custom executor or use default from Context func combineLatest<ES1: ES, ES2: ES, ES3: ES>( _ es1: ES1, _ es2: ES2, _ es3: ES3, executor: Executor? = nil ) -> Channel<(ES1.Update, ES2.Update, ES3.Update), (ES1.Success, ES2.Success, ES3.Success)> { return CombineLatest3(es1, es2, es3, executor: executor ?? self.executor) .retain(with: self) .producer } // MARK: - combineLatest4 /// Combines recent 3 updates into tuple /// You can pass custom executor or use default from Context func combineLatest<ES1: ES, ES2: ES, ES3: ES, ES4: ES>( _ es1: ES1, _ es2: ES2, _ es3: ES3, _ es4: ES4, executor: Executor? = nil ) -> Channel<(ES1.Update, ES2.Update, ES3.Update, ES4.Update), (ES1.Success, ES2.Success, ES3.Success, ES4.Success)> { return CombineLatest4(es1, es2, es3, es4, executor: executor ?? self.executor) .retain(with: self) .producer } } class RetainableProducerOwner<Update, Success>: ExecutionContext, ReleasePoolOwner { public let releasePool = ReleasePool() public var executor: Executor var producer = Producer<Update, Success>() init(executor: Executor) { self.executor = executor } func retain(with releasePool: Retainer) -> RetainableProducerOwner { releasePool.releaseOnDeinit(self) return self } } private class CombineLatest2<ES1: ES, ES2: ES>: RetainableProducerOwner< (ES1.Update, ES2.Update), (ES1.Success, ES2.Success) > { var update1: ES1.Update? var update2: ES2.Update? var success1: ES1.Success? var success2: ES2.Success? init(_ es1: ES1, _ es2: ES2, executor: Executor) { super.init(executor: executor) es1.onUpdate(context: self) { ctx, upd in ctx.update1 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success1 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es2.onUpdate(context: self) { ctx, upd in ctx.update2 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success2 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } } func trySendUpdate() { guard let upd1 = update1 else { return } guard let upd2 = update2 else { return } producer.update((upd1, upd2), from: executor) } func tryComplete() { guard let suc1 = success1 else { return } guard let suc2 = success2 else { return } producer.succeed((suc1, suc2), from: executor) } } private class CombineLatest3<ES1: ES, ES2: ES, ES3: ES>: RetainableProducerOwner< (ES1.Update, ES2.Update, ES3.Update), (ES1.Success, ES2.Success, ES3.Success) > { var update1: ES1.Update? var update2: ES2.Update? var update3: ES3.Update? var success1: ES1.Success? var success2: ES2.Success? var success3: ES3.Success? init(_ es1: ES1, _ es2: ES2, _ es3: ES3, executor: Executor) { super.init(executor: executor) es1.onUpdate(context: self) { ctx, upd in ctx.update1 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success1 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es2.onUpdate(context: self) { ctx, upd in ctx.update2 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success2 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es3.onUpdate(context: self) { ctx, upd in ctx.update3 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success3 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } } func trySendUpdate() { guard let upd1 = update1 else { return } guard let upd2 = update2 else { return } guard let upd3 = update3 else { return } producer.update((upd1, upd2, upd3), from: executor) } func tryComplete() { guard let suc1 = success1 else { return } guard let suc2 = success2 else { return } guard let suc3 = success3 else { return } producer.succeed((suc1, suc2, suc3), from: executor) } } private class CombineLatest4<ES1: ES, ES2: ES, ES3: ES, ES4: ES>: RetainableProducerOwner< (ES1.Update, ES2.Update, ES3.Update, ES4.Update), (ES1.Success, ES2.Success, ES3.Success, ES4.Success) > { var update1: ES1.Update? var update2: ES2.Update? var update3: ES3.Update? var update4: ES4.Update? var success1: ES1.Success? var success2: ES2.Success? var success3: ES3.Success? var success4: ES4.Success? init(_ es1: ES1, _ es2: ES2, _ es3: ES3, _ es4: ES4, executor: Executor) { super.init(executor: executor) es1.onUpdate(context: self) { ctx, upd in ctx.update1 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success1 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es2.onUpdate(context: self) { ctx, upd in ctx.update2 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success2 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es3.onUpdate(context: self) { ctx, upd in ctx.update3 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success3 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } es4.onUpdate(context: self) { ctx, upd in ctx.update4 = upd; ctx.trySendUpdate() } .onSuccess(context: self) { ctx, success in ctx.success4 = success; ctx.tryComplete() } .onFailure(context: self) { ctx, error in ctx.producer.fail(error, from: executor) } } func trySendUpdate() { guard let upd1 = update1 else { return } guard let upd2 = update2 else { return } guard let upd3 = update3 else { return } guard let upd4 = update4 else { return } producer.update((upd1, upd2, upd3, upd4), from: executor) } func tryComplete() { guard let suc1 = success1 else { return } guard let suc2 = success2 else { return } guard let suc3 = success3 else { return } guard let suc4 = success4 else { return } producer.succeed((suc1, suc2, suc3, suc4), from: executor) } }
mit
1bd1f21e6d8981bb0619e94710f2add3
36.310811
120
0.674997
3.31984
false
true
false
false
vitkuzmenko/Swiftex
Extensions/Foundation/NSObject+Extension.swift
1
4219
// // NSObject+Extension.swift // // // Created by Vitaliy Kuzmenko on 14/04/15. // Copyright (c) 2015. All rights reserved. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #else import Foundation #endif extension NSObject { public class var nameOfClass: String { return NSStringFromClass(self).components(separatedBy: ".").last! } public var nameOfClass: String { return NSStringFromClass(type(of: self)).components(separatedBy: ".").last! } } #if os(iOS) || os(watchOS) @objc extension NSObject { // MARK: - Keyboard open func addKeyboardWillShowNotification() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) } open func addKeyboardDidShowNotification() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil) } open func addKeyboardWillHideNotification() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } open func addKeyboardDidHideNotification() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(notification:)), name: UIResponder.keyboardDidHideNotification, object: nil) } open func addKeyboardWillUpdateNotification() { addKeyboardWillShowNotification() addKeyboardWillHideNotification() } open func addKeyboardDidUpdateNotification() { addKeyboardDidShowNotification() addKeyboardDidHideNotification() } open func removeKeyboardWillShowNotification() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) } open func removeKeyboardDidShowNotification() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) } open func removeKeyboardWillHideNotification() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } open func removeKeyboardDidHideNotification() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil) } open func keyboardDidShow(notification: Notification) { guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } keyboardDidShow(frame: value.cgRectValue) keyboardDidUpdate(frame: value.cgRectValue) } open func keyboardWillShow(notification: Notification) { guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } keyboardWillShow(frame: value.cgRectValue) keyboardWillUpdate(frame: value.cgRectValue) } open func keyboardWillHide(notification: Notification) { guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } keyboardWillHide(frame: value.cgRectValue) keyboardWillUpdate(frame: .zero) } open func keyboardDidHide(notification: Notification) { guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } keyboardDidHide(frame: value.cgRectValue) keyboardDidUpdate(frame: .zero) } open func keyboardWillShow(frame: CGRect) { } open func keyboardDidShow(frame: CGRect) { } open func keyboardWillHide(frame: CGRect) { } open func keyboardDidHide(frame: CGRect) { } open func keyboardWillUpdate(frame: CGRect) { } open func keyboardDidUpdate(frame: CGRect) { } } #endif
apache-2.0
b20cd32bfd26fff3c82f4519405e01a4
33.024194
167
0.700403
5.429858
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewSlider.swift
1
19363
// // PayloadCellViewDatePicker.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads class PayloadCellViewSliderViewController: NSViewController { // MARK: - // MARK: Variables weak var cellView: PayloadCellViewSlider? // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(cellView: PayloadCellViewSlider) { super.init(nibName: nil, bundle: nil) self.view = EditorSlider.slider(cellView: cellView) self.cellView = cellView } override func viewWillAppear() { self.cellView?.updateTickMarkConstraints() self.cellView?.setupSliderTickMarkTitles() } } class PayloadCellViewSlider: PayloadCellView, ProfileCreatorCellView, SliderCellView { // MARK: - // MARK: Instance Variables var slider: NSSlider? var sliderViewController: NSViewController? var tickMarkTextFields = [NSTextField]() var tickMarkConstraints = [NSLayoutConstraint]() var tickMarkConstraintsApplied = false var valueDefault: Double? @objc private var value: Any? // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) { super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor) // --------------------------------------------------------------------- // Setup Custom View Content // --------------------------------------------------------------------- self.sliderViewController = PayloadCellViewSliderViewController(cellView: self) let slider = self.sliderViewController?.view as? NSSlider ?? NSSlider() self.slider = slider self.setupSlider() self.setupSliderTickMarkTextFields() // Last textField add height to frame self.height += 3 + (tickMarkTextFields.first?.intrinsicContentSize.height ?? 0) // --------------------------------------------------------------------- // Setup Footer // --------------------------------------------------------------------- super.setupFooter(belowCustomView: self.tickMarkTextFields.first) // --------------------------------------------------------------------- // Get Default Value // --------------------------------------------------------------------- if let valueDefault = subkey.defaultValue() as? Double { self.valueDefault = valueDefault } // --------------------------------------------------------------------- // Get Value // --------------------------------------------------------------------- var currentValue: Any if let value = profile.settings.value(forSubkey: subkey, payloadIndex: payloadIndex) as? Double { currentValue = value } else if let valueDefault = self.valueDefault { currentValue = valueDefault } else if let valueMin = subkey.rangeMin as? Double { currentValue = valueMin } else { currentValue = slider.minValue } if let index = subkey.rangeList?.index(ofValue: currentValue, ofType: subkey.type) { slider.doubleValue = slider.tickMarkValue(at: index) } // --------------------------------------------------------------------- // Setup KeyView Loop Items // --------------------------------------------------------------------- self.leadingKeyView = self.slider self.trailingKeyView = self.slider // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(self.cellViewConstraints) } func updateTickMarkConstraints() { guard !self.tickMarkConstraintsApplied, let slider = self.slider else { return } for (index, constraint) in self.tickMarkConstraints.enumerated() { if index == 0 || index == (self.tickMarkConstraints.count - 1) { continue } constraint.constant = slider.rectOfTickMark(at: index).midX } self.tickMarkConstraintsApplied = true } // MARK: - // MARK: PayloadCellView Functions override func enable(_ enable: Bool) { self.isEnabled = enable self.slider?.isEnabled = enable } // MARK: - // MARK: SliderCellView Functions func selected(_ slider: NSSlider) { var value: NSNumber = 0 if let rangeList = self.subkey.rangeList { if let sliderCell = slider.cell as? NSSliderCell { let knobPoint = CGPoint(x: sliderCell.knobRect(flipped: false).midX, y: slider.rectOfTickMark(at: 0).origin.y) let index = slider.indexOfTickMark(at: knobPoint) if index < rangeList.count, let tickMarkValue = rangeList[index] as? NSNumber { value = tickMarkValue } } } else { value = NSNumber(value: slider.doubleValue) } self.profile.settings.setValue(value, forSubkey: self.subkey, payloadIndex: self.payloadIndex) } } // MARK: - // MARK: Setup NSLayoutConstraints extension PayloadCellViewSlider { private func setupSlider() { // --------------------------------------------------------------------- // Get Slider // --------------------------------------------------------------------- guard let slider = self.slider else { return } slider.allowsTickMarkValuesOnly = (self.subkey.rangeList != nil) // --------------------------------------------------------------------- // Add Slider to TableCellView // --------------------------------------------------------------------- self.addSubview(slider) if let rangeMax = self.subkey.rangeList?.last as? NSNumber { slider.maxValue = rangeMax.doubleValue } else if let rangeMax = self.subkey.rangeMax as? NSNumber { slider.maxValue = rangeMax.doubleValue } else { slider.maxValue = Double(Int.max) } if let rangeMin = self.subkey.rangeList?.first as? NSNumber, rangeMin.doubleValue < slider.maxValue { slider.minValue = rangeMin.doubleValue } else if let rangeMin = self.subkey.rangeMin as? NSNumber, rangeMin.doubleValue < slider.maxValue { slider.minValue = rangeMin.doubleValue } else { slider.minValue = 0.0 } if let rangeList = self.subkey.rangeList { slider.numberOfTickMarks = rangeList.count } else { slider.numberOfTickMarks = 2 } // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Below self.addConstraints(forViewBelow: slider) // Leading self.addConstraints(forViewLeading: slider) // Trailing self.addConstraints(forViewTrailing: slider) } private func setupSliderTickMarkTextFields() { // --------------------------------------------------------------------- // Get Slider // --------------------------------------------------------------------- guard let slider = self.slider else { return } for index in 0...(slider.numberOfTickMarks - 1) { let textFieldTickMark = EditorTextField.label(string: "", fontWeight: .regular, cellView: self) self.setupTextFieldTickMark(textFieldTickMark, first: index == 0, last: index == (slider.numberOfTickMarks - 1)) } } func setupSliderTickMarkTitles() { // --------------------------------------------------------------------- // Get Slider // --------------------------------------------------------------------- guard let slider = self.slider else { return } let sliderWidth = slider.frame.width if let rangeListTitles = self.subkey.rangeListTitles { self.setupSliderTickMarkTitles(rangeListTitles: rangeListTitles, sliderWidth: sliderWidth) } else if let rangeList = self.subkey.rangeList { // let rangeListTitles = rangeList.map({ String(describing: $0) }) self.setupSliderTickMarkTitles(rangeList: rangeList, sliderWidth: sliderWidth) // self.setupSliderTickMarkTitles(rangeListTitles: rangeListTitles, sliderWidth: sliderWidth) } } func setupSliderTickMarkTitles(rangeList: [Any], sliderWidth: CGFloat) { // --------------------------------------------------------------------- // Get Slider // --------------------------------------------------------------------- guard let slider = self.slider else { return } var combinedTextFieldWidth: CGFloat = 0.0 for (index, textField) in self.tickMarkTextFields.enumerated() { var title: String if index < rangeList.count, let value = rangeList[index] as? NSNumber { title = String(value.doubleValue) } else { title = String(slider.tickMarkValue(at: index)) } textField.stringValue = title combinedTextFieldWidth += textField.intrinsicContentSize.width } } func setupSliderTickMarkTitles(rangeListTitles titles: [String], sliderWidth: CGFloat) { // FIXME: This while thing could be made much more efficient, and also should be saved in the subkey to not have to recalculate the same info all the time. var titlesWidth: CGFloat = 1_000.0 var titlesToSkip = -1 while sliderWidth < titlesWidth { var combinedTextFieldWidth: CGFloat = 0.0 titlesToSkip += 1 var titlesSkipped = 0 var previousTextField = NSTextField() var previousTextFieldFrame = CGRect() var titlesOverlapped = false for (index, textField) in self.tickMarkTextFields.enumerated() { if index == 0 || index == (self.tickMarkTextFields.count - 1) || titlesToSkip == titlesSkipped { if index < titles.count { textField.stringValue = titles[index] previousTextFieldFrame = previousTextField.frame previousTextField = textField } titlesSkipped = 0 } else { textField.stringValue = "" titlesSkipped += 1 } combinedTextFieldWidth += textField.intrinsicContentSize.width self.layoutSubtreeIfNeeded() if textField.frame.intersects(previousTextFieldFrame) { titlesOverlapped = true break } } if !titlesOverlapped { titlesWidth = combinedTextFieldWidth } // FIXME: Need to only keep first and last if there is no more room, even if they touch. if (self.tickMarkTextFields.count - 2) <= titlesToSkip { break } } } private func setupTextFieldTickMark(_ textField: NSTextField, first: Bool = false, last: Bool = false) { // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(textField) self.tickMarkTextFields.append(textField) textField.alignment = .center // Below self.cellViewConstraints.append(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: slider, attribute: .bottom, multiplier: 1.0, constant: 3.0)) if first { // Leading let constraintLeading = NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: slider, attribute: .leading, multiplier: 1.0, constant: 0.0) self.cellViewConstraints.append(constraintLeading) self.tickMarkConstraints.append(constraintLeading) } else if last { // Trailing let constraintTrailing = NSLayoutConstraint(item: textField, attribute: .trailing, relatedBy: .equal, toItem: slider, attribute: .trailing, multiplier: 1.0, constant: 0.0) self.cellViewConstraints.append(constraintTrailing) self.tickMarkConstraints.append(constraintTrailing) } else { // Center let constraintCenter = NSLayoutConstraint(item: textField, attribute: .centerX, relatedBy: .equal, toItem: slider, attribute: .leading, multiplier: 1.0, constant: 0.0) self.cellViewConstraints.append(constraintCenter) self.tickMarkConstraints.append(constraintCenter) } } /* private func setupTextFieldInput() { // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- guard let textFieldInput = self.textFieldInput, let slider = self.slider else { return } self.addSubview(textFieldInput) // --------------------------------------------------------------------- // Add Number Formatter to TextField // --------------------------------------------------------------------- let numberFormatter = NumberFormatter() if self.subkey.type == .float { numberFormatter.allowsFloats = true numberFormatter.alwaysShowsDecimalSeparator = true numberFormatter.numberStyle = .decimal } else { numberFormatter.numberStyle = .none } if let rangeMax = self.subkey.rangeMax as? NSNumber { numberFormatter.maximum = rangeMax } else { numberFormatter.maximum = Int.max as NSNumber } if let rangeMin = self.subkey.rangeMin as? NSNumber { numberFormatter.minimum = rangeMin } else { numberFormatter.minimum = Int.min as NSNumber } if let decimalPlaces = self.subkey.valueDecimalPlaces { numberFormatter.maximumFractionDigits = decimalPlaces numberFormatter.minimumFractionDigits = decimalPlaces } else { numberFormatter.maximumFractionDigits = 16 // This is the default in plist <real> tags. which is a double. } textFieldInput.formatter = numberFormatter textFieldInput.bind(.value, to: self, withKeyPath: "value", options: [NSBindingOption.nullPlaceholder: "", NSBindingOption.continuouslyUpdatesValue: true]) textFieldInput.isBordered = false // --------------------------------------------------------------------- // Get TextField Number Maximum Width // --------------------------------------------------------------------- var valueMaxWidth: CGFloat = 0 if let valueMax = numberFormatter.maximum { textFieldInput.stringValue = NSNumber(value: (valueMax.doubleValue - 0.000_000_000_000_001)).stringValue } else if let valueMin = numberFormatter.minimum { textFieldInput.stringValue = NSNumber(value: (valueMin.doubleValue + 0.000_000_000_000_001)).stringValue } textFieldInput.sizeToFit() valueMaxWidth = textFieldInput.frame.width + 2.0 textFieldInput.stringValue = "" // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Leading self.cellViewConstraints.append(NSLayoutConstraint(item: textFieldInput, attribute: .leading, relatedBy: .equal, toItem: slider, attribute: .trailing, multiplier: 1.0, constant: 4.0)) // Baseline self.cellViewConstraints.append(NSLayoutConstraint(item: textFieldInput, attribute: .firstBaseline, relatedBy: .equal, toItem: slider, attribute: .firstBaseline, multiplier: 1.0, constant: 0.0)) // Width self.cellViewConstraints.append(NSLayoutConstraint(item: textFieldInput, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: valueMaxWidth)) self.addConstraints(forViewTrailing: textFieldInput) } */ }
mit
ba613c680238c24b687d73afae20c74b
40.818575
163
0.466532
6.341959
false
false
false
false
charles-oder/FontAwesomeSwift
FontAwesomeSwift/Core/FASFontLoader.swift
1
2339
// // FontLoader.swift // FontAwesomeSwift // // Created by Charles Oder Dev on 12/26/16. // // import Foundation public class FASFontLoader { public static func loadCustomFont(family: String, name: String, fileName: String, type: String, size: CGFloat, bundle: Bundle) -> UIFont { if !UIFont.fontNames(forFamilyName: family).contains(name) { loadFont(fileName, type: type, bundle: bundle) } return UIFont(name: name, size: size)! } class func loadFont(_ fileName: String, type: String, bundle: Bundle) { let fontURL = getFontUrl(name: fileName, type: type, bundle: bundle) registerFontFile(url: fontURL) } class func registerFontFile(url: URL) { do { let data = try Data(contentsOf: url) let provider = CGDataProvider(data: data as CFData) let font = CGFont.init(provider!) var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font!, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } catch { print("unable to load font file: \(url.absoluteString)") } } class func getFontUrl(name: String, type: String, bundle: Bundle) -> URL { var fontURL = URL(string: "") for filePath : String in bundle.paths(forResourcesOfType: type, inDirectory: nil) { let filename = NSURL(fileURLWithPath: filePath).lastPathComponent! if filename == "\(name).\(type)" { fontURL = NSURL(fileURLWithPath: filePath) as URL } } return fontURL! } class func listAllFonts() { let families = UIFont.familyNames.sorted() for family in families { print("Family: \(family)") let names = UIFont.fontNames(forFamilyName: family) for name in names { print("\t\(name)") } } } }
mit
17741b5389f2732ac16403ac76a35f7b
32.414286
168
0.586148
4.893305
false
false
false
false
alirsamar/BiOS
RobotMaze2/Maze/MazeCellView.swift
1
2502
// // MazeCell.swift // Maze // // Created by Jarrod Parkes on 8/14/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import UIKit // MARK: - MazeCellView class MazeCellView : UIView { // MARK: Properties var wallColor: UIColor = UIColor.orangeColor() var cellModel: MazeCellModel? var wallWidth: CGFloat = 1 // MARK: UIView override func drawRect(rect: CGRect) { super.drawRect(rect) if let cellModel = cellModel { // Set the wallColor wallColor.set() let width = bounds.width let height = bounds.height let path = CGPathCreateMutable() // Half wallWidth let hw = wallWidth / CGFloat(2) if cellModel.top { CGPathMoveToPoint(path, nil, 0 - hw, 0) CGPathAddLineToPoint(path, nil, width + hw, 0) } if cellModel.right { CGPathMoveToPoint(path, nil, width, 0) CGPathAddLineToPoint(path, nil, width, height) } if cellModel.bottom { CGPathMoveToPoint(path, nil, width + hw, height) CGPathAddLineToPoint(path, nil, 0 - hw, height) } if cellModel.left { CGPathMoveToPoint(path, nil, 0, height) CGPathAddLineToPoint(path, nil, 0, 0) } let bezierPath = UIBezierPath(CGPath: path) bezierPath.lineWidth = wallWidth; bezierPath.stroke() // Rounded corners let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) let nearCornerValue = -0.5 * wallWidth let farCornerValue = width + nearCornerValue CGContextFillEllipseInRect(context, CGRect(x: nearCornerValue, y: nearCornerValue, width: wallWidth, height: wallWidth)) CGContextFillEllipseInRect(context, CGRect(x: farCornerValue, y: farCornerValue, width: wallWidth, height: wallWidth)) CGContextFillEllipseInRect(context, CGRect(x: farCornerValue, y: nearCornerValue, width: wallWidth, height: wallWidth)) CGContextFillEllipseInRect(context, CGRect(x: nearCornerValue, y: farCornerValue, width: wallWidth, height: wallWidth)) CGContextRestoreGState(context) } } }
mit
fc7c9943cf3b0b7a4f8713e215469021
32.346667
132
0.564574
5.104082
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/search/GsFreeCardViewController.swift
1
2536
// // GsFreeCardViewController.swift // GitHubStar // // Created by midoks on 16/2/8. // Copyright © 2016年 midoks. All rights reserved. // import UIKit //自由号管理 class GsFreeCardViewController: GsViewController, UITableViewDataSource, UITableViewDelegate { public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) return cell } var _tableView: UITableView? override func viewDidLoad() { super.viewDidLoad() self.title = "自由号" _tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.plain) _tableView?.dataSource = self _tableView?.delegate = self self.view.addSubview(_tableView!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.tabBarController?.tabBar.isHidden = false } //Mark: - UITableViewDataSource - private func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 0 } else if section == 1 { return 1 } else if section == 2 { return 1 } return 0 } private func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) if indexPath.section == 0 { } else if indexPath.section == 1 { if indexPath.row == 0 { cell.textLabel?.text = "新鲜事" cell.accessoryType = .disclosureIndicator } } else if indexPath.section == 2 { if indexPath.row == 0 { cell.textLabel?.text = "自由号" cell.accessoryType = .disclosureIndicator } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) print("设置") } }
apache-2.0
dcf386a148677c58f0152aa53d788540
26.788889
115
0.591763
5.378495
false
false
false
false
Daemon-Devarshi/MedicationSchedulerSwift3.0
Medication/ViewControllers/PatientsListing/PatientDetailViewController.swift
1
2022
// // PatientDetailViewController.swift // Medication // // Created by Devarshi Kulshreshtha on 8/20/16. // Copyright © 2016 Devarshi. All rights reserved. // import UIKit import CoreData class PatientDetailViewController: UIViewController { //MARK: Constants declarations static let pushSegueIdentifier = "PushPatientDetailViewController" //MARK: Var declarations fileprivate var managedObjectContext: NSManagedObjectContext! fileprivate var medicationsTableViewController: MedicationsTableViewController! var patient: Patient! { didSet { managedObjectContext = patient.managedObjectContext } } //MARK: Outlets declarations @IBOutlet weak var patientName: UILabel! @IBOutlet weak var patientEmail: UILabel! @IBOutlet weak var patientPhoneNumber: UILabel! //MARK: Overriden methods override func viewDidLoad() { super.viewDidLoad() populate() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segueIdentifier = segue.identifier { if segueIdentifier == MedicationsTableViewController.embedSegueIdentifier { // passing managedObjectContext to PatientsTableViewController medicationsTableViewController = segue.destination as! MedicationsTableViewController medicationsTableViewController.patient = patient } else if segueIdentifier == AddNewMedicationViewController.pushSegueIdentifier { // passing managedObjectContext to PatientsTableViewController let addNewMedicationViewController = segue.destination as! AddNewMedicationViewController addNewMedicationViewController.patient = patient } } } fileprivate func populate() { patientName.text = patient.fullName patientEmail.text = patient.email patientPhoneNumber.text = patient.phoneNumber } }
mit
d7419dba7ad8a8ba8ad4699950865726
33.254237
105
0.689758
5.97929
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCMailAttachmentsStructuresViewController.swift
2
1546
// // NCMailAttachmentsStructuresViewController.swift // Neocom // // Created by Artem Shimanski on 12.07.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import Futures class NCMailAttachmentsStructuresViewController: NCTreeViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCDefaultTableViewCell.default, Prototype.NCHeaderTableViewCell.default]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func content() -> Future<TreeNode?> { return .init(NCLoadoutsSection<NCAttachmentLoadoutRow>(categoryID: .structure)) } //MARK: - TreeControllerDelegate override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { super.treeController(treeController, didSelectCellWithNode: node) guard let item = node as? NCLoadoutRow else {return} guard let context = NCStorage.sharedStorage?.viewContext else {return} guard let loadout = (try? context.existingObject(with: item.loadoutID)) else {return} guard let parent = parent as? NCMailAttachmentsViewController else {return} parent.completionHandler?(parent, loadout) } func treeControllerDidUpdateContent(_ treeController: TreeController) { tableView.backgroundView = treeController.content?.children.isEmpty == false ? nil : NCTableViewBackgroundLabel(text: NSLocalizedString("No Results", comment: "")) } }
lgpl-2.1
b8da2a9c2b53a4c6f344f8598d578bf9
33.333333
165
0.769579
4.61194
false
false
false
false
chris-hatton/SwiftImage
Sources/Process/Image/GenericImage+Line.swift
1
1119
// // GenericImage+Line.swift // SwiftImage-Apple // // Created by Christopher Hatton on 21/10/2016. // Copyright © 2016 Chris Hatton. All rights reserved. // extension GenericImage { /* public func drawLine( x: Int, y: Int, x2: Int, y2: Int, color: UIColor) { int w = x2 - x ; int h = y2 - y ; int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ; if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ; if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ; if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ; int longest = Math.abs(w) ; int shortest = Math.abs(h) ; if (!(longest>shortest)) { longest = Math.abs(h) ; shortest = Math.abs(w) ; if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ; dx2 = 0 ; } int numerator = longest >> 1 ; for (int i=0;i<=longest;i++) { putpixel(x,y,color) ; numerator += shortest ; if (!(numerator<longest)) { numerator -= longest ; x += dx1 ; y += dy1 ; } else { x += dx2 ; y += dy2 ; } } } */ }
gpl-2.0
37e434e672f40956f8c8b8361e5bf4cb
25
75
0.453488
2.965517
false
true
false
false
hugolundin/Template
Template/Template/Controllers/MainViewController.swift
1
2420
// // MainViewController.swift // Template // // Created by Hugo Lundin on 2017-08-10. // Copyright © 2017 Hugo Lundin. All rights reserved. // import UIKit class MainViewController: UIViewController, UITextViewDelegate, Alertable { typealias Dependencies = HasSettingsProvider & HasTodoistProvider & HasCSVProvider var dependencies: Dependencies? // MARK: - Outlets @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var settingsButton: UIBarButtonItem! @IBOutlet weak var textView: UITextView! { didSet { textView.delegate = self textView.becomeFirstResponder() } } override func viewDidLoad() { super.viewDidLoad() } @IBAction func share(_ sender: UIBarButtonItem) { guard let text = textView?.text else { return } // Make sure that user is authenticated if dependencies?.settings?.apiToken == "" { alert(title: "Error", message: "You are not authenticated.\n Please go to settings and enter your API token.") return } // Make sure that any text is entered guard text.count > 0 else { alert(title: "Error", message: "You have not entered any text.") return } // Replace share button with activity indicator let loading = UIActivityIndicatorView(activityIndicatorStyle: .gray) loading.hidesWhenStopped = true loading.startAnimating() self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loading) guard let file = try? dependencies?.csv?.file(from: text) else { return } guard let fileURL = file else { return } let controller = ShareViewController(with: fileURL, dependencies: dependencies) present(controller, animated: true, completion: { // Stop activity indicator and replace it with the `shareButton` loading.stopAnimating() self.navigationItem.rightBarButtonItem = self.shareButton }) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? SettingsViewController { controller.dependencies = dependencies } } }
mit
b611cfc86585ef34a7fc84d2f9363ca2
30.828947
122
0.613477
5.510251
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/Business/Goals/GoalProgressCalculator.swift
1
5682
// // GoalProgressCalculator.swift // YourGoals // // Created by André Claaßen on 27.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation /// progress indicator /// /// - met: 95% - 100% /// - ahead: 20% more ahead /// - onTrack: + / - 20% /// - lagging: 20% behind /// - behind: >50% behind /// - notStarted: no progress at allo enum ProgressIndicator { case met case ahead case onTrack case lagging case behind case notStarted } /// this class calculates the progress on this goal in percent class GoalProgressCalculator:StorageManagerWorker { /// calculate the progress made on this goal. compare progress of tasks done versus progress of time elapsed /// /// - Parameters: /// - goal: the goal /// - date: the date for comparision /// - Returns: progress of tasks in percent and a progress indicator func calculateProgress(forGoal goal: Goal, forDate date: Date, withBackburned backburnedGoals: Bool) throws -> (progress:Double, indicator:ProgressIndicator) { let progressTasks = try calculateProgressOfActionables(forGoal: goal, andDate: date, withBackburned: backburnedGoals) let progressDate = calculateProgressOfTime(forGoal: goal, forDate: date) let progressIndicator = calculateIndicator(progressTasks: progressTasks, progressDate: progressDate) return (progressTasks, progressIndicator) } /// get the actionables for this goal for the day /// /// - Parameters: /// - goal: the goal /// - date: the day /// - backburnedGoals: include backburned goals /// - Returns: an array of actionables /// - Throws: core data exceptio func getActionables(goal: Goal, date: Date, backburnedGoals: Bool) throws -> [Actionable] { let dataSource = ActionableDataSourceProvider(manager: self.manager).dataSource(forGoal: goal, andType: goal.goalType() == .todayGoal ? nil : .task) let items = try dataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil) let actionables = items.map{ $0.actionable } return actionables } /// calculate the progress of tasks done in per /// /// - Parameters /// - goal: the goal /// - date: the date for the actionables /// - Returns: ratio of done tasks and all tasks (between 0.0 and 1.0) func calculateProgressOfActionables(forGoal goal: Goal, andDate date: Date, withBackburned backburnedGoals: Bool) throws -> Double { let actionables = try getActionables(goal: goal, date: date, backburnedGoals: backburnedGoals) let sizeOfAll = actionables.reduce(0.0, { return $0 + $1.size }) let sizeOfDone = actionables.filter{ $0.checkedState(forDate: date) == .done}.reduce(0.0, { return $0 + $1.size }) guard sizeOfAll > 0.0 else { return 0.0 } let progress = Double(sizeOfDone / sizeOfAll) return progress } // todo: test /// this function calculates the progress on a single task in relation to the goal /// /// - Parameters: /// - goal: the goal /// - actionable: the actionable (which is normally a task) /// - date: the date as a base for the calculation /// - backburnedGoals: true, if backburned goals will be included in the calculation /// - Returns: a progress between 0.0 and 1.0 /// - Throws: a core data exception func calculateProgressOnActionable(forGoal goal: Goal, actionable: Actionable, andDate date: Date, withBackburned backburnedGoals: Bool) throws -> Double { let actionables = try getActionables(goal: goal, date: date, backburnedGoals: backburnedGoals) let sizeOfAll = actionables.reduce(0.0, { return $0 + $1.size }) guard sizeOfAll > 0.0 else { return 0.0 } let progress = Double(actionable.size / sizeOfAll) return progress } /// calculate the progress of time in relation to the given date /// /// - Parameters: /// - goal: the goal /// - date: the date for calculate the progress of time since start of the goal /// - Returns: progress of time elapsed from the goal (between 0.0 and 1.0) func calculateProgressOfTime(forGoal goal: Goal, forDate date:Date) -> Double { let range = goal.logicalDateRange(forDate: date) let startDate = range.start let endDate = range.end let timeSpanGoal = endDate.timeIntervalSince(startDate) let timeSpanForDate = date.timeIntervalSince(startDate) let percent = timeSpanForDate / timeSpanGoal if percent < 0.0 { return 0.0 } if percent > 1.0 { return 1.0 } return percent } /// calculate an indicator of progress relative to the time of the goal /// /// - Parameters: /// - progressTasks: progress of the tasks in percent /// - progressDate: progress of the date in percent /// - Returns: an indicator func calculateIndicator(progressTasks:Double, progressDate: Double) -> ProgressIndicator { if progressTasks == 0.0 { return .notStarted } if progressTasks >= 0.95 { return .met } if progressTasks - progressDate >= 0.20 { return .ahead } if progressTasks - progressDate >= -0.20 { return .onTrack } if progressTasks - progressDate >= -0.50 { return .lagging } return .behind } }
lgpl-3.0
0c82fe3c565d9b6c15bc5174687b48d1
35.863636
163
0.627796
4.326982
false
false
false
false
SeaHub/ImgTagging
ImgTagger/ImgTagger/User.swift
1
1630
// // User.swift // ImgTagger // // Created by SeaHub on 2017/6/24. // Copyright © 2017年 SeaCluster. All rights reserved. // import UIKit import SwiftyJSON struct UserJSONParsingKeys { static let kEmailKey = "email" static let kExpiredAtKey = "expired_at" static let kIdentityKey = "identity" static let kLastLoginedTimeKey = "last_logined_time" static let kRefreshExpiredAtKey = "refresh_expired_at" static let kTokenKey = "token" static let kUserIDKey = "userId" static let kUsernameKey = "username" } enum UserIdentity: Int { case normal = 0 case Admin = 1 } class User: NSObject { let userID: Int! let email: String! let token: String! let username: String! let expiredAt: String! let identity: UserIdentity! let lastLoginedTime: String! let refreshExpiredAt: String! init(JSON: Dictionary<String, JSON>) { self.userID = JSON[UserJSONParsingKeys.kUserIDKey]!.int! self.email = JSON[UserJSONParsingKeys.kEmailKey]!.string! self.token = JSON[UserJSONParsingKeys.kTokenKey]!.string! self.username = JSON[UserJSONParsingKeys.kUsernameKey]!.string! self.expiredAt = JSON[UserJSONParsingKeys.kExpiredAtKey]!.string! self.identity = UserIdentity(rawValue: JSON[UserJSONParsingKeys.kIdentityKey]!.int!) self.lastLoginedTime = JSON[UserJSONParsingKeys.kLastLoginedTimeKey]!.string! self.refreshExpiredAt = JSON[UserJSONParsingKeys.kRefreshExpiredAtKey]!.string! } }
gpl-3.0
fbc3cdc6b5f973c0e434bacb1c82fe72
32.895833
100
0.657037
3.997543
false
false
false
false
lieonCX/Uber
UberRider/UberRider/View/Chat/ContactVC.swift
1
3009
// // ContactVC.swift // UberRider // // Created by lieon on 2017/3/31. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit class ContactVC: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate var contactVM: ContactViewModel = ContactViewModel() @IBAction func backAction(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func addAction(_ sender: Any) { addContact() } override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } extension ContactVC: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contactVM.contacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ContactCell = tableView.dequeueReusableCell(for: indexPath) if indexPath.row <= contactVM.contacts.count - 1 { cell.textLabel?.text = contactVM.contacts[indexPath.row].name } return cell } } extension ContactVC: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let destVC: ChatVC = UIStoryboard.findVC(storyboardName: StoryboardName.chat, identifier: ChatVC.identifier) if indexPath.row <= contactVM.contacts.count - 1 { destVC.tofriendID = contactVM.contacts[indexPath.row].id ?? "" destVC.tofriendName = contactVM.contacts[indexPath.row].name ?? "" navigationController?.pushViewController(destVC, animated: true) } } } extension ContactVC { fileprivate func setupUI() { tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: CellID.contactCellID) tableView.register(UINib(nibName: NibName.contactCell, bundle: nil), forCellReuseIdentifier: ContactCell.identifier) } fileprivate func loadData() { contactVM.getContacts { self.tableView.reloadData() } } fileprivate func addContact() { let alter = UIAlertController(title: "Add A Friend", message: nil, preferredStyle: .alert) alter.addTextField { textFied in textFied.placeholder = "Please enter a valid email" } let enterAction = UIAlertAction(title: "OK", style: .default) { (action) in if let textField = alter.textFields?.first, let email = textField.text { self.contactVM.addConact(email: email, callback: { mesage in self.show(title: "Add Info", message: mesage) }) } } alter.addAction(enterAction) present(alter, animated: true, completion: nil) } }
mit
eb1d9c1909ecccc7382356c15c84a279
31.673913
124
0.643047
4.733858
false
false
false
false
CaryZheng/VaporDemo
Sources/App/Controllers/CryptoController.swift
1
1503
// // CryptoController.swift // App // // Created by CaryZheng on 2018/4/11. // import Vapor import Crypto import Random class CryptoController: RouteCollection { func boot(router: Router) throws { let routes = router.grouped("crypto") routes.get(use: hash) routes.get("hash", String.parameter, use: hash) routes.get("aes128", String.parameter, use: aes128) routes.get("random", use: random) } // hash func hash(_ req: Request) throws -> String { let value = try req.parameters.next(String.self) let hashData = try SHA1.hash(value) let result = hashData.hexEncodedString() return ResponseWrapper(protocolCode: .success, obj: result).makeResponse() } // aes128 func aes128(_ req: Request) throws -> String { let value = try req.parameters.next(String.self) let key = "qwertgfdsa123490" let ciphertext = try AES128.encrypt(value, key: key) let originalData = try AES128.decrypt(ciphertext, key: key) let result = String(data: originalData, encoding: .utf8)! return ResponseWrapper(protocolCode: .success, obj: result).makeResponse() } // random func random(_ req: Request) throws -> String { let randomInt = try OSRandom().generate(UInt8.self) % 100 return ResponseWrapper(protocolCode: .success, obj: randomInt).makeResponse() } }
mit
962a24ab6a17b6566c63739e8f178c4a
27.358491
85
0.610113
4.18663
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/_KeyValueStoreAccess.swift
2
1785
// // _KeyValueStoreAccess.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import PlaygroundSupport import Foundation /// The name of the current page being presented. /// Must be manually set in the pages auxiliary sources. public var pageIdentifier = "" struct KeyValueStoreKey { static let domain = "com.apple.learntocode.customization" static let characterName = "characterNameKey" static var executionCount: String { return "\(pageIdentifier).executionCountKey" } } /** Reads the current page run count from UserDefaults. It relies on the `pageIdentifier` to be correctly set so that the page can be correctly identified. */ public var currentPageRunCount: Int { get { let count = UserDefaults(suiteName: KeyValueStoreKey.domain)?.integer(forKey: KeyValueStoreKey.executionCount) return count ?? 0 } set { if let defaults = UserDefaults(suiteName: KeyValueStoreKey.domain) { defaults.set(newValue, forKey: KeyValueStoreKey.executionCount) defaults.synchronize() } } } extension ActorType { static func loadDefault() -> ActorType { // Return `.byte` as the default if no saved value is found. let fallbackType: ActorType = .byte if let value = UserDefaults(suiteName:KeyValueStoreKey.domain)?.object(forKey: KeyValueStoreKey.characterName) { return ActorType(rawValue: value as! String) ?? fallbackType } return fallbackType } func saveAsDefault() { if let defaults = UserDefaults(suiteName: KeyValueStoreKey.domain) { defaults.set(self.rawValue, forKey:KeyValueStoreKey.characterName) defaults.synchronize() } } }
mit
3e15c921e8034f340aecc676b84d5d29
28.262295
120
0.67395
4.672775
false
false
false
false
sunch001/SCHShareView
SCHShareViewDemo/SCHShareViewDemo/SCHShareView/SCHShareView.swift
1
4684
// // SCHShareView.swift // SCHShareViewDemo // // Created by sundar on 17/7/4. // Copyright © 2017年 sunch. All rights reserved. // import UIKit typealias CompleteClosure = (_ index: Int) ->Void class SCHShareView: UIView { var title: String = "分享至:" var itemSize: CGSize = CGSize.init(width: 50, height: 71) private var closure: CompleteClosure? private var images = [UIImage?]() private var contentView = UIView.init() init() { let frame = UIScreen.main.bounds super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() -> Void { backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) alpha = 0 contentView.backgroundColor = UIColor.white contentView.frame = CGRect.init(x: 0, y: frame.size.height-150, width: frame.size.width, height: 150) addSubview(contentView) let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hideShareViewAction)) addGestureRecognizer(tapGesture) } //显示弹框 func showShareView(images:[UIImage?], closure:CompleteClosure?) { self.images = images self.closure = closure tintColor = UIColor.init(red: 0.486, green: 0.490, blue: 0.494, alpha: 1) UIApplication.shared.keyWindow?.addSubview(self) addShareView() showShareViewAnimate() } private func addShareView() -> Void { //1、标题 let titleLabel = UILabel.init(frame: CGRect.init(x: 20, y: 10, width: 100, height: 30)) titleLabel.text = title titleLabel.textColor = tintColor titleLabel.font = UIFont.systemFont(ofSize: 16) contentView.addSubview(titleLabel) var spaceW: CGFloat = 25.0 let spaceH: CGFloat = 20 let rowCount: NSInteger = (NSInteger)((contentView.frame.size.width-spaceW)/(itemSize.width+spaceW)) spaceW = (contentView.frame.size.width-itemSize.width*CGFloat(rowCount))/(CGFloat(rowCount) + 1.0) for (index, image) in images.enumerated() { let x = spaceW + CGFloat((index % rowCount)) * (itemSize.width + spaceW) let y = titleLabel.frame.maxY + CGFloat(spaceH / 2) + CGFloat((index / rowCount)) * (itemSize.height + spaceH) let frame = CGRect.init(x: x, y: y, width: itemSize.width, height: itemSize.height) let btn = UIButton.init() btn.setBackgroundImage(image, for: .normal) btn.addTarget(self, action: #selector(shareButtonClicked), for: .touchUpInside) btn.tag = index btn.frame = frame contentView.addSubview(btn) if index == images.count-1 { var frame = contentView.frame frame.size.height = btn.frame.maxY+spaceH frame.origin.y = self.frame.size.height-frame.size.height contentView.frame = frame } } } //MARK: 视图显示、隐藏动画 private func showShareViewAnimate() -> Void { contentView.transform = CGAffineTransform.init(translationX: 0, y: contentView.frame.size.height) UIView.animate(withDuration: 0.3) { self.contentView.alpha = 1 self.alpha = 1 self.contentView.transform = CGAffineTransform.identity } } //隐藏视图 @objc private func hideShareViewAction() -> Void { UIView.animate(withDuration: 0.3, animations: { self.contentView.transform = CGAffineTransform.init(translationX: 0, y: self.frame.size.height) self.alpha = 0 }) { (finished) in self.contentView.removeFromSuperview() for (_, view) in self.contentView.subviews.enumerated() { var v: UIView? = view v?.removeFromSuperview() v = nil } self.removeFromSuperview() } } //MARK: 按钮点击事件 @objc private func shareButtonClicked(sender: UIButton) -> Void { if closure != nil { closure!(sender.tag) } hideShareViewAction() } //MARK: deinit deinit { closure = nil } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
apache-2.0
4e08ef06c1060fd5e390bac225959a96
31.556338
122
0.584036
4.402857
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/GroupSettingsViewController.swift
1
15342
// // GroupSettingsViewController.swift // TeacherTools // // Created by Parker Rushton on 12/27/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class GroupSettingsViewController: UITableViewController, AutoStoryboardInitializable { @IBOutlet weak var groupNameLabel: UILabel! @IBOutlet weak var groupNameTextField: UITextField! @IBOutlet weak var lastNameLabel: UILabel! @IBOutlet weak var lastNameSwitch: UISwitch! @IBOutlet weak var exportImageView: UIImageView! @IBOutlet weak var exportLabel: UILabel! @IBOutlet weak var deleteLabel: UILabel! @IBOutlet weak var themeLabel: UILabel! @IBOutlet weak var themeNameLabel: UILabel! @IBOutlet weak var rateLabel: UILabel! @IBOutlet weak var shareLabel: UILabel! @IBOutlet weak var upgradeLabel: UILabel! var core = App.core var group: Group? { return core.state.selectedGroup } fileprivate var saveBarButton = UIBarButtonItem() fileprivate var doneBarButton = UIBarButtonItem() fileprivate var flexy = UIBarButtonItem() fileprivate var toolbarTapRecognizer = UITapGestureRecognizer() fileprivate let appStoreURL = URL(string: "itms-apps://itunes.apple.com/app/id977797579") fileprivate let versionLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() setUp() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) core.remove(subscriber: self) } @IBAction func groupNameTextFieldChanged(_ sender: UITextField) { updateToolbar() } @IBAction func lastNameSwitchChanged(_ sender: UISwitch) { updateLastFirstPreference() } var isNewGroupName: Bool { guard groupNameTextField.isFirstResponder else { return false } guard let text = groupNameTextField.text else { return false } return text != group?.name } var toolbar: UIToolbar = { let toolbar = UIToolbar() toolbar.sizeToFit() toolbar.tintColor = .white toolbar.barTintColor = App.core.state.theme.tintColor return toolbar }() } // MARK: - Subscriber extension GroupSettingsViewController: Subscriber { func update(with state: AppState) { groupNameTextField.text = group?.name lastNameSwitch.isOn = state.currentUser?.lastFirst ?? false themeNameLabel.text = state.theme.name let proText = state.currentUser!.isPro ? "Thanks for upgrading to pro!" : "Upgrade to PRO!" upgradeLabel.text = proText updateUI(with: state.theme) tableView.reloadData() } func updateUI(with theme: Theme) { tableView.backgroundView = theme.mainImage.imageView let borderImage = theme.borderImage.image.stretchableImage(withLeftCapWidth: 0, topCapHeight: 0) navigationController?.navigationBar.setBackgroundImage(borderImage, for: .default) lastNameSwitch.onTintColor = theme.tintColor groupNameTextField.textColor = theme.textColor groupNameTextField.font = theme.font(withSize: 19) exportBarButton.tintColor = theme.tintColor exportImageView.tintColor = theme.textColor for label in [groupNameLabel, lastNameLabel, exportLabel, deleteLabel, themeLabel, themeNameLabel, rateLabel, shareLabel, upgradeLabel] { label?.font = theme.font(withSize: 17) label?.textColor = theme.textColor } upgradeLabel.textColor = core.state.currentUser!.isPro ? theme.textColor : .appleBlue deleteLabel.textColor = .red versionLabel.font = theme.font(withSize: 12) versionLabel.textColor = theme.textColor } } // MARK: Fileprivate extension GroupSettingsViewController { func setUp() { groupNameTextField.inputAccessoryView = toolbar setupToolbar() setUpVersionFooter() } func showThemeSelectionVC() { let themeVC = ThemeSelectionViewController.initializeFromStoryboard() navigationController?.pushViewController(themeVC, animated: true) } func launchAppStore() { guard let appStoreURL = appStoreURL, UIApplication.shared.canOpenURL(appStoreURL) else { core.fire(event: ErrorEvent(error: nil, message: "Error launching app store")) return } UIApplication.shared.open(appStoreURL, options: [:], completionHandler: nil) } func launchShareSheet() { let textToShare = "Check out this great app for teachers called Teacher Tools. You can find it in the app store!" var objectsToShare: [Any] = [textToShare] if let appStoreURL = URL(string: "https://itunes.apple.com/us/app/teacher-tools-tool-for-teachers/id977797579?mt=8") { objectsToShare.append(appStoreURL) } let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, .addToReadingList, .assignToContact, .openInIBooks, .postToTencentWeibo, .postToVimeo, .print, .saveToCameraRoll, .postToWeibo, .postToFlickr] activityVC.modalPresentationStyle = .popover let shareIndexPath = IndexPath(row: TableSection.app.rows.index(of: .share)!, section: TableSection.app.rawValue) activityVC.popoverPresentationController?.sourceRect = tableView.cellForRow(at: shareIndexPath)!.contentView.frame activityVC.popoverPresentationController?.sourceView = tableView.cellForRow(at: shareIndexPath)?.contentView present(activityVC, animated: true, completion: nil) } func showProVC() { let proVC = ProViewController.initializeFromStoryboard().embededInNavigationController proVC.modalPresentationStyle = .popover let proIndexPath = IndexPath(row: TableSection.app.rows.index(of: .pro)!, section: TableSection.app.rawValue) proVC.popoverPresentationController?.sourceRect = tableView.cellForRow(at: proIndexPath)!.contentView.frame proVC.popoverPresentationController?.sourceView = tableView.cellForRow(at: proIndexPath)?.contentView present(proVC, animated: true, completion: nil) } func showAlreadyProAlert() { let alert = UIAlertController(title: "Thanks for purchasing the PRO version", message: "If you haven't already, consider sharing this app with someone who would enjoy it, or rating it on the app store!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Rate", style: .default, handler: { _ in self.launchAppStore() })) alert.addAction(UIAlertAction(title: "Share", style: .default, handler: { _ in self.launchShareSheet() })) alert.addAction(UIAlertAction(title: "Later", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func presentNoDeleteAlert() { let alert = UIAlertController(title: "You won't have any classes left!", message: "You'll have to add a new class first", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func presentDeleteConfirmation() { var message = "This cannot be undone" guard let group = group else { return } if group.studentIds.count > 0 { let studentKey = group.studentIds.count == 1 ? "student" : "students" message = "This class's \(group.studentIds.count) \(studentKey) will also be deleted." } let alert = UIAlertController(title: "Are you sure?", message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { _ in self.core.fire(command: DeleteObject(object: group)) guard let tabBarController = self.tabBarController as? MainTabBarController else { return } tabBarController.selectedIndex = 0 })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func saveClassName() { guard var group = group, let name = groupNameTextField.text else { core.fire(event: ErrorEvent(error: nil, message: "Error saving class")) return } let shouldSave = name.isEmpty == false && name != group.name if shouldSave { group.name = name core.fire(command: UpdateObject(object: group)) core.fire(event: DisplaySuccessMessage(message: "Saved!")) } else { groupNameTextField.text = group.name } groupNameTextField.resignFirstResponder() } @objc func toolbarTapped() { if isNewGroupName { saveClassName() } else { doneButtonPressed() } } @objc func doneButtonPressed() { view.endEditing(true) } func setupToolbar() { flexy = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: #selector(toolbarTapped)) saveBarButton = UIBarButtonItem(title: NSLocalizedString("Save", comment: ""), style: .plain, target: self, action: #selector(saveClassName)) doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneButtonPressed)) saveBarButton.setTitleTextAttributes([NSAttributedString.Key.font: core.state.theme.font(withSize: 20)], for: .normal) toolbarTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(toolbarTapped)) toolbar.addGestureRecognizer(toolbarTapRecognizer) toolbar.setItems([flexy, saveBarButton, flexy], animated: false) updateToolbar() } func updateToolbar() { let items = isNewGroupName ? [flexy, saveBarButton, flexy] : [flexy, doneBarButton] toolbar.setItems(items, animated: false) } func updateLastFirstPreference() { guard let user = core.state.currentUser else { core.fire(event: NoOp()) return } user.lastFirst = lastNameSwitch.isOn core.fire(command: UpdateUser(user: user)) } fileprivate func showExportShareSheet() { let textToShare = Exporter.exportStudentList(state: core.state) let objectsToShare: [Any] = [textToShare] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, .addToReadingList, .assignToContact, .openInIBooks, .postToTencentWeibo, .postToVimeo, .print, .saveToCameraRoll, .postToWeibo, .postToFlickr] activityVC.modalPresentationStyle = .popover activityVC.popoverPresentationController?.barButtonItem = exportBarButton present(activityVC, animated: true, completion: nil) } fileprivate func setUpVersionFooter() { versionLabel.frame = CGRect(x: 0, y: -2, width: view.frame.size.width * 0.95, height: 20) versionLabel.font = core.state.theme.font(withSize: 12) versionLabel.textColor = core.state.theme.textColor versionLabel.textAlignment = .right versionLabel.text = versionDescription let footerView = UIView() footerView.addSubview(versionLabel) tableView.tableFooterView = footerView } fileprivate var versionDescription: String { let versionDescription = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String var version = "3.1" if let versionString = versionDescription { version = versionString } return "version: \(version)" } } // MARK: - UITextFieldDelegate extension GroupSettingsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { updateToolbar() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { saveClassName() return true } } // MARK: - UITableViewDelegate extension GroupSettingsViewController { enum TableSection: Int { case group case app var rows: [TableRow] { switch self { case .group: return [.className, .lastFirst, .export, .delete] case .app: return [.theme, .rate, .share, .pro] } } } enum TableRow { case className case lastFirst case export case delete case theme case rate case share case pro } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Platform.isPad || UIDevice.current.type.isPlusSize ? 60 : 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = core.state.theme.tintColor let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = core.state.theme.font(withSize: 17) label.textColor = core.state.theme.isDefault ? .white : core.state.theme.textColor label.textAlignment = .center headerView.addSubview(label) headerView.addConstraint(headerView.centerYAnchor.constraint(equalTo: label.centerYAnchor)) headerView.addConstraint(headerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: label.leadingAnchor)) headerView.addConstraint(headerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: label.trailingAnchor)) switch TableSection(rawValue: section)! { case .group: label.text = "Class Settings" case .app: label.text = "App Settings" } return headerView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = TableSection(rawValue: indexPath.section)! let row = section.rows[indexPath.row] switch row { case .className: groupNameTextField.becomeFirstResponder() case .lastFirst: lastNameSwitch.isOn = !lastNameSwitch.isOn lastNameSwitchChanged(lastNameSwitch) case .export: showExportShareSheet() case .delete: presentDeleteConfirmation() case .theme: showThemeSelectionVC() case .rate: launchAppStore() case .share: launchShareSheet() case .pro: guard let currentUser = core.state.currentUser, currentUser.isPro else { showProVC() return } showAlreadyProAlert() } } }
mit
e3709266040ef622943172ef61d4545d
38.437018
235
0.663516
5.028187
false
false
false
false
naokuro/sticker
Carthage/Checkouts/RapidFire/RapidFireTests/UtilTests.swift
1
2440
// // UtilTests.swift // RapidFireTests // // Created by keygx on 2016/11/19. // Copyright © 2016年 keygx. All rights reserved. // import XCTest @testable import RapidFire class UtilTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func test_toJsonDictionary() { let json: [String: Any] = ["a":1, "b":"あ"] let testData = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) XCTAssertEqual(RapidFire.Util.toDictionary(from: testData)["a"] as? Int, 1) XCTAssertEqual(RapidFire.Util.toDictionary(from: testData)["b"] as? String, "あ") XCTAssertEqual(RapidFire.Util.toDictionary(from: nil).count, 0) XCTAssertNotEqual(RapidFire.Util.toDictionary(from: testData)["a"] as? Int, 1000) XCTAssertNotEqual(RapidFire.Util.toDictionary(from: testData)["b"] as? String, "ん") } func test_toJsonArray() { let json: [[String: Any]] = [["a":1, "b":"あ"], ["a":1000, "b":"い"]] let testData = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) XCTAssertEqual(RapidFire.Util.toArray(from: testData)[0]["a"] as? Int, 1) XCTAssertEqual(RapidFire.Util.toArray(from: testData)[0]["b"] as? String, "あ") XCTAssertEqual(RapidFire.Util.toArray(from: testData)[1]["a"] as? Int, 1000) XCTAssertEqual(RapidFire.Util.toArray(from: testData)[1]["b"] as? String, "い") XCTAssertEqual(RapidFire.Util.toArray(from: nil).count, 0) XCTAssertNotEqual(RapidFire.Util.toArray(from: testData)[0]["a"] as? Int, 1000) XCTAssertNotEqual(RapidFire.Util.toArray(from: testData)[0]["b"] as? String, "ん") } func test_toString() { let str = "RapidFire" let testData = str.data(using: String.Encoding.utf8) XCTAssertEqual(RapidFire.Util.toString(from: testData), str) XCTAssertEqual(RapidFire.Util.toString(from: nil), "") XCTAssertNotEqual(RapidFire.Util.toString(from: testData), "foo bar") } func test_toJSON() { let testData: [[String: Any]] = [["a":1, "b":"あ"], ["a":1000, "b":"い"]] let json = try! JSONSerialization.data(withJSONObject: testData, options: .prettyPrinted) XCTAssertEqual(RapidFire.Util.toJSON(from: testData), json) } }
mit
3d4b3d0c8da250281ad28b337c31c7a7
38.622951
97
0.629293
3.842607
false
true
false
false
Zane6w/MoreColorButton
ColorfulButton/ColorfulButton/ViewController.swift
1
6707
//// //// ViewController.swift //// ColorfulButton //// //// Created by zhi zhou on 2017/1/19. //// Copyright © 2017年 zhi zhou. All rights reserved. //// // //import UIKit // //class ViewController: UIViewController { // // MARK:- 属性 // @IBOutlet weak var colorBtn: ColorfulButton! // @IBOutlet weak var topBtn: ColorfulButton! // @IBOutlet weak var bottomBtn: ColorfulButton! // var btnArr = [ColorfulButton]() // // var chooseBtn: ColorfulButton? // // var effectView: UIVisualEffectView? // //var remarksVC: RemarksController? // // /// 标记触发的按钮 // var sign: UIButton? // /// 语言判断 // var isHanLanguage: Bool { // // 判断系统当前语言 // let languages = Locale.preferredLanguages // let currentLanguage = languages[0] // // 判断是否是中文, 根据语言设置字体样式 // if currentLanguage.hasPrefix("zh") { // return true // } else { // return false // } // } // // // MARK:- 系统函数 // override func viewDidLoad() { // super.viewDidLoad() // // print(SQLite.shared.dataSize()) // // btnArr = [colorBtn, topBtn, bottomBtn] // colorBtn.id = "111" // topBtn.id = "222" // bottomBtn.id = "333" // // // for btn in btnArr { // btn.buttonTapHandler = { (button) in // if button.dataStr != nil { // _ = SQLite.shared.update(id: button.id!, status: "\(button.bgStatus)", remark: "\(button.dataStr!)", inTable: "t_buttons") // } else { // _ = SQLite.shared.update(id: button.id!, status: "\(button.bgStatus)", remark: "", inTable: "t_buttons") // } // } // // let array = SQLite.shared.query(inTable: "t_buttons", id: btn.id!) // if array?.count == 0 { // if btn.dataStr != nil { // _ = SQLite.shared.insert(id: btn.id!, status: "\(btn.bgStatus)", remark: "\(btn.dataStr!)", inTable: "t_buttons") // } else { // _ = SQLite.shared.insert(id: btn.id!, status: "\(btn.bgStatus)", remark: "", inTable: "t_buttons") // } // } else { // let array = SQLite.shared.query(inTable: "t_buttons", id: btn.id!) // // let id = array?[0] as! String // let status = array?[1] as! String // let remark = array?[2] as! String // print(status) // if btn.id! == id { // let statusType = StatusType(rawValue: status)! // btn.bgStatus = statusType // // opinionIndicator(button: btn, text: remark) // // btn.dataStr = remark // } // } // // } // // setupInterface() // // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // } // //} // //// MARK:- 界面设置 //extension ViewController { // fileprivate func setupInterface() { // // 添加备注时, 显示蒙版 // for btn in btnArr { // let remarksVC = RemarksController() // btn.remarksTapHandler = { (button) in // self.setupBlur() // self.chooseBtn = button // // if button.dataStr != nil { // remarksVC.textView.text = button.dataStr! // } // // UIView.animate(withDuration: 0.3, animations: { // self.effectView?.alpha = 1.0 // // remarksVC.modalPresentationStyle = .custom // self.present(remarksVC, animated: true, completion: nil) // }) // } // // // 取消备注后隐藏蒙版 // remarksVC.cancelTapHandler = { (vc) in // UIView.animate(withDuration: 0.3) { // self.effectView?.alpha = 0 // } // } // // remarksVC.pinTapHandler = { (vc, text) in // UIView.animate(withDuration: 0.3) { // self.effectView?.alpha = 0 // } // // self.chooseBtn?.dataStr = text! // // _ = SQLite.shared.update(id: (self.chooseBtn?.id)!, status: "\((self.chooseBtn?.bgStatus)!)", remark: text!, inTable: "t_buttons") // // if let text = text, let chooseBtn = self.chooseBtn { // self.opinionIndicator(button: chooseBtn, text: text) // } // } // // } // // }// // // /// 按钮备注标识与菜单名称 // fileprivate func opinionIndicator(button: ColorfulButton, text: String) { // if text != "" { // button.indicator.isHidden = false // // // 判断系统当前语言 // if isHanLanguage { // button.remarksTitle = "编辑备注" // } else { // button.remarksTitle = "Edit Note" // } // // button.reloadMenu() // } else { // // // 判断系统当前语言 // if isHanLanguage { // button.remarksTitle = "添加备注" // } else { // button.remarksTitle = "Add Note" // } // // button.indicator.isHidden = true // button.reloadMenu() // } // } // //} // //// MARK:- 手势相关 //extension ViewController: UIGestureRecognizerDelegate { // /// 点击菜单备注弹出窗口 // fileprivate func setupBlur() { // let effect = UIBlurEffect(style: .dark) // effectView = UIVisualEffectView(effect: effect) // effectView?.frame = UIScreen.main.bounds // effectView?.alpha = 0 // view.addSubview(effectView!) // setupTapGesture(effectView!) // } // // fileprivate func setupTapGesture(_ effectView: UIVisualEffectView) { // let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap(tap:))) // tapGesture.delegate = self // effectView.addGestureRecognizer(tapGesture) // } // // @objc fileprivate func tap(tap: UITapGestureRecognizer) { // UIView.animate(withDuration: 0.3) { // self.effectView?.alpha = 0 // } // } // //}
apache-2.0
7fb3b803552fbed2983986889a25338c
32.220513
148
0.466193
3.916566
false
false
false
false
colemancda/NetworkObjects
Source/ResponseMessage.swift
1
6017
// // ResponseMessage.swift // NetworkObjects // // Created by Alsey Coleman Miller on 9/2/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import SwiftFoundation import CoreModel public struct ResponseMessage: JSONEncodable, JSONParametrizedDecodable { public var metadata: [String: String] public var response: Response public init(_ response: Response, metadata: [String: String] = [:]) { self.response = response self.metadata = metadata } } // MARK: - JSON private extension ResponseMessage { private enum JSONKey: String { case Metadata case Response case Error } } public extension ResponseMessage { /// Decode from JSON. public init?(JSONValue: JSON.Value, parameters: (type: RequestType, entity: Entity)) { let type = parameters.type let entity = parameters.entity guard let jsonObject = JSONValue.objectValue, let metadata = jsonObject[JSONKey.Metadata.rawValue]?.rawValue as? [String: String] else { return nil } self.metadata = metadata guard jsonObject[JSONKey.Error.rawValue] == nil else { guard let errorStatusCode = jsonObject[JSONKey.Error.rawValue]?.rawValue as? Int else { return nil } self.response = Response.Error(errorStatusCode) return } guard let responseJSON = jsonObject[JSONKey.Response.rawValue], let response = { switch type { case .Get: // parse response guard let valuesJSONObect = responseJSON.objectValue, let values = entity.convert(valuesJSONObect) else { return nil } return Response.Get(values) case .Edit: // parse response guard let valuesJSONObect = responseJSON.objectValue, let values = entity.convert(valuesJSONObect) else { return nil } return Response.Edit(values) case .Delete: /// Cant be created from JSON return nil case .Create: // parse response guard let responseJSONObject = responseJSON.objectValue where responseJSONObject.count == 1, let (resourceID, valuesJSON) = responseJSONObject.first, let valuesJSONObect = valuesJSON.objectValue, let values = entity.convert(valuesJSONObect) else { return nil } return Response.Create(resourceID, values) case .Search: guard let resourceIDs = responseJSON.rawValue as? [String] else { return nil } return Response.Search(resourceIDs) case .Function: let functionJSON: JSONObject? switch responseJSON { case .Null: functionJSON = nil case let .Object(value): functionJSON = value default: return nil } return Response.Function(functionJSON) } }() as Response? else { return nil } self.response = response } public func toJSON() -> JSON.Value { var jsonObject = JSON.Object() let metaDataJSONObject: JSONObject = { var jsonObject = JSONObject() for (key, value) in self.metadata { jsonObject[key] = JSON.Value.String(value) } return jsonObject }() jsonObject[JSONKey.Metadata.rawValue] = JSON.Value.Object(metaDataJSONObject) switch self.response { case let .Get(values): let jsonValues = JSON.fromValues(values) jsonObject[JSONKey.Response.rawValue] = JSON.Value.Object(jsonValues) case let .Edit(values): let jsonValues = JSON.fromValues(values) jsonObject[JSONKey.Response.rawValue] = JSON.Value.Object(jsonValues) case .Delete: break case let .Create(resourceID, values): let jsonValues = JSON.fromValues(values) let createJSONObject = [resourceID: JSON.Value.Object(jsonValues)] jsonObject[JSONKey.Response.rawValue] = JSON.Value.Object(createJSONObject) case let .Search(resourceIDs): var jsonArray = JSON.Array() for resourceID in resourceIDs { let jsonValue = JSON.Value.String(resourceID) jsonArray.append(jsonValue) } jsonObject[JSONKey.Response.rawValue] = JSON.Value.Array(jsonArray) case let .Function(functionJSONObject): if let functionJSONObject = functionJSONObject { jsonObject[JSONKey.Response.rawValue] = JSON.Value.Object(functionJSONObject) } case let .Error(errorCode): jsonObject[JSONKey.Error.rawValue] = JSON.Value.Number(.Integer(errorCode)) } return JSON.Value.Object(jsonObject) } }
mit
5ee954f2faa2581105999f79ad81e446
29.383838
95
0.496509
6.003992
false
false
false
false
KrishMunot/swift
test/DebugInfo/typealias.swift
3
969
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(_ t: T) {} class DWARF { // CHECK-DAG: ![[DIEOFFSET:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_TtaC9typealias5DWARF9DIEOffset",{{.*}} line: [[@LINE+1]], baseType: !"_TtVs6UInt32") typealias DIEOffset = UInt32 // CHECK-DAG: ![[PRIVATETYPE:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_TtaC9typealias5DWARFP{{.+}}11PrivateType",{{.*}} line: [[@LINE+1]], baseType: !"_TtT_") private typealias PrivateType = () private static func usePrivateType() -> PrivateType { return () } } func main () { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} type: ![[DIEOFFSET]] var a : DWARF.DIEOffset = 123 markUsed(a) // CHECK-DAG: !DILocalVariable(name: "b",{{.*}} type: ![[DIEOFFSET]] var b = DWARF.DIEOffset(456) as DWARF.DIEOffset markUsed(b) // CHECK-DAG: !DILocalVariable(name: "c",{{.*}} type: ![[PRIVATETYPE]] let c = DWARF.usePrivateType() } main();
apache-2.0
63e589e65e402db163bbc91a1431c43d
37.76
169
0.632611
3.23
false
false
false
false
Wakup/Wakup-iOS-SDK
WakupDemo/WakupDemo/OffersWidgetView.swift
1
10073
// // OffersWidgetView.swift // WakupDemo // // Created by Guillermo Gutiérrez Doral on 27/10/16. // Copyright © 2016 Yellow Pineapple. All rights reserved. // import Foundation import UIKit import Wakup import CoreLocation import DZNEmptyDataSet enum Status { case idle case loading case fetchingLocation case locationFailed(error: Error) case offersFailed(error: Error) case permissionDenied case awaitingPermission } @objc open class OffersWidgetView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, CLLocationManagerDelegate { @IBInspectable public var offerCellNib: String? @IBInspectable public var offerCellId = "cellId" @IBOutlet open var collectionView: UICollectionView! @IBOutlet open var pageControl: UIPageControl! var onOfferSelected: ((Coupon) -> Void)? public var offers = [Coupon]() { didSet { pageControl?.numberOfPages = offers.count } } var location: CLLocation? var locationTimestamp: Date? var locationExpirationTime: TimeInterval = 5 * 60 var locationExpired: Bool { get { if let timestamp = locationTimestamp { let elapsedTime = -timestamp.timeIntervalSinceNow return elapsedTime > locationExpirationTime } return true } } var status: Status = .idle { didSet { self.collectionView?.reloadEmptyDataSet() } } private let locationManager = CLLocationManager() func fetchOffers() { guard let location = location else { return } status = .loading offers = [Coupon]() collectionView.reloadData() OffersService.sharedInstance.findOffers(usingLocation: location.coordinate, sensor: true, pagination: PaginationInfo(perPage: 5)) { offers, error in self.status = .loading if let error = error { print("Error loading offers: ", error) self.status = .offersFailed(error: error) } else if let offers = offers { self.offers = offers self.collectionView.reloadData() self.status = .idle } } } func fetchLocation() { self.status = .fetchingLocation locationManager.requestWhenInUseAuthorization() locationManager.delegate = self locationManager.stopUpdatingLocation() locationManager.startUpdatingLocation() } func fetchLocationIfAvailable() { guard offers.isEmpty || locationExpired else { return } switch CLLocationManager.authorizationStatus() { case .authorizedAlways, .authorizedWhenInUse: fetchLocation() case .notDetermined: status = .awaitingPermission case .denied, .restricted: status = .permissionDenied @unknown default: status = .permissionDenied } } func configure(withParentController parentVC: UIViewController) { onOfferSelected = { [weak self] offer in print("Selected offer \(offer)") guard let sself = self else { return } let detailsVC = WakupManager.manager.offerDetailsController(forOffer: offer, userLocation: sself.location, offers: sself.offers)! sself.collectionView.contentInsetAdjustmentBehavior = .never let navicationController = WakupManager.manager.rootNavigationController()! navicationController.viewControllers = [detailsVC] parentVC.present(navicationController, animated: true, completion: nil) } } func openAppSettings() { guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil) } // MARK: - UIView open override func awakeFromNib() { super.awakeFromNib() if let offerCellNib = offerCellNib { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: offerCellNib, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: offerCellId) } collectionView.emptyDataSetSource = self collectionView.emptyDataSetDelegate = self collectionView.reloadData() pageControl?.numberOfPages = 0 } override open func layoutSubviews() { super.layoutSubviews() // Adjust collection view margins and item size to new frame size guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return } let height = frame.height - layout.sectionInset.top - layout.sectionInset.bottom let width = frame.width - layout.minimumLineSpacing layout.itemSize = CGSize(width: width, height: height) } // MARK: - UICollectionViewDataSource public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return offers.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: offerCellId, for: indexPath) if let cell = cell as? CouponCollectionViewCell { cell.coupon = offers[indexPath.row] } return cell } // MARK: - UICollectionViewDelegate public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let offer = offers[indexPath.row] onOfferSelected?(offer) } // MARK: - UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl?.currentPage = Int(Double(scrollView.contentOffset.x / scrollView.frame.width) + 0.5) } // MARK: - CLLocationManagerDelegate public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last locationTimestamp = Date() fetchOffers() manager.delegate = nil manager.stopUpdatingLocation() } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { NSLog("Error obtaining location: %@", error.localizedDescription) let locationDenied = CLLocationManager.authorizationStatus() == .denied status = locationDenied ? .permissionDenied : .locationFailed(error: error) } // MARK: - DZNEmptyDataSetSource public func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { var text: String? switch status { case .locationFailed: text = "LOCATION_ERROR_TITLE" case .permissionDenied: text = "LOCATION_PERMISSION_ERROR_TITLE" case .offersFailed: text = "OFFERS_SERVER_ERROR_TITLE" case .awaitingPermission: text = "AWAITING_PERMISSION_TITLE" case .idle: text = "NO_OFFERS_TITLE" default: break } return text.map { NSAttributedString(string: NSLocalizedString($0, comment: "")) } } public func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { var text: String? switch status { case .locationFailed: text = "LOCATION_ERROR_DESC" case .permissionDenied: text = "LOCATION_PERMISSION_ERROR_DESC" case .offersFailed: text = "OFFERS_SERVER_ERROR_DESC" case .awaitingPermission: text = "AWAITING_PERMISSION_DESC" case .idle: text = "NO_OFFERS_DESC" default: break } return text.map { NSAttributedString(string: NSLocalizedString($0, comment: "")) } } public func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> NSAttributedString! { var text: String? switch status { case .locationFailed: text = "LOCATION_ERROR_ACTION" case .permissionDenied: text = "LOCATION_PERMISSION_ERROR_ACTION" case .offersFailed: text = "OFFERS_SERVER_ERROR_ACTION" case .awaitingPermission: text = "AWAITING_PERMISSION_ACTION" case .idle: text = "NO_OFFERS_ACTION" default: break } let attrs = [NSAttributedString.Key.foregroundColor: UIColor.lightGray] return text.map { NSAttributedString(string: NSLocalizedString($0, comment: ""), attributes: attrs) } } public func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! { switch status { case .loading, .fetchingLocation: let view = UIActivityIndicatorView(style: .gray) view.startAnimating() return view default: return nil } } // MARK: - DZNEmptyDataSetDelegate public func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) { switch status { case .permissionDenied, .awaitingPermission, .locationFailed, .idle, .offersFailed where location == nil: fetchLocation() case .offersFailed: fetchOffers() default: break } } public func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) { switch status { case .permissionDenied: openAppSettings() case .awaitingPermission, .locationFailed, .idle, .offersFailed where location == nil: fetchLocation() case .offersFailed: fetchOffers() default: break } } }
mit
0a3efb92382df0d99b09338453faa8b9
35.226619
166
0.634793
5.43497
false
false
false
false
syedabsar/ios-nytimes-mostpopular
Pods/AZDropdownMenu/Pod/Classes/AZDropdownMenuBaseCell.swift
2
1154
// // AZDropdownMenuBaseCell.swift // Pods // // Created by Chris Wu on 01/15/2016. // Copyright (c) 2016 Chris Wu. All rights reserved. // import Foundation open class AZDropdownMenuBaseCell : UITableViewCell, AZDropdownMenuCellProtocol { open func configureData(_ data: AZDropdownMenuItemData) { self.textLabel?.text = data.title } func configureStyle(_ config: AZDropdownMenuConfig) { self.selectionStyle = .none self.backgroundColor = config.itemColor self.textLabel?.textColor = config.itemFontColor self.textLabel?.font = UIFont(name: config.itemFont, size: config.itemFontSize) switch config.itemAlignment { case .left: self.textLabel?.textAlignment = .left case .right: self.textLabel?.textAlignment = .right case .center: self.textLabel?.textAlignment = .center } } } protocol AZDropdownMenuCellProtocol { func configureData(_ data: AZDropdownMenuItemData) func configureStyle(_ configuration:AZDropdownMenuConfig) } public enum AZDropdownMenuItemAlignment { case left, right, center }
mit
68f595e28839a939c53718c47cdb35cd
27.146341
87
0.683709
4.653226
false
true
false
false
carping/Postal
Postal/MimeType+Parsing.swift
1
7411
// // The MIT License (MIT) // // Copyright (c) 2017 Snips // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import libetpan public struct MimeType { public let type: String public let subtype: String public init(type: String, subtype: String) { self.type = type.lowercased() self.subtype = subtype.lowercased() } } extension MimeType: Hashable { public var hashValue: Int { return 31 &* type.hash &+ subtype.hash } } public func ==(lhs: MimeType, rhs: MimeType) -> Bool { return lhs.type == rhs.type && lhs.subtype == rhs.subtype } extension MimeType: CustomStringConvertible { public var description: String { return "\(type)/\(subtype)" } } public extension MimeType { static var applicationJavascript: MimeType { return MimeType(type: "application", subtype: "javascript") } static var applicationOctetStream: MimeType { return MimeType(type: "application", subtype: "octet-stream") } static var applicationOgg: MimeType { return MimeType(type: "application", subtype: "ogg") } static var applicationPdf: MimeType { return MimeType(type: "application", subtype: "pdf") } static var applicationXhtml: MimeType { return MimeType(type: "application", subtype: "xhtml+xml") } static var applicationFlash: MimeType { return MimeType(type: "application", subtype: "x-shockwave-flash") } static var applicationJson: MimeType { return MimeType(type: "application", subtype: "json") } static var applicationXml: MimeType { return MimeType(type: "application", subtype: "xml") } static var applicationZip: MimeType { return MimeType(type: "application", subtype: "zip") } static var audioMpeg: MimeType { return MimeType(type: "audio", subtype: "mpeg") } static var audioMp3: MimeType { return MimeType(type: "audio", subtype: "mp3") } static var audioWma: MimeType { return MimeType(type: "audio", subtype: "x-ms-wma") } static var audioWav: MimeType { return MimeType(type: "audio", subtype: "x-wav") } static var imageGif: MimeType { return MimeType(type: "image", subtype: "jpeg") } static var imageJpeg: MimeType { return MimeType(type: "image", subtype: "jpeg") } static var imagePng: MimeType { return MimeType(type: "image", subtype: "jpeg") } static var imageTiff: MimeType { return MimeType(type: "image", subtype: "jpeg") } static var imageIcon: MimeType { return MimeType(type: "image", subtype: "x-icon") } static var imageSvg: MimeType { return MimeType(type: "image", subtype: "svg+xml") } static var multipartMixed: MimeType { return MimeType(type: "multipart", subtype: "mixed") } static var multipartAlternative: MimeType { return MimeType(type: "multipart", subtype: "alternative") } static var multipartRelated: MimeType { return MimeType(type: "multipart", subtype: "related") } static var textCss: MimeType { return MimeType(type: "text", subtype: "css") } static var textCsv: MimeType { return MimeType(type: "text", subtype: "csv") } static var textHtml: MimeType { return MimeType(type: "text", subtype: "html") } static var textJavascript: MimeType { return MimeType(type: "text", subtype: "javascript") } static var textPlain: MimeType { return MimeType(type: "text", subtype: "plain") } static var textXml: MimeType { return MimeType(type: "text", subtype: "xml") } static var videoMpeg: MimeType { return MimeType(type: "video", subtype: "mpeg") } static var videoMp4: MimeType { return MimeType(type: "video", subtype: "mp4") } static var videoQuicktime: MimeType { return MimeType(type: "video", subtype: "quicktime") } static var videoWmv: MimeType { return MimeType(type: "video", subtype: "x-ms-wmv") } static var videoAvi: MimeType { return MimeType(type: "video", subtype: "x-msvideo") } static var videoFlv: MimeType { return MimeType(type: "video", subtype: "x-flv") } static var videoWebm: MimeType { return MimeType(type: "video", subtype: "webm") } } // MARK: IMAP Parsing extension mailimap_media_basic { var parse: MimeType? { let subtype = String(cString: med_subtype).lowercased() switch Int(med_type) { case MAILIMAP_MEDIA_BASIC_APPLICATION: return MimeType(type: "application", subtype: subtype) case MAILIMAP_MEDIA_BASIC_AUDIO: return MimeType(type: "audio", subtype: subtype) case MAILIMAP_MEDIA_BASIC_IMAGE: return MimeType(type: "image", subtype: subtype) case MAILIMAP_MEDIA_BASIC_MESSAGE: return MimeType(type: "message", subtype: subtype) case MAILIMAP_MEDIA_BASIC_VIDEO: return MimeType(type: "video", subtype: subtype) case MAILIMAP_MEDIA_BASIC_OTHER: return String.fromUTF8CString(med_basic_type).map { MimeType(type: $0, subtype: subtype) } default: return nil } } } // MARK: IMF Parsing extension mailmime_content { var parse: MimeType { let type: String = ct_type?.pointee.parse ?? "unknown" let subtype = String.fromUTF8CString(ct_subtype)?.lowercased() ?? "unknown" return MimeType(type: type, subtype: subtype) } } extension mailmime_type { var parse: String? { switch Int(tp_type) { case MAILMIME_TYPE_DISCRETE_TYPE: return tp_data.tp_discrete_type?.pointee.parse case MAILMIME_TYPE_COMPOSITE_TYPE: return tp_data.tp_composite_type?.pointee.parse default: return nil } } } extension mailmime_composite_type { var parse: String? { switch Int(ct_type) { case MAILMIME_COMPOSITE_TYPE_MESSAGE: return "message" case MAILMIME_COMPOSITE_TYPE_MULTIPART: return "multipart" case MAILMIME_COMPOSITE_TYPE_EXTENSION: return String.fromUTF8CString(ct_token)?.lowercased() default: return nil } } } extension mailmime_discrete_type { var parse: String? { switch Int(dt_type) { case MAILMIME_DISCRETE_TYPE_TEXT: return "text" case MAILMIME_DISCRETE_TYPE_IMAGE: return "image" case MAILMIME_DISCRETE_TYPE_AUDIO: return "audio" case MAILMIME_DISCRETE_TYPE_VIDEO: return "video" case MAILMIME_DISCRETE_TYPE_APPLICATION: return "application" case MAILMIME_DISCRETE_TYPE_EXTENSION: return String.fromUTF8CString(dt_extension)?.lowercased() default: return nil } } }
mit
afbfdf20fd83ea26487d95c4d94a0cf7
46.812903
131
0.694373
3.925318
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Settings/SettingsNavigationController.swift
2
1694
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class ThemedNavigationController: UINavigationController { var presentingModalViewControllerDelegate: PresentingModalViewControllerDelegate? @objc func done() { if let delegate = presentingModalViewControllerDelegate { delegate.dismissPresentedModalViewController(self, animated: true) } else { self.dismiss(animated: true, completion: nil) } } override var preferredStatusBarStyle: UIStatusBarStyle { return ThemeManager.instance.statusBarStyle } override func viewDidLoad() { super.viewDidLoad() modalPresentationStyle = .formSheet applyTheme() } } extension ThemedNavigationController: Themeable { func applyTheme() { navigationBar.barTintColor = UIColor.theme.tableView.headerBackground navigationBar.tintColor = UIColor.theme.general.controlTint navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextDark] setNeedsStatusBarAppearanceUpdate() viewControllers.forEach { ($0 as? Themeable)?.applyTheme() } } } protocol PresentingModalViewControllerDelegate: AnyObject { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) } class ModalSettingsNavigationController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .default } }
mpl-2.0
1b452455978199bf9a0b5aea4ebfad97
33.571429
124
0.727273
5.861592
false
false
false
false
cemolcay/YSCards
Pods/ALKit/ALKit/ALKit/ALKit.swift
1
5472
// // ALKit.swift // AutolayoutPlayground // // Created by Cem Olcay on 22/10/15. // Copyright © 2015 prototapp. All rights reserved. // // https://www.github.com/cemolcay/ALKit // import UIKit extension UIEdgeInsets { init (inset: CGFloat) { top = inset bottom = inset left = inset right = inset } } extension UIView{ convenience init (withAutolayout: Bool) { self.init(frame: CGRect.zero) translatesAutoresizingMaskIntoConstraints = false } class func AutoLayout() -> UIView { let view = UIView(frame: CGRect.zero) view.translatesAutoresizingMaskIntoConstraints = false return view } func pin( inView inView: UIView? = nil, edge: NSLayoutAttribute, toEdge: NSLayoutAttribute, ofView: UIView?, withInset: CGFloat = 0) { let view = inView ?? ofView ?? self view.addConstraint(NSLayoutConstraint( item: self, attribute: edge, relatedBy: .Equal, toItem: ofView, attribute: toEdge, multiplier: 1, constant: withInset)) } // Pin func pinRight(inView inView: UIView? = nil, toView: UIView, withInset: CGFloat = 0) { pin(inView: inView, edge: .Right, toEdge: .Right, ofView: toView, withInset: -withInset) } func pinLeft(inView inView: UIView? = nil, toView: UIView, withInset: CGFloat = 0) { pin(inView: inView, edge: .Left, toEdge: .Left, ofView: toView, withInset: withInset) } func pinTop(inView inView: UIView? = nil, toView: UIView, withInset: CGFloat = 0) { pin(inView: inView, edge: .Top, toEdge: .Top, ofView: toView, withInset: withInset) } func pinBottom(inView inView: UIView? = nil, toView: UIView, withInset: CGFloat = 0) { pin(inView: inView, edge: .Bottom, toEdge: .Bottom, ofView: toView, withInset: -withInset) } // Pin To func pinToRight(inView inView: UIView? = nil, toView: UIView, withOffset: CGFloat = 0) { pin(inView: inView, edge: .Left, toEdge: .Right, ofView: toView, withInset: withOffset) } func pinToLeft(inView inView: UIView? = nil, toView: UIView, withOffset: CGFloat = 0) { pin(inView: inView, edge: .Right, toEdge: .Left, ofView: toView, withInset: -withOffset) } func pinToTop(inView inView: UIView? = nil, toView: UIView, withOffset: CGFloat = 0) { pin(inView: inView, edge: .Bottom, toEdge: .Top, ofView: toView, withInset: -withOffset) } func pinToBottom(inView inView: UIView? = nil, toView: UIView, withOffset: CGFloat = 0) { pin(inView: inView, edge: .Top, toEdge: .Bottom, ofView: toView, withInset: withOffset) } // Fill func fill(toView view: UIView, withInset: UIEdgeInsets = UIEdgeInsetsZero) { pinLeft(toView: view, withInset: withInset.left) pinRight(toView: view, withInset: withInset.right) pinTop(toView: view, withInset: withInset.top) pinBottom(toView: view, withInset: withInset.bottom) } func fillHorizontal(toView view: UIView, withInset: CGFloat = 0) { pinRight(toView: view, withInset: withInset) pinLeft(toView: view, withInset: withInset) } func fillVertical(toView view: UIView, withInset: CGFloat = 0) { pinTop(toView: view, withInset: withInset) pinBottom(toView: view, withInset: withInset) } // Size func pinSize(width width: CGFloat, height: CGFloat) { pinWidht(width) pinHeight(height) } func pinWidht(width: CGFloat) { pin(edge: .Width, toEdge: .NotAnAttribute, ofView: nil, withInset: width) } func pinHeight(height: CGFloat) { pin(edge: .Height, toEdge: .NotAnAttribute, ofView: nil, withInset: height) } // Center func pinCenter(toView view: UIView) { pinCenterX(toView: view) pinCenterY(toView: view) } func pinCenterX(toView view: UIView) { pin(edge: .CenterX, toEdge: .CenterX, ofView: view) } func pinCenterY(toView view: UIView) { pin(edge: .CenterY, toEdge: .CenterY, ofView: view) } } class ALScrollView: UIView { private var scrollView: UIScrollView! private var contentView: UIView! init () { super.init(frame: CGRect.zero) translatesAutoresizingMaskIntoConstraints = false scrollView = UIScrollView(withAutolayout: true) scrollView.fill(toView: self) addSubview(scrollView) contentView = UIView(withAutolayout: true) scrollView.addSubview(contentView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func addSubview(view: UIView) { contentView.addSubview(view) } override func layoutSubviews() { super.layoutSubviews() var previousDeep: CGFloat = 0 var previousFar: CGFloat = 0 for subview in contentView.subviews { let deep = subview.frame.origin.y + subview.frame.size.height let far = subview.frame.origin.x + subview.frame.size.width if deep > previousDeep { previousDeep = deep } if far > previousFar { previousFar = far } } contentView.frame.size = CGSize(width: previousFar, height: previousDeep) scrollView.contentSize = contentView.frame.size } }
mit
cd223de2b42b26a34680ffd3c1cbad42
29.735955
98
0.626028
4.29098
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPMainViewController.swift
1
41354
// // KPMainViewController.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/10. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import SideMenu import PromiseKit import Alamofire protocol KPMainViewControllerDelegate { var selectedDataModel: KPDataModel? { get } } public enum ControllerState { case normal case loading case barLoading case noInternet case failed } class KPMainViewController: KPViewController { var statusBarShouldBeHidden = false var searchHeaderView: KPSearchHeaderView! var statusContainer: UIView! var statusLabel: UILabel! var loadingIndicator: UIActivityIndicatorView! var reFetchTapGesture: UITapGestureRecognizer! var sideBarController: KPSideViewController! var opacityView: UIView! var percentDrivenTransition: UIPercentDrivenInteractiveTransition! var mainListViewController: KPMainListViewController? var mainMapViewController: KPMainMapViewController? var transitionController: KPPhotoDisplayTransition = KPPhotoDisplayTransition() var currentController: KPViewController! private var displayDataModel: [KPDataModel]! func setDisplayDataModel(_ dataModels: [KPDataModel]!, _ animated: Bool!) { displayDataModel = dataModels if animated { mainListViewController?.state = .loading mainMapViewController?.state = .loading mainListViewController?.tableView.reloadData() DispatchQueue.main.asyncAfter(deadline: .now()+0.5) { self.mainListViewController?.displayDataModel = self.displayDataModel self.mainMapViewController?.allDataModel = self.displayDataModel self.searchHeaderView.styleButton.isEnabled = true self.searchHeaderView.searchButton.isEnabled = true self.searchHeaderView.menuButton.isEnabled = true self.searchHeaderView.searchTagView.isUserInteractionEnabled = true } } else { DispatchQueue.main.asyncAfter(deadline: .now()) { self.mainListViewController?.displayDataModel = self.displayDataModel self.mainMapViewController?.allDataModel = self.displayDataModel self.searchHeaderView.styleButton.isEnabled = true self.searchHeaderView.searchButton.isEnabled = true self.searchHeaderView.menuButton.isEnabled = true self.searchHeaderView.searchTagView.isUserInteractionEnabled = true } } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black mainListViewController = KPMainListViewController() mainMapViewController = KPMainMapViewController() sideBarController = KPSideViewController() sideBarController.mainController = self mainListViewController!.mainController = self mainMapViewController!.mainController = self currentController = mainMapViewController addChildViewController(mainListViewController!) view.addSubview((mainListViewController?.view)!) mainListViewController?.didMove(toParentViewController: self) mainListViewController?.view.layer.rasterizationScale = UIScreen.main.scale _ = mainListViewController?.view.addConstraints(fromStringArray: ["H:|[$self]|", "V:|[$self]|"]) addChildViewController(mainMapViewController!) view.addSubview((mainMapViewController?.view)!) mainMapViewController?.didMove(toParentViewController: self) mainMapViewController?.view.layer.rasterizationScale = UIScreen.main.scale mainMapViewController?.showAllButton.addTarget(self, action: #selector(showAllLocation), for: .touchUpInside) _ = mainMapViewController?.view.addConstraints(fromStringArray: ["H:|[$self]|", "V:|[$self]|"]) searchHeaderView = KPSearchHeaderView() searchHeaderView.searchButton.isEnabled = false searchHeaderView.menuButton.isEnabled = false searchHeaderView.styleButton.isEnabled = false searchHeaderView.searchTagView.isUserInteractionEnabled = false searchHeaderView.searchTagView.delegate = self view.addSubview(searchHeaderView) searchHeaderView.addConstraints(fromStringArray: ["V:|[$self(104)]", "H:|[$self]|"]) statusContainer = UIView() statusContainer.isHidden = true statusContainer.alpha = 0.0 statusContainer.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level3 view.addSubview(statusContainer) statusContainer.addConstraints(fromStringArray: ["H:|[$self]|", "V:[$view0][$self]"], views:[searchHeaderView]) statusLabel = UILabel() statusLabel.font = UIFont.systemFont(ofSize: 14) statusLabel.textColor = UIColor.white statusLabel.textAlignment = .center statusLabel.numberOfLines = 0 statusLabel.setText(text: "啊啊啊,似乎發生了一些問題。゚ヽ(゚´Д`)ノ゚。\n點擊重新抓取資料", lineSpacing: 3.0) statusContainer.addSubview(statusLabel) statusLabel.addConstraints(fromStringArray: ["V:|-8-[$self]-8-|", "H:|-16-[$self]-16-|"]) loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white) statusContainer.addSubview(loadingIndicator) loadingIndicator.addConstraintForCenterAligningToSuperview(in: .vertical) loadingIndicator.addConstraintForCenterAligningToSuperview(in: .horizontal) reFetchTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleStatusContainerOnTapped(_:))) statusContainer.addGestureRecognizer(reFetchTapGesture) opacityView = UIView() opacityView.backgroundColor = UIColor.black opacityView.alpha = 0.0 opacityView.isHidden = true view.addSubview(opacityView) opacityView.addConstraints(fromStringArray: ["V:|[$self]|", "H:|[$self]|"]) searchHeaderView.menuButton.addTarget(self, action: #selector(switchSideBar), for: .touchUpInside) searchHeaderView.styleButton.addTarget(self, action: #selector(changeStyle), for: .touchUpInside) searchHeaderView.searchButton.addTarget(self, action: #selector(search), for: .touchUpInside) let menuLeftNavigationController = UISideMenuNavigationController(rootViewController: sideBarController) menuLeftNavigationController.leftSide = true SideMenuManager.menuLeftNavigationController = menuLeftNavigationController SideMenuManager.menuPresentMode = .menuSlideIn SideMenuManager.menuFadeStatusBar = false SideMenuManager.menuShadowOpacity = 0.6 SideMenuManager.menuShadowRadius = 3 SideMenuManager.menuAnimationFadeStrength = 0.5 SideMenuManager.menuAnimationBackgroundColor = UIColor.black SideMenuManager.menuWidth = 260 let reachabilityManager = NetworkReachabilityManager() reachabilityManager?.startListening() reachabilityManager?.listener = { status in if reachabilityManager?.isReachable ?? false { self.mainListViewController?.state = self.mainListViewController?.state == .normal ? .normal : .loading self.mainMapViewController?.state = self.mainMapViewController?.state == .normal ? .normal : .loading UIView.animate(withDuration: 0.15, animations: { self.statusContainer.alpha = 0.0 }, completion: { (_) in self.statusContainer.isHidden = true }) } else { self.mainListViewController?.state = .noInternet self.mainMapViewController?.state = .noInternet self.searchHeaderView.searchTagView.isUserInteractionEnabled = false self.statusContainer.isHidden = false UIView.animate(withDuration: 0.15, animations: { self.statusContainer.alpha = 1.0 }) } } NotificationCenter.default.addObserver(self, selector: #selector(fetchRemoteData), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeVisible(_:)), name: NSNotification.Name.UIWindowDidBecomeVisible, object: nil) } func windowDidBecomeVisible(_ notification:Notification){ let window = notification.object as! UIWindow let windows = UIApplication.shared.windows print("\nwindow目前總數:\(windows.count)") print("Become Visible資訊:\(window)") print("windowLevel數值:\(window.windowLevel)\n") } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } override var prefersStatusBarHidden: Bool { return statusBarShouldBeHidden } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = self.mainListViewController!.tableView.indexPathForSelectedRow { self.mainListViewController!.tableView.deselectRow(at: indexPath, animated: false) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 使用者第一次使用 if !UserDefaults.standard.bool(forKey: AppConstant.introShownKey) { UserDefaults.standard.set(true, forKey: AppConstant.introShownKey) let controller = KPModalViewController() controller.edgeInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0); let introController = KPIntroViewController() self.present(introController, animated: true, completion: nil) } else { if KPUserManager.sharedManager.currentUser == nil && !UserDefaults.standard.bool(forKey: AppConstant.cancelLogInKey) { let controller = KPModalViewController() controller.edgeInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0); let loginController = KPLoginViewController() self.present(loginController, animated: true, completion: nil) } } } // MARK: Data func fetchRemoteData() { let rightTop = mainMapViewController?.mapView.projection.visibleRegion().farRight let leftBottom = mainMapViewController?.mapView.projection.visibleRegion().nearLeft KPServiceHandler.sharedHandler.fetchRemoteData(nil, nil, nil, nil, nil, rightTop, leftBottom, nil) { (results, error) in DispatchQueue.main.async { if results != nil { self.setDisplayDataModel(KPFilter.sharedFilter.currentFilterCafeDatas(), false) self.updateStatusContainerState(true, nil) } else if let requestError = error { self.updateStatusContainerState(false, nil) switch requestError { case .noNetworkConnection: self.mainListViewController?.state = .noInternet self.mainMapViewController?.state = .noInternet default: self.mainMapViewController?.state = .failed print("錯誤萬歲: \(requestError)") } } } } if (KPUserManager.sharedManager.currentUser != nil) { KPUserManager.sharedManager.updateUserInformation() } KPServiceHandler.sharedHandler.fetchTagList() } func reFetchRemoteData(_ showLoading: Bool? = true) { mainListViewController?.state = showLoading! ? .loading : .barLoading mainListViewController?.tableView.reloadData() mainMapViewController?.state = showLoading! ? .loading : .barLoading fetchRemoteData() } // MARK: UI Event func updateStatusContainerState(_ hidden: Bool, _ completion: (() -> Swift.Void)?) { if hidden { self.statusLabel.alpha = 1.0 self.searchHeaderView.searchTagView.isUserInteractionEnabled = true self.loadingIndicator.stopAnimating() UIView.animate(withDuration: 0.15, animations: { self.statusContainer.alpha = 0.0 }, completion: { (_) in self.statusContainer.isHidden = true completion?() }) } else { self.searchHeaderView.searchTagView.isUserInteractionEnabled = false self.statusContainer.isHidden = false self.statusLabel.alpha = 1.0 self.loadingIndicator.stopAnimating() UIView.animate(withDuration: 0.15, animations: { self.statusContainer.alpha = 1.0 }, completion: { (_) in self.statusContainer.isUserInteractionEnabled = true completion?() }) } } func handleStatusContainerOnTapped(_ sender: UITapGestureRecognizer) { statusContainer.isUserInteractionEnabled = false UIView.animate(withDuration: 0.1, animations: { self.statusLabel.alpha = 0.0 }) { (_) in self.loadingIndicator.startAnimating() self.reFetchRemoteData() } } func switchSideBar() { KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.main_menu_button) statusBarShouldBeHidden = true UIView.animate(withDuration: 0.1) { self.setNeedsStatusBarAppearanceUpdate() } opacityView.isHidden = false present(SideMenuManager.menuLeftNavigationController!, animated: true, completion: nil) } func changeStyle() { KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.main_switch_mode_button) let iconImage = (self.currentController == self.mainListViewController) ? R.image.icon_list()!.withRenderingMode(.alwaysTemplate) : R.image.icon_map()!.withRenderingMode(.alwaysTemplate) var transform = CATransform3DMakeTranslation(0, 2, 0) transform.m34 = -1.0/1000 self.mainListViewController?.snapShotShowing = true self.mainListViewController?.view.layer.transform = transform self.mainMapViewController?.view.layer.transform = transform if self.currentController == self.mainListViewController { mainListViewController?.view.alpha = 1.0 mainMapViewController?.view.alpha = 0.0 if !(self.mainMapViewController?.isCollectionViewShow)! { self.mainMapViewController?.collectionView.isHidden = true } self.mainMapViewController?.view.layer.transform = CATransform3DRotate((self.mainMapViewController?.view.layer.transform)!, CGFloat.pi, 0, 1, 0) UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.mainListViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate(transform, CGFloat.pi/2, 0, 1, 0) , 0.7 , 0.7 , 0.7) self.mainMapViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate(transform, -CGFloat.pi/2, 0, 1, 0) , 0.7 , 0.7 , 0.7) self.mainListViewController?.view.alpha = 0.2 }, completion: { (_) in self.mainListViewController?.view.alpha = 0.0 UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.searchHeaderView.styleButton.setImage(iconImage, for: .normal) if !(self.mainMapViewController?.isCollectionViewShow)! { self.mainMapViewController?.collectionView.isHidden = true } self.mainListViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate((self.mainMapViewController?.view.layer.transform)!, -CGFloat.pi/2, 0, 1, 0), 1/0.7, 1/0.7, 1/0.7) self.mainMapViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate((self.mainMapViewController?.view.layer.transform)!, CGFloat.pi/2, 0, 1, 0), 1/0.7, 1/0.7, 1/0.7) self.mainMapViewController?.view.alpha = 1.0 }, completion: { (_) in self.mainMapViewController?.collectionView.isHidden = false self.currentController = self.mainMapViewController }) }) } else { mainListViewController?.view.alpha = 0.0 mainMapViewController?.view.alpha = 1.0 if !(self.mainMapViewController?.isCollectionViewShow)! { self.mainMapViewController?.collectionView.isHidden = true } self.mainListViewController?.view.layer.transform = CATransform3DRotate((self.mainListViewController?.view.layer.transform)!, CGFloat.pi, 0, 1, 0) UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.mainListViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate(transform, CGFloat.pi/2, 0, 1, 0) , 0.7 , 0.7 , 0.7) self.mainMapViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate(transform, -CGFloat.pi/2, 0, 1, 0) , 0.7 , 0.7 , 0.7) self.mainMapViewController?.view.alpha = 0.2 }, completion: { (_) in self.mainMapViewController?.view.alpha = 0.0 UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.searchHeaderView.styleButton.setImage(iconImage, for: .normal) self.mainListViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate((self.mainListViewController?.view.layer.transform)!, -CGFloat.pi/2, 0, 1, 0), 1/0.7, 1/0.7, 1/0.7) self.mainMapViewController?.view.layer.transform = CATransform3DScale(CATransform3DRotate((self.mainMapViewController?.view.layer.transform)!, -CGFloat.pi/2, 0, 1, 0), 1/0.7, 1/0.7, 1/0.7) self.mainListViewController?.view.alpha = 1.0 }, completion: { (_) in self.mainListViewController?.snapShotShowing = false self.mainMapViewController?.collectionView.isHidden = false self.currentController = self.mainListViewController }) }) } } func search() { KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.main_search_button) let controller = KPModalViewController() controller.edgeInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) controller.presentationStyle = .right let searchController = KPSearchViewController() searchController.displayDataModel = displayDataModel searchController.mainListController = mainListViewController let navigationController = UINavigationController(rootViewController: searchController) controller.contentController = navigationController controller.presentModalView() } func showAllLocation() { searchHeaderView.searchTagView.deselectAllSearchTag() mainListViewController?.state = .loading mainMapViewController?.state = .loading mainMapViewController?.showAllButton.isHidden = true mainListViewController?.tableView.reloadData() KPFilter.sharedFilter.restoreDefaultSettings() searchHeaderView.searchTagView.preferenceHintButton.hintCount = 0 DispatchQueue.main.async { self.setDisplayDataModel(KPFilter.sharedFilter.currentFilterCafeDatas(), true) } } func addScreenEdgePanGestureRecognizer(view: UIView, edges: UIRectEdge) { let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(edgePanGesture(edgePanGesture:))) edgePanGesture.edges = edges view.addGestureRecognizer(edgePanGesture) } func edgePanGesture(edgePanGesture: UIScreenEdgePanGestureRecognizer) { let progress = edgePanGesture.translation(in: self.view).x / self.view.bounds.width if edgePanGesture.state == UIGestureRecognizerState.began { self.percentDrivenTransition = UIPercentDrivenInteractiveTransition() if edgePanGesture.edges == UIRectEdge.left { self.dismiss(animated: true, completion: nil) } } else if edgePanGesture.state == UIGestureRecognizerState.changed { self.percentDrivenTransition.update(progress/4) } else if edgePanGesture.state == UIGestureRecognizerState.cancelled || edgePanGesture.state == UIGestureRecognizerState.ended { if progress > 0.5 { self.percentDrivenTransition.finish() } else { self.percentDrivenTransition.cancel() } self.percentDrivenTransition = nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "datailedInformationSegue" { let toViewController = segue.destination as UIViewController let destinationNavigationController = segue.destination as! UINavigationController let targetController = destinationNavigationController.topViewController as! KPInformationViewController toViewController.transitioningDelegate = self targetController.informationDataModel = (sender as! KPMainViewControllerDelegate).selectedDataModel addScreenEdgePanGestureRecognizer(view: toViewController.view, edges: .left) } } } //extension KPMainViewController: ImageTransitionProtocol { // // func tranisitionSetup(){ // // } // // func tranisitionCleanup(){ // // } // // func imageWindowFrame() -> CGRect{ // let convertedRect = self.mainListViewController?.view.convert((self.mainListViewController?.currentSelectedCell?.shopImageView.frame)!, // from: (self.mainListViewController?.currentSelectedCell?.shopImageView)!) // return convertedRect! // } //} //extension KPMainViewController: UIViewControllerTransitioningDelegate { // // func animationController(forPresented presented: UIViewController, // presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { // if let navigationController = presented as? UINavigationController { // if let informationViewcontroller = navigationController.viewControllers.first as? KPInformationViewController { // transitionController.setupImageTransition((self.mainListViewController?.currentSelectedCell?.shopImageView.image)!, // fromDelegate: self, // toDelegate: informationViewcontroller) // // return transitionController // } else { // return nil // } // } else { // return nil // } // } // // func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // if let informationViewcontroller = dismissed as? KPInformationViewController { // transitionController.setupImageTransition((self.mainListViewController?.currentSelectedCell?.shopImageView.image)!, // fromDelegate: informationViewcontroller, // toDelegate: self) // return transitionController // // } else { // return nil // } // } //} extension KPMainViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return KPInformationTranstion() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { if let navigationController = dismissed as? UINavigationController { if let informationViewcontroller = navigationController.viewControllers.first as? KPInformationViewController { if informationViewcontroller.dismissWithDefaultType { let transition = KPInformationDismissTransition() transition.defaultDimissed = true return transition } } } return KPInformationDismissTransition() } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.percentDrivenTransition } } extension KPMainViewController: KPSearchTagViewDelegate, KPSearchConditionViewControllerDelegate { func searchTagDidSelect(_ searchTag: searchTagType) { mainListViewController?.state = .loading mainMapViewController?.state = .loading mainMapViewController?.showAllButton.isHidden = false mainListViewController?.tableView.reloadData() DispatchQueue.global().async { switch searchTag { case .wifi: KPFilter.sharedFilter.wifiRate = 5 KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_wifi_button) case .socket: KPFilter.sharedFilter.socket = 1 KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_socket_button) case .limitTime: KPFilter.sharedFilter.limited_time = 2 KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_time_button) case .opening: KPFilter.sharedFilter.currentOpening = true KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_open_button) case .highRate: KPFilter.sharedFilter.averageRate = 4 KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_rate_button) case .clear: self.mainMapViewController?.showAllButton.isHidden = true KPAnalyticManager.sendButtonClickEvent(KPAnalyticsEventValue.button.quick_clear_button) KPFilter.sharedFilter.restoreDefaultSettings() } DispatchQueue.main.async { self.setDisplayDataModel(KPFilter.sharedFilter.currentFilterCafeDatas(), true) } } } func searchTagDidDeselect(_ searchTag: searchTagType) { mainListViewController?.state = .loading mainMapViewController?.state = .loading mainMapViewController?.showAllButton.isHidden = (searchHeaderView.searchTagView.preferenceHintButton.hintCount == 0) mainListViewController?.tableView.reloadData() DispatchQueue.global().async { switch searchTag { case .wifi: KPFilter.sharedFilter.wifiRate = 0 case .socket: KPFilter.sharedFilter.socket = 4 case .limitTime: KPFilter.sharedFilter.limited_time = 4 case .opening: KPFilter.sharedFilter.currentOpening = false case .highRate: KPFilter.sharedFilter.averageRate = 0 case .clear: break } let filteredData = KPFilter.sharedFilter.currentFilterCafeDatas() DispatchQueue.main.async { self.setDisplayDataModel(filteredData, true) } } } func searchConditionControllerDidSearch(_ searchConditionController: KPSearchConditionViewController) { mainListViewController?.state = .loading mainMapViewController?.state = .loading mainMapViewController?.showAllButton.isHidden = false mainListViewController?.tableView.reloadData() // 各個 rating if searchConditionController.sortSegmentedControl.selectedSegmentIndex == 0 { KPFilter.sharedFilter.sortedby = .distance } else if searchConditionController.sortSegmentedControl.selectedSegmentIndex == 1 { KPFilter.sharedFilter.sortedby = .rates } // Wifi KPFilter.sharedFilter.wifiRate = Double(searchConditionController.ratingViews[0].currentRate) if KPFilter.sharedFilter.wifiRate >= 4, let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .wifi) { self.searchHeaderView.searchTagView.collectionView.selectItem(at: IndexPath.init(row: index, section: 0), animated: false, scrollPosition: []) } else if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .wifi) { self.searchHeaderView.searchTagView.collectionView.deselectItem(at: IndexPath.init(row: index, section:0), animated: false) } KPFilter.sharedFilter.quietRate = Double(searchConditionController.ratingViews[1].currentRate) KPFilter.sharedFilter.cheapRate = Double(searchConditionController.ratingViews[2].currentRate) KPFilter.sharedFilter.seatRate = Double(searchConditionController.ratingViews[3].currentRate) KPFilter.sharedFilter.tastyRate = Double(searchConditionController.ratingViews[4].currentRate) KPFilter.sharedFilter.foodRate = Double(searchConditionController.ratingViews[5].currentRate) KPFilter.sharedFilter.musicRate = Double(searchConditionController.ratingViews[6].currentRate) KPFilter.sharedFilter.limited_time = (searchConditionController.timeRadioBoxOne.groupValue as! Int) KPFilter.sharedFilter.socket = (searchConditionController.socketRadioBoxOne.groupValue as! Int) if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .limitTime) { if KPFilter.sharedFilter.limited_time == 2 { self.searchHeaderView.searchTagView.collectionView.selectItem(at: IndexPath.init(row: index, section: 0), animated: false, scrollPosition: []) } else { self.searchHeaderView.searchTagView.collectionView.deselectItem(at: IndexPath.init(row: index, section: 0), animated: false) } } if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .socket) { if KPFilter.sharedFilter.socket == 1 { self.searchHeaderView.searchTagView.collectionView.selectItem(at: IndexPath.init(row: index, section: 0), animated: false, scrollPosition: []) } else { self.searchHeaderView.searchTagView.collectionView.deselectItem(at: IndexPath.init(row: index, section: 0), animated: false) } } // 時間 if searchConditionController.businessCheckBoxOne.checkBox.checkState == .checked { // 不設定 KPFilter.sharedFilter.currentOpening = false KPFilter.sharedFilter.searchTime = nil // 取消 營業中 的tag if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .opening) { self.searchHeaderView.searchTagView.collectionView.deselectItem(at: IndexPath.init(row: index, section:0), animated: false) } } else if searchConditionController.businessCheckBoxThree.checkBox.checkState == .checked { // 特定時段 KPFilter.sharedFilter.currentOpening = false if let startTime = searchConditionController.timeSupplementView.startTime, let endTime = searchConditionController.timeSupplementView.endTime { KPFilter.sharedFilter.searchTime = "\(startTime)~\(endTime)" } // 取消 營業中 的tag if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .opening) { self.searchHeaderView.searchTagView.collectionView.deselectItem(at: IndexPath.init(row: index, section:0), animated: false) } } else if searchConditionController.businessCheckBoxTwo.checkBox.checkState == .checked { // 目前營業中 KPFilter.sharedFilter.currentOpening = true // 選取 營業中 的tag if let index = self.searchHeaderView.searchTagView.headerTagContents.index(of: .opening) { self.searchHeaderView.searchTagView.collectionView.selectItem(at: IndexPath.init(row: index, section: 0), animated: false, scrollPosition: []) } } KPFilter.sharedFilter.standingDesk = searchConditionController.othersCheckBoxOne.checkBox.checkState == .checked ? true : false // 更新選取tag的數量 self.searchHeaderView.searchTagView.preferenceHintButton.hintCount = self.searchHeaderView.searchTagView.collectionView.indexPathsForSelectedItems?.count ?? 0 DispatchQueue.global().async { let filteredData = KPFilter.sharedFilter.currentFilterCafeDatas() DispatchQueue.main.async { self.setDisplayDataModel(filteredData, true) } } } }
mit
c7e097e8ab595be24c562def06ef73de
46.479815
145
0.545026
6.278981
false
false
false
false
sarath-vijay/ColorPickerSlider
ColorPickerSlider/Classes/ColorPickerView.swift
1
3746
// // ColorPickerView.swift // TestColorPicker // // Created by Sarath Vijay on 20/10/16. // Copyright © 2016 jango. All rights reserved. // import UIKit fileprivate enum ColorPickerViewConstant { static let colorPickerSliderHeightMin: CGFloat = 2.0 static let uiSliderHeightDefault: CGFloat = 31.0 } public typealias ColorChangeBlock = (_ color: UIColor?) -> Void open class ColorPickerView: UIView { //MARK:- Open constant //MARK:- /** User can use this value to change the slider height. */ open var colorPickerSliderHeight: CGFloat = 2.0 //Min value //MARK:- Private variables //MARK:- fileprivate var currentHueValue : CGFloat = 0.0 fileprivate var currentSliderColor = UIColor.red fileprivate var hueImage: UIImage! fileprivate var slider: UISlider! //MARK:- Open variables //MARK:- open var didChangeColor: ColorChangeBlock? //SJ : didchange - meaningful name //MARK:- Override Functions //MARK:- override open func layoutSubviews() { super.layoutSubviews() backgroundColor = UIColor.clear update() } override open func draw(_ rect: CGRect) { super.draw(rect) if slider == nil { let sliderRect = CGRect(x: rect.origin.x, y: (rect.size.height - ColorPickerViewConstant.uiSliderHeightDefault) * 0.5, width: rect.width, height: ColorPickerViewConstant.uiSliderHeightDefault) slider = UISlider(frame: sliderRect) slider.setValue(0, animated: false) slider.addTarget(self, action: #selector(onSliderValueChange), for: UIControlEvents.valueChanged) slider.minimumTrackTintColor = UIColor.clear slider.maximumTrackTintColor = UIColor.clear let heigthForSliderImage = max(colorPickerSliderHeight, ColorPickerViewConstant.colorPickerSliderHeightMin) let sliderImageRect = CGRect(x: rect.origin.x, y: (rect.size.height - heigthForSliderImage) * 0.5, width: rect.width, height: heigthForSliderImage) if hueImage != nil { hueImage.draw(in: sliderImageRect) } addSubview(slider) } } //MARK:- Internal Functions //MARK:- func onSliderValueChange(slider: UISlider) { currentHueValue = CGFloat(slider.value) currentSliderColor = UIColor(hue: currentHueValue, saturation: 1, brightness: 1, alpha: 1) self.didChangeColor?(currentSliderColor) } } fileprivate extension ColorPickerView { func update() { if hueImage == nil { let heigthForSliderImage = max(colorPickerSliderHeight, ColorPickerViewConstant.colorPickerSliderHeightMin) let size: CGSize = CGSize(width: frame.width, height: heigthForSliderImage) hueImage = generateHUEImage(size) } } func generateHUEImage(_ size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let heigthForSliderImage = max(colorPickerSliderHeight, ColorPickerViewConstant.colorPickerSliderHeightMin) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIBezierPath(roundedRect: rect, cornerRadius: heigthForSliderImage * 0.5).addClip() for x: Int in 0 ..< Int(size.width) { UIColor(hue: CGFloat(CGFloat(x) / size.width), saturation: 1.0, brightness: 1.0, alpha: 1.0).set() let temp = CGRect(x: CGFloat(x), y: 0, width: 1, height: size.height) UIRectFill(temp) } let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
mit
41ebe369241a1265371057c745233e30
35.009615
131
0.654206
4.442467
false
false
false
false
bellots/usefulExtensions
UsefulExtensions/UITextViewExtensions.swift
1
1403
// // UITextViewExtensions.swift // UsefulExtensions // // Created by Andrea Bellotto on 06/09/17. // Copyright © 2017 Andrea Bellotto. All rights reserved. // import Foundation extension UITextView{ public var placeholder:String?{ get{ // Get the placeholder text from the label var placeholderText: String? if let placeHolderLabel = self.viewWithTag(222) as? UILabel { placeholderText = placeHolderLabel.text } return placeholderText } set{ var placeholderLabel = UILabel() if let oldPlaceHolderLabel = self.viewWithTag(222) as? UILabel { placeholderLabel = oldPlaceHolderLabel } placeholderLabel.text = newValue placeholderLabel.textColor = UILabel.appearance().textColor placeholderLabel.font = self.font placeholderLabel.sizeToFit() placeholderLabel.tag = 222 placeholderLabel.frame.origin = CGPoint(x: 5, y: (self.font?.pointSize)! / 2) placeholderLabel.isHidden = !self.text.isEmpty self.addSubview(placeholderLabel) } } func checkPlaceholder() { let placeholderLabel = self.viewWithTag(222) as! UILabel placeholderLabel.isHidden = !self.text.isEmpty } }
mit
64c2c542c836cb7c6eb24b64d9b725dd
29.478261
89
0.598431
5.351145
false
false
false
false
JC-Hu/ColorExpert
Pods/FirebaseCoreInternal/FirebaseCore/Internal/Sources/HeartbeatLogging/Storage.swift
3
4655
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// A type that reads from and writes to an underlying storage container. protocol Storage { /// Reads and returns the data stored by this storage type. /// - Returns: The data read from storage. /// - Throws: An error if the read failed. func read() throws -> Data /// Writes the given data to this storage type. /// - Throws: An error if the write failed. func write(_ data: Data?) throws } /// Error types for `Storage` operations. enum StorageError: Error { case readError case writeError } // MARK: - FileStorage /// A object that provides API for reading and writing to a file system resource. final class FileStorage: Storage { /// A file system URL to the underlying file resource. private let url: URL /// The file manager used to perform file system operations. private let fileManager: FileManager /// Designated initializer. /// - Parameters: /// - url: A file system URL for the underlying file resource. /// - fileManager: A file manager. Defaults to `default` manager. init(url: URL, fileManager: FileManager = .default) { self.url = url self.fileManager = fileManager } /// Reads and returns the data from this object's associated file resource. /// /// - Returns: The data stored on disk. /// - Throws: An error if reading the contents of the file resource fails (i.e. file doesn't exist). func read() throws -> Data { do { return try Data(contentsOf: url) } catch { throw StorageError.readError } } /// Writes the given data to this object's associated file resource. /// /// When the given `data` is `nil`, this object's associated file resource is emptied. /// /// - Parameter data: The `Data?` to write to this object's associated file resource. func write(_ data: Data?) throws { do { try createDirectories(in: url.deletingLastPathComponent()) if let data = data { try data.write(to: url, options: .atomic) } else { let emptyData = Data() try emptyData.write(to: url, options: .atomic) } } catch { throw StorageError.writeError } } /// Creates all directories in the given file system URL. /// /// If the directory for the given URL already exists, the error is ignored because the directory /// has already been created. /// /// - Parameter url: The URL to create directories in. private func createDirectories(in url: URL) throws { do { try fileManager.createDirectory( at: url, withIntermediateDirectories: true ) } catch CocoaError.fileWriteFileExists { // Directory already exists. } catch { throw error } } } // MARK: - UserDefaultsStorage /// A object that provides API for reading and writing to a user defaults resource. final class UserDefaultsStorage: Storage { /// The underlying defaults container. private let defaults: UserDefaults /// The key mapping to the object's associated resource in `defaults`. private let key: String /// Designated initializer. /// - Parameters: /// - defaults: The defaults container. /// - key: The key mapping to the value stored in the defaults container. init(defaults: UserDefaults, key: String) { self.defaults = defaults self.key = key } /// Reads and returns the data from this object's associated defaults resource. /// /// - Returns: The data stored on disk. /// - Throws: An error if no data has been stored to the defaults container. func read() throws -> Data { if let data = defaults.data(forKey: key) { return data } else { throw StorageError.readError } } /// Writes the given data to this object's associated defaults. /// /// When the given `data` is `nil`, the associated default is removed. /// /// - Parameter data: The `Data?` to write to this object's associated defaults. func write(_ data: Data?) throws { if let data = data { defaults.set(data, forKey: key) } else { defaults.removeObject(forKey: key) } } }
mit
c818454b8aa0badc7de99cba0c25c980
31.326389
102
0.675403
4.354537
false
false
false
false
zhangao0086/DrawingBoard
DrawingBoard/RGBColorPicker.swift
1
3208
// // RGBColorPicker.swift // DrawingBoard // // Created by ZhangAo on 15-3-29. // Copyright (c) 2015年 zhangao. All rights reserved. // import UIKit class RGBColorPicker: UIView { var colorChangedBlock: ((color: UIColor) -> Void)? private var sliders = [UISlider]() private var labels = [UILabel]() override init(frame: CGRect) { super.init(frame: frame) self.initial() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initial() } private func initial() { self.backgroundColor = UIColor.clearColor() let trackColors = [UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor()] for index in 1...3 { let slider = UISlider() slider.minimumValue = 0 slider.value = 0 slider.maximumValue = 255 slider.minimumTrackTintColor = trackColors[index - 1] slider.addTarget(self, action: "colorChanged:", forControlEvents: .ValueChanged) self.addSubview(slider) self.sliders.append(slider) let label = UILabel() label.text = "0" self.addSubview(label) self.labels.append(label) } } override func layoutSubviews() { super.layoutSubviews() let sliderHeight = CGFloat(31) let labelWidth = CGFloat(29) let yHeight = self.bounds.size.height / CGFloat(sliders.count) for index in 0..<self.sliders.count { let slider = self.sliders[index] slider.frame = CGRect(x: 0, y: CGFloat(index) * yHeight, width: self.bounds.size.width - labelWidth - 5.0, height: sliderHeight) let label = self.labels[index] label.frame = CGRect(x: CGRectGetMaxX(slider.frame) + 5, y: slider.frame.origin.y, width: labelWidth, height: sliderHeight) } } override func intrinsicContentSize() -> CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: 107) } @IBAction private func colorChanged(slider: UISlider) { let color = UIColor( red: CGFloat(self.sliders[0].value / 255.0), green: CGFloat(self.sliders[1].value / 255.0), blue: CGFloat(self.sliders[2].value / 255.0), alpha: 1) let label = self.labels[self.sliders.indexOf(slider)!] label.text = NSString(format: "%.0f", slider.value) as String if let colorChangedBlock = self.colorChangedBlock { colorChangedBlock(color: color) } } func setCurrentColor(color: UIColor) { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: nil) let colors = [red, green, blue] for index in 0..<self.sliders.count { let slider = self.sliders[index] slider.value = Float(colors[index]) * 255 let label = self.labels[index] label.text = NSString(format: "%.0f", slider.value) as String } } }
mit
51d13f5f29813cfe818a2f44af03253c
31.393939
140
0.571429
4.403846
false
false
false
false
karstengresch/rw_studies
Apprentice/Checklists09/Checklists/AllListsTableViewController.swift
1
5337
// // AllListsTableViewController.swift // Checklists // // Created by Karsten Gresch on 11.12.15. // Copyright © 2015 Closure One. All rights reserved. // import UIKit class AllListsTableViewController: UITableViewController, ListDetailViewControllerDelegate, UINavigationControllerDelegate { var dataModel: DataModel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("Numbers of rows: \(dataModel.checklists.count)") return dataModel.checklists.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // print("indexPath.row: \(indexPath.row)" ) let cell = cellForTableView(tableView) let checklist = dataModel.checklists[(indexPath as NSIndexPath).row] cell.textLabel?.text = checklist.name cell.accessoryType = .detailDisclosureButton let count = checklist.countUncheckedItems() if checklist.checklistItems.count == 0 { cell.detailTextLabel?.text = "Start entering new items!" } else if count == 0 { cell.detailTextLabel?.text = "All done!" } else { cell.detailTextLabel?.text = "\(count) Remaining" } cell.imageView?.image = UIImage(named: checklist.iconName) return cell } func cellForTableView(_ tableView: UITableView) -> UITableViewCell { let cellIdentifier = "AddChecklistCell" var returnCell: UITableViewCell? if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { returnCell = cell } else { returnCell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) } return returnCell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("indexPath.row: \((indexPath as NSIndexPath).row)" ) dataModel.indexOfSelectedChecklist = (indexPath as NSIndexPath).row let checklist = dataModel.checklists[(indexPath as NSIndexPath).row] performSegue(withIdentifier: "ShowChecklist", sender: checklist) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { dataModel.checklists.remove(at: (indexPath as NSIndexPath).row) let indexPaths = [indexPath] tableView.deleteRows(at: indexPaths, with: .automatic) } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let navigationController = storyboard!.instantiateViewController(withIdentifier: "ListDetailViewController") as! UINavigationController let controller = navigationController.topViewController as! ListDetailViewController controller.delegate = self let checklist = dataModel.checklists[(indexPath as NSIndexPath).row] controller.checklistToEdit = checklist present(navigationController, animated: true, completion: nil) } // MARK: ListDetailViewController delegate methods func listDetailViewControllerDidCancel(_ controller: ListDetailViewController) { dismiss(animated: true, completion: nil) } func listDetailViewController(_ controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist) { print("didFinishAddingItem - checklist name: \(checklist.name)") dataModel.checklists.append(checklist) dataModel.sortChecklists() tableView.reloadData() dismiss(animated: true, completion: nil) } func listDetailViewController(_ controller: ListDetailViewController, didFinishEditingChecklist checklist: Checklist) { print("didFinishEditingItem - checklist name: \(checklist.name)") dataModel.sortChecklists() tableView.reloadData() dismiss(animated: true, completion: nil) } // MARK: Navigation func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController === self { dataModel.indexOfSelectedChecklist = -1 } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowChecklist" { let controller = segue.destination as! ChecklistViewController controller.checklist = sender as! Checklist } else if segue.identifier == "AddChecklist" { let navigationController = segue.destination as! UINavigationController let controller = navigationController.topViewController as! ListDetailViewController controller.delegate = self controller.checklistToEdit = nil } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.delegate = self let index = dataModel.indexOfSelectedChecklist if index > 0 && index < dataModel.checklists.count { let checklist = dataModel.checklists[index] performSegue(withIdentifier: "ShowChecklist", sender: checklist) } } }
unlicense
585c0b9291188143998e7eb54f9c86e4
34.105263
139
0.723951
5.433809
false
false
false
false
dsp1589/template-uber
My Taxi/My Taxi/EmbedCustomSegue.swift
1
1368
// // EmbedCustomSegue.swift // My Taxi // // Created by Dhanasekarapandian Srinivasan on 1/8/17. // Copyright © 2017 Systameta. All rights reserved. // import Foundation import UIKit class EmbedCustomSegue: UIStoryboardSegue { override func perform() { var containerView : UIView? = nil for view in self.source.view.subviews{ if view.tag == SINGLE_CONTAINER_VIEW_TAG{ containerView = view break } } containerView?.subviews.first?.removeFromSuperview() switch identifier! { case PROCEED_TO_SIGN_IN: break case PROCEED_TO_SIGN_UP: break default: break } guard let embeddableview = containerView else { print("Container view not implemented for Embed segue") exit(1) } self.destination.view.frame = embeddableview.frame self.destination.view.frame.origin.x = 0 self.destination.view.frame.origin.y = 0 self.destination.willMove(toParentViewController: self.source) embeddableview.addSubview(self.destination.view) self.destination.view.layoutIfNeeded() self.source.addChildViewController(self.destination) self.destination.didMove(toParentViewController: self.source) } }
mit
eb838682a478ee38fd2e99cd6a2845e4
29.377778
70
0.622531
4.481967
false
false
false
false
kingloveyy/SwiftBlog
SwiftBlog/SwiftBlog/Classes/UI/Home/HomeViewController.swift
1
3303
// // HomeViewController.swift // SwiftBlog // // Created by King on 15/3/19. // Copyright (c) 2015年 king. All rights reserved. // import UIKit class HomeViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
327c47b84043e65f7cec4769d8b5dbcf
33.030928
157
0.682823
5.557239
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/Detail/ReaderDetailCoordinator.swift
1
26298
import Foundation class ReaderDetailCoordinator { /// Key for restoring the VC post static let restorablePostObjectURLKey: String = "RestorablePostObjectURLKey" /// A post to be displayed var post: ReaderPost? { didSet { postInUse(true) indexReaderPostInSpotlight() } } /// Used to determine if block and report are shown in the options menu. var readerTopic: ReaderAbstractTopic? /// Used for analytics var remoteSimplePost: RemoteReaderSimplePost? /// A post URL to be loaded and be displayed var postURL: URL? /// A comment ID used to navigate to a comment var commentID: Int? { // Comment fragments have the form #comment-50484 // If one is present, we'll extract the ID and return it. if let fragment = postURL?.fragment, fragment.hasPrefix("comment-"), let idString = fragment.components(separatedBy: "comment-").last { return Int(idString) } return nil } /// Called if the view controller's post fails to load var postLoadFailureBlock: (() -> Void)? = nil /// An authenticator to ensure any request made to WP sites is properly authenticated lazy var authenticator: RequestAuthenticator? = { guard let account = accountService.defaultWordPressComAccount() else { DDLogInfo("Account not available for Reader authentication") return nil } return RequestAuthenticator(account: account) }() /// Core Data stack manager private let coreDataStack: CoreDataStack /// Reader Post Service private let readerPostService: ReaderPostService /// Reader Topic Service private let topicService: ReaderTopicService /// Post Service private let postService: PostService /// Used for `RequestAuthenticator` creation and likes filtering logic. private let accountService: AccountService /// Post Sharing Controller private let sharingController: PostSharingController /// Reader Link Router private let readerLinkRouter: UniversalLinkRouter /// Reader View private weak var view: ReaderDetailView? /// Reader View Controller private var viewController: UIViewController? { return view as? UIViewController } /// A post ID to fetch private(set) var postID: NSNumber? /// A site ID to be used to fetch a post private(set) var siteID: NSNumber? /// If the site is an external feed (not hosted at WPcom and not using Jetpack) private(set) var isFeed: Bool? /// The perma link URL for the loaded post private var permaLinkURL: URL? { guard let postURLString = post?.permaLink else { return nil } return URL(string: postURLString) } /// The total number of Likes for the post. /// Passed to ReaderDetailLikesListController to display in the view title. private var totalLikes = 0 /// Initialize the Reader Detail Coordinator /// /// - Parameter service: a Reader Post Service init(coreDataStack: CoreDataStack = ContextManager.shared, readerPostService: ReaderPostService = ReaderPostService(managedObjectContext: ContextManager.sharedInstance().mainContext), topicService: ReaderTopicService = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext), postService: PostService = PostService(managedObjectContext: ContextManager.sharedInstance().mainContext), accountService: AccountService = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext), sharingController: PostSharingController = PostSharingController(), readerLinkRouter: UniversalLinkRouter = UniversalLinkRouter(routes: UniversalLinkRouter.readerRoutes), view: ReaderDetailView) { self.coreDataStack = coreDataStack self.readerPostService = readerPostService self.topicService = topicService self.postService = postService self.accountService = accountService self.sharingController = sharingController self.readerLinkRouter = readerLinkRouter self.view = view } deinit { postInUse(false) } /// Start the coordinator /// func start() { view?.showLoading() if post != nil { renderPostAndBumpStats() } else if let siteID = siteID, let postID = postID, let isFeed = isFeed { fetch(postID: postID, siteID: siteID, isFeed: isFeed) } else if let postURL = postURL { fetch(postURL) } } /// Fetch related posts for the current post /// func fetchRelatedPosts(for post: ReaderPost) { readerPostService.fetchRelatedPosts(for: post) { [weak self] relatedPosts in self?.view?.renderRelatedPosts(relatedPosts) } failure: { error in DDLogError("Error fetching related posts for detail: \(String(describing: error?.localizedDescription))") } } /// Fetch Likes for the current post. /// Returns `ReaderDetailLikesView.maxAvatarsDisplayed` number of Likes. /// func fetchLikes(for post: ReaderPost) { guard let postID = post.postID else { return } // Fetch a full page of Likes but only return the `maxAvatarsDisplayed` number. // That way the first page will already be cached if the user displays the full Likes list. postService.getLikesFor(postID: postID, siteID: post.siteID, success: { [weak self] users, totalLikes, _ in var filteredUsers = users var currentLikeUser: LikeUser? = nil let totalLikesExcludingSelf = totalLikes - (post.isLiked ? 1 : 0) // Split off current user's like from the list. // Likes from self will always be placed in the last position, regardless of the when the post was liked. if let userID = self?.accountService.defaultWordPressComAccount()?.userID.int64Value, let userIndex = filteredUsers.firstIndex(where: { $0.userID == userID }) { currentLikeUser = filteredUsers.remove(at: userIndex) } self?.totalLikes = totalLikes self?.view?.updateLikes(with: filteredUsers.prefix(ReaderDetailLikesView.maxAvatarsDisplayed).map { $0.avatarUrl }, totalLikes: totalLikesExcludingSelf) // Only pass current user's avatar when we know *for sure* that the post is liked. // This is to work around a possible race condition that causes an unliked post to have current user's LikeUser, which // would cause a display bug in ReaderDetailLikesView. The race condition issue will be investigated separately. self?.view?.updateSelfLike(with: post.isLiked ? currentLikeUser?.avatarUrl : nil) }, failure: { [weak self] error in self?.view?.updateLikes(with: [String](), totalLikes: 0) DDLogError("Error fetching Likes for post detail: \(String(describing: error?.localizedDescription))") }) } /// Share the current post /// func share(fromView anchorView: UIView) { guard let post = post, let view = viewController else { return } sharingController.shareReaderPost(post, fromView: anchorView, inViewController: view) WPAnalytics.trackReader(.readerSharedItem) } /// Set a postID, siteID and isFeed /// /// - Parameter postID: A post ID to fetch /// - Parameter siteID: A site ID to fetch /// - Parameter isFeed: If the site is an external feed (not hosted at WPcom and not using Jetpack) func set(postID: NSNumber, siteID: NSNumber, isFeed: Bool) { self.postID = postID self.siteID = siteID self.isFeed = isFeed } /// Show more about a specific site in Discovery /// func showMore() { guard let post = post, post.sourceAttribution != nil else { return } if let blogID = post.sourceAttribution.blogID { let controller = ReaderStreamViewController.controllerWithSiteID(blogID, isFeed: false) viewController?.navigationController?.pushViewController(controller, animated: true) return } var path: String? if post.sourceAttribution.attributionType == SourcePostAttributionTypePost { path = post.sourceAttribution.permalink } else { path = post.sourceAttribution.blogURL } if let path = path, let linkURL = URL(string: path) { presentWebViewController(linkURL) } } /// Loads an image (or GIF) from a URL and displays it in fullscreen /// /// - Parameter url: URL of the image or gif func presentImage(_ url: URL) { let imageViewController = WPImageViewController(url: url) imageViewController.readerPost = post imageViewController.modalTransitionStyle = .crossDissolve imageViewController.modalPresentationStyle = .fullScreen viewController?.present(imageViewController, animated: true) } /// Open the postURL in a separated view controller /// func openInBrowser() { let url: URL? = { // For Reader posts, use post link. if let permaLink = post?.permaLink { return URL(string: permaLink) } // For Related posts, use postURL. return postURL }() guard let postURL = url else { return } WPAnalytics.trackReader(.readerArticleVisited) presentWebViewController(postURL) } /// Some posts have content from private sites that need special cookies /// /// Use this method to make sure these cookies are downloaded. /// - Parameter webView: the webView where the post will be rendered /// - Parameter completion: a completion block func storeAuthenticationCookies(in webView: WKWebView, completion: @escaping () -> Void) { guard let authenticator = authenticator, let postURL = permaLinkURL else { completion() return } authenticator.request(url: postURL, cookieJar: webView.configuration.websiteDataStore.httpCookieStore) { _ in completion() } } /// Requests a ReaderPost from the service and updates the View. /// /// Use this method to fetch a ReaderPost. /// - Parameter postID: a post identification /// - Parameter siteID: a site identification /// - Parameter isFeed: a Boolean indicating if the site is an external feed (not hosted at WPcom and not using Jetpack) private func fetch(postID: NSNumber, siteID: NSNumber, isFeed: Bool) { readerPostService.fetchPost(postID.uintValue, forSite: siteID.uintValue, isFeed: isFeed, success: { [weak self] post in self?.post = post self?.renderPostAndBumpStats() }, failure: { [weak self] _ in self?.postURL == nil ? self?.view?.showError() : self?.view?.showErrorWithWebAction() self?.reportPostLoadFailure() }) } /// Requests a ReaderPost from the service and updates the View. /// /// Use this method to fetch a ReaderPost from a URL. /// - Parameter url: a post URL private func fetch(_ url: URL) { readerPostService.fetchPost(at: url, success: { [weak self] post in self?.post = post self?.renderPostAndBumpStats() }, failure: { [weak self] error in DDLogError("Error fetching post for detail: \(String(describing: error?.localizedDescription))") self?.postURL == nil ? self?.view?.showError() : self?.view?.showErrorWithWebAction() self?.reportPostLoadFailure() }) } private func renderPostAndBumpStats() { guard let post = post else { return } view?.render(post) bumpStats() bumpPageViewsForPost() markPostAsSeen() } private func markPostAsSeen() { guard let post = post, let context = post.managedObjectContext, !post.isSeen else { return } let postService = ReaderPostService(managedObjectContext: context) postService.toggleSeen(for: post, success: { NotificationCenter.default.post(name: .ReaderPostSeenToggled, object: nil, userInfo: [ReaderNotificationKeys.post: post]) }, failure: nil) } /// If the loaded URL contains a hash/anchor then jump to that spot in the post content /// once it loads /// private func scrollToHashIfNeeded() { guard let url = postURL, let hash = URLComponents(url: url, resolvingAgainstBaseURL: true)?.fragment else { return } view?.scroll(to: hash) } /// Shows the current post site posts in a new screen /// private func previewSite() { guard let post = post else { return } let controller = ReaderStreamViewController.controllerWithSiteID(post.siteID, isFeed: post.isExternal) viewController?.navigationController?.pushViewController(controller, animated: true) let properties = ReaderHelpers.statsPropertiesForPost(post, andValue: post.blogURL as AnyObject?, forKey: "URL") WPAppAnalytics.track(.readerSitePreviewed, withProperties: properties) } /// Show a menu with options for the current post's site /// private func showMenu(_ anchorView: UIView) { guard let post = post, let context = post.managedObjectContext, let viewController = viewController else { return } ReaderMenuAction(logged: ReaderHelpers.isLoggedIn()).execute(post: post, context: context, readerTopic: readerTopic, anchor: anchorView, vc: viewController, source: ReaderPostMenuSource.details) WPAnalytics.trackReader(.readerArticleDetailMoreTapped) } private func showTopic(_ topic: String) { let controller = ReaderStreamViewController.controllerWithTagSlug(topic) viewController?.navigationController?.pushViewController(controller, animated: true) } /// Show a list with posts containing this tag /// private func showTag() { guard let post = post else { return } let controller = ReaderStreamViewController.controllerWithTagSlug(post.primaryTagSlug) viewController?.navigationController?.pushViewController(controller, animated: true) let properties = ReaderHelpers.statsPropertiesForPost(post, andValue: post.primaryTagSlug as AnyObject?, forKey: "tag") WPAppAnalytics.track(.readerTagPreviewed, withProperties: properties) } /// Given a URL presents it the best way possible. /// /// If it's an image, shows it fullscreen. /// If it's a fullscreen Story link, open it in the webview controller. /// If it's a post, open a new detail screen. /// If it's a link protocol (tel: / sms: / mailto:), take the correct action. /// If it's a regular URL, open it in the webview controller. /// /// - Parameter url: the URL to be handled func handle(_ url: URL) { // If the URL has an anchor (#) // and the URL is equal to the current post URL if let hash = URLComponents(url: url, resolvingAgainstBaseURL: true)?.fragment, let postURL = permaLinkURL, postURL.isHostAndPathEqual(to: url) { view?.scroll(to: hash) } else if url.pathExtension.contains("gif") || url.pathExtension.contains("jpg") || url.pathExtension.contains("jpeg") || url.pathExtension.contains("png") { presentImage(url) } else if url.query?.contains("wp-story") ?? false { presentWebViewController(url) } else if readerLinkRouter.canHandle(url: url) { readerLinkRouter.handle(url: url, shouldTrack: false, source: .inApp(presenter: viewController)) } else if url.isWordPressDotComPost { presentReaderDetail(url) } else if url.isLinkProtocol { readerLinkRouter.handle(url: url, shouldTrack: false, source: .inApp(presenter: viewController)) } else { presentWebViewController(url) } } /// Called after the webView fully loads func webViewDidLoad() { scrollToHashIfNeeded() } /// Show the featured image fullscreen /// private func showFeaturedImage(_ sender: CachedAnimatedImageView) { guard let post = post else { return } var controller: WPImageViewController if post.featuredImageURL.isGif, let data = sender.animatedGifData { controller = WPImageViewController(gifData: data) } else if let featuredImage = sender.image { controller = WPImageViewController(image: featuredImage) } else { return } controller.modalTransitionStyle = .crossDissolve controller.modalPresentationStyle = .fullScreen viewController?.present(controller, animated: true) } private func followSite(completion: @escaping () -> Void) { guard let post = post else { return } ReaderFollowAction().execute(with: post, context: coreDataStack.mainContext, completion: { [weak self] follow in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: true) self?.view?.updateHeader() completion() }, failure: { [weak self] follow, _ in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: false) self?.view?.updateHeader() completion() }) } /// Given a URL presents it in a new Reader detail screen /// private func presentReaderDetail(_ url: URL) { let readerDetail = ReaderDetailViewController.controllerWithPostURL(url) viewController?.navigationController?.pushViewController(readerDetail, animated: true) } /// Given a URL presents it in a web view controller screen /// /// - Parameter url: the URL to be loaded private func presentWebViewController(_ url: URL) { var url = url if url.host == nil { if let postURL = permaLinkURL { url = URL(string: url.absoluteString, relativeTo: postURL)! } } let configuration = WebViewControllerConfiguration(url: url) configuration.authenticateWithDefaultAccount() configuration.addsWPComReferrer = true let controller = WebViewControllerFactory.controller(configuration: configuration) let navController = LightNavigationController(rootViewController: controller) viewController?.present(navController, animated: true) } /// Report to the callback that the post failed to load private func reportPostLoadFailure() { postLoadFailureBlock?() // We'll nil out the failure block so we don't perform multiple callbacks postLoadFailureBlock = nil } /// Change post's inUse property and saves the context private func postInUse(_ inUse: Bool) { guard let context = post?.managedObjectContext else { return } post?.inUse = inUse coreDataStack.save(context) } private func showLikesList() { guard let post = post else { return } let controller = ReaderDetailLikesListController(post: post, totalLikes: totalLikes) viewController?.navigationController?.pushViewController(controller, animated: true) } /// Index the post in Spotlight private func indexReaderPostInSpotlight() { guard let post = post else { return } SearchManager.shared.indexItem(post) } // MARK: - Analytics /// Bump WP App Analytics /// private func bumpStats() { guard let readerPost = post else { return } let isOfflineView = ReachabilityUtils.isInternetReachable() ? "no" : "yes" let detailType = readerPost.topic?.type == ReaderSiteTopic.TopicType ? DetailAnalyticsConstants.TypePreviewSite : DetailAnalyticsConstants.TypeNormal var properties = ReaderHelpers.statsPropertiesForPost(readerPost, andValue: nil, forKey: nil) properties[DetailAnalyticsConstants.TypeKey] = detailType properties[DetailAnalyticsConstants.OfflineKey] = isOfflineView // Track related post tapped if let simplePost = remoteSimplePost { switch simplePost.postType { case .local: WPAnalytics.track(.readerRelatedPostFromSameSiteClicked, properties: properties) case .global: WPAnalytics.track(.readerRelatedPostFromOtherSiteClicked, properties: properties) default: DDLogError("Unknown related post type: \(String(describing: simplePost.postType))") } } // Track open WPAppAnalytics.track(.readerArticleOpened, withProperties: properties) if let railcar = readerPost.railcarDictionary() { WPAppAnalytics.trackTrainTracksInteraction(.readerArticleOpened, withProperties: railcar) } } /// Bump post page view /// private func bumpPageViewsForPost() { guard let readerPost = post else { return } ReaderHelpers.bumpPageViewForPost(readerPost) } private struct DetailAnalyticsConstants { static let TypeKey = "post_detail_type" static let TypeNormal = "normal" static let TypePreviewSite = "preview_site" static let OfflineKey = "offline_view" static let PixelStatReferrer = "https://wordpress.com/" } } // MARK: - ReaderDetailHeaderViewDelegate extension ReaderDetailCoordinator: ReaderDetailHeaderViewDelegate { func didTapBlogName() { previewSite() } func didTapMenuButton(_ sender: UIView) { showMenu(sender) } func didTapTagButton() { showTag() } func didTapHeaderAvatar() { previewSite() } func didTapFollowButton(completion: @escaping () -> Void) { followSite(completion: completion) } func didSelectTopic(_ topic: String) { showTopic(topic) } } // MARK: - ReaderDetailFeaturedImageViewDelegate extension ReaderDetailCoordinator: ReaderDetailFeaturedImageViewDelegate { func didTapFeaturedImage(_ sender: CachedAnimatedImageView) { showFeaturedImage(sender) } } // MARK: - ReaderDetailLikesViewDelegate extension ReaderDetailCoordinator: ReaderDetailLikesViewDelegate { func didTapLikesView() { showLikesList() } } // MARK: - ReaderDetailToolbarDelegate extension ReaderDetailCoordinator: ReaderDetailToolbarDelegate { func didTapLikeButton(isLiked: Bool) { guard let userAvatarURL = accountService.defaultWordPressComAccount()?.avatarURL else { return } self.view?.updateSelfLike(with: isLiked ? userAvatarURL : nil) } } // MARK: - State Restoration extension ReaderDetailCoordinator { static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { guard let path = coder.decodeObject(forKey: restorablePostObjectURLKey) as? String else { return nil } let context = ContextManager.sharedInstance().mainContext guard let url = URL(string: path), let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: url) else { return nil } guard let post = (try? context.existingObject(with: objectID)) as? ReaderPost else { return nil } return ReaderDetailViewController.controllerWithPost(post) } func encodeRestorableState(with coder: NSCoder) { if let post = post { coder.encode(post.objectID.uriRepresentation().absoluteString, forKey: type(of: self).restorablePostObjectURLKey) } } }
gpl-2.0
693a3c1739c606addc8f776c849fb9a1
37.00289
165
0.604114
5.477609
false
false
false
false
Amefuri/ZSwiftKit
ZSwiftKit/Classes/Helper+L10N.swift
1
804
// // Helper+L10N.swift // pointube // // Created by peerapat atawatana on 9/8/2559 BE. // Copyright © 2559 DaydreamClover. All rights reserved. // import Foundation import UIKit public extension Helper { struct L10N { public static func setText(_ target:AnyObject, text:String) { if target is UILabel { let target = target as! UILabel target.text = text } else if target is UIButton { let target = target as! UIButton target.setTitle(text, for: UIControl.State()) } else if target is UIBarButtonItem { let target = target as! UIBarButtonItem target.title = text } else if target is UITextField { let target = target as! UITextField target.placeholder = text } } } }
mit
c74072f836416293aa75dbed46a8d562
21.942857
65
0.617684
4.139175
false
false
false
false
gaelfoppolo/handicarparking
HandiParking/HandiParking/LTMorphingLabel/LTMorphingLabel+Sparkle.swift
1
5345
// // LTMorphingLabel+Sparkle.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2015 Lex Tang, http://LexTang.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension LTMorphingLabel { func _maskedImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight) UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight) String(charLimbo.char).drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let newRect = CGRectMake( charLimbo.rect.origin.x, charLimbo.rect.origin.y, charLimbo.rect.size.width, maskedHeight) return (newImage, newRect) } func SparkleLoad() { _startClosures["Sparkle\(LTMorphingPhaseStart)"] = { self.emitterView.removeAllEmit() } _progressClosures["Sparkle\(LTMorphingPhaseManipulateProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.5 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } _effectClosures["Sparkle\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self._originRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0) } _effectClosures["Sparkle\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in if char != " " { let rect = self._newRects[index] let emitterPosition = CGPointMake( rect.origin.x + rect.size.width / 2.0, CGFloat(progress) * rect.size.height * 0.9 + rect.origin.y) self.emitterView.createEmitter("c\(index)", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 1) layer.renderMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 300.0 cell.scaleSpeed = self.font.pointSize / 300.0 * -1.5 cell.color = self.textColor.CGColor cell.birthRate = Float(self.font.pointSize) * Float(arc4random_uniform(7) + 3) }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self._newRects[index], alpha: CGFloat(self.morphingProgress), size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } _drawingClosures["Sparkle\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self._maskedImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress) charImage.drawInRect(rect) return true } return false } _skipFramesClosures["Sparkle\(LTMorphingPhaseSkipFrames)"] = { return 1 } } }
gpl-3.0
3defe9ed3f67e3231c19074f27f798e9
39.431818
121
0.583474
4.937095
false
false
false
false
CD1212/Doughnut
Pods/GRDB.swift/GRDB/Core/Support/Foundation/NSNumber.swift
3
2806
import Foundation private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) /// NSNumber adopts DatabaseValueConvertible extension NSNumber : DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { // Don't lose precision: store integers that fits in Int64 as Int64 if let decimal = self as? NSDecimalNumber, decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min { return int64Value.databaseValue } switch String(cString: objCType) { case "c": return Int64(int8Value).databaseValue case "C": return Int64(uint8Value).databaseValue case "s": return Int64(int16Value).databaseValue case "S": return Int64(uint16Value).databaseValue case "i": return Int64(int32Value).databaseValue case "I": return Int64(uint32Value).databaseValue case "l": return Int64(intValue).databaseValue case "L": let uint = uintValue GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database") return Int64(uint).databaseValue case "q": return Int64(int64Value).databaseValue case "Q": let uint64 = uint64Value GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database") return Int64(uint64).databaseValue case "f": return Double(floatValue).databaseValue case "d": return doubleValue.databaseValue case "B": return boolValue.databaseValue case let objCType: // Assume a GRDB bug: there is no point throwing any error. fatalError("DatabaseValueConvertible: Unsupported NSNumber type: \(objCType)") } } /// Returns an NSNumber initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { switch dbValue.storage { case .int64(let int64): return self.init(value: int64) case .double(let double): return self.init(value: double) default: return nil } } }
gpl-3.0
6c28776568e1c50f5f614bcfb26b44be
40.880597
194
0.626515
4.905594
false
false
false
false
vector-im/vector-ios
Riot/Modules/Call/Views/CallAudioRouteView.swift
1
2778
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Reusable class CallAudioRouteView: UIView { @IBOutlet private weak var iconImageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var selectedIconImageView: UIImageView! @IBOutlet private weak var bottomLineView: UIView! let route: MXiOSAudioOutputRoute private let isSelected: Bool private let isBottomLineHidden: Bool private var theme: Theme = ThemeService.shared().theme init(withRoute route: MXiOSAudioOutputRoute, isSelected: Bool, isBottomLineHidden: Bool = false) { self.route = route self.isSelected = isSelected self.isBottomLineHidden = isBottomLineHidden super.init(frame: .zero) loadNibContent() setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { selectedIconImageView.isHidden = !isSelected bottomLineView.isHidden = isBottomLineHidden switch route.routeType { case .builtIn: iconImageView.image = Asset.Images.callAudioRouteBuiltin.image titleLabel.text = route.name case .loudSpeakers: iconImageView.image = Asset.Images.callAudioRouteSpeakers.image titleLabel.text = VectorL10n.callMoreActionsAudioUseDevice case .externalWired, .externalBluetooth, .externalCar: iconImageView.image = Asset.Images.callAudioRouteHeadphones.image titleLabel.text = route.name } update(theme: theme) } } extension CallAudioRouteView: NibOwnerLoadable {} extension CallAudioRouteView: Themable { func update(theme: Theme) { self.theme = theme backgroundColor = theme.colors.navigation iconImageView.tintColor = theme.colors.secondaryContent titleLabel.textColor = theme.colors.primaryContent titleLabel.font = theme.fonts.body selectedIconImageView.tintColor = theme.colors.primaryContent bottomLineView.backgroundColor = theme.colors.secondaryContent } }
apache-2.0
4a0f240eea16abc08616735dcbe21478
32.071429
77
0.688985
4.839721
false
false
false
false