hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
14313ac082dbb49017c78f8ecaa99055d3c0ca57
5,442
// // ClosestPointsUITests.swift // ClosestPointsUITests // // Created by Robert Huston on 1/1/17. // Copyright © 2017 Pinpoint Dynamics. All rights reserved. // import XCTest class ClosestPointsUITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. app = XCUIApplication() // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. app.launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. app.terminate() app = nil super.tearDown() } func test_CanSetNumberOfPointsToFive() { let window = app.windows["Window"] let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) let numberOfPointsScrollView = window.scrollViews.otherElements.children(matching: .textField) numberOfPointsBox.children(matching: .button).element.click() numberOfPointsScrollView.element(boundBy: 0).click() window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "5") } func test_CanSetNumberOfPointsToOneHundred() { let window = app.windows["Window"] let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) let numberOfPointsScrollView = window.scrollViews.otherElements.children(matching: .textField) numberOfPointsBox.children(matching: .button).element.click() numberOfPointsScrollView.element(boundBy: 4).click() window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "100") } func test_CanSetNumberOfPointsToOneThousand() { let window = app.windows["Window"] // Bah! Stupid Apple keeps changing how we do UI testing. Make up yer minds! window/*@START_MENU_TOKEN@*/.comboBoxes/*[[".groups.comboBoxes",".comboBoxes"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .button).element.click() window/*@START_MENU_TOKEN@*/.scrollBars/*[[".groups",".comboBoxes",".scrollViews.scrollBars",".scrollBars"],[[[-1,3],[-1,2],[-1,1,2],[-1,0,1]],[[-1,3],[-1,2],[-1,1,2]],[[-1,3],[-1,2]]],[0]]@END_MENU_TOKEN@*/.children(matching: .button).element(boundBy: 0).click() window/*@START_MENU_TOKEN@*/.scrollViews/*[[".groups",".comboBoxes.scrollViews",".scrollViews"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.otherElements.children(matching: .textField).element(boundBy: 7).click() window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "1000") } func test_CanSetNumberOfPointsTo1234() { let window = app.windows["Window"] let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) window.groups.containing(.button, identifier:"Generate").children(matching: .comboBox).element.typeText("1234\r") window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "1234") } func test_LimitsNumberOfPointsToNoLessThan2() { let window = app.windows["Window"] let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) window.groups.containing(.button, identifier:"Generate").children(matching: .comboBox).element.typeText("1\r") window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "2") } func test_LimitsNumberOfPointsToNoMoreThan100000() { let window = app.windows["Window"] let numberOfPointsBox = window.comboBoxes.element(boundBy: 0) window.groups.containing(.button, identifier:"Generate").children(matching: .comboBox).element.typeText("123456\r") window/*@START_MENU_TOKEN@*/.buttons["Generate"]/*[[".groups.buttons[\"Generate\"]",".buttons[\"Generate\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.click() let pointsValue = numberOfPointsBox.value as! String XCTAssertEqual(pointsValue, "100000") } }
43.887097
271
0.658214
e9e422795e5c00ed16b5850e08849c2ef105487d
14,694
// // Node.swift // FRAuth // // Copyright (c) 2019 ForgeRock. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // import Foundation import FRCore /** Node class is the core abstraction within an authentication tree. Trees are made up of nodes, which may modify the shared state and/or request input from the user via Callbacks. Node is also a representation of each step in the authentication flow, and keeps unique identifier and its state of the authentication flow. Node must be submitted to OpenAM to proceed or finish the authentication flow. Submitting the Node object returns one of following: * Result of expected type, if available * Another Node object instance to continue on the authentication flow * An error, if occurred during the authentication flow */ @objc(FRNode) public class Node: NSObject { // MARK: - Public properties /// A list of Callback for the state @objc public var callbacks: [Callback] = [] /// authId for the authentication flow @objc public var authId: String /// Unique UUID String value of initiated AuthService flow @objc public var authServiceId: String /// Stage attribute in Page Node @objc public var stage: String? /// Header attribute in Page Node @objc public var pageHeader: String? /// Description attribute in Page Node @objc public var pageDescription: String? /// Designated AuthService name defined in OpenAM var serviceName: String /// authIndexType value in AM var authIndexType: String /// ServerConfig information for AuthService/Node API communication var serverConfig: ServerConfig /// OAuth2Client information for AuthService/Node API communication var oAuth2Config: OAuth2Client? /// Optional SessionManager for SDK's abstraction layer var sessionManager: SessionManager? /// TokenManager instance to manage, and persist authenticated session var tokenManager: TokenManager? // MARK: - Init /// Designated initialization method for Node; AuthService process will initialize Node with given response from OpenAM /// /// - Parameters: /// - authServiceId: Unique UUID for current AuthService flow /// - authServiceResponse: JSON response object of AuthService in OpenAM /// - serverConfig: ServerConfig object for AuthService/Node communication /// - serviceName: Service name for AuthService (TreeName) /// - authIndexType: authIndexType value in AM (default to 'service') /// - oAuth2Config: (Optional) OAuth2Client object for AuthService/Node communication for abstraction layer /// - Throws: AuthError error may be thrown from parsing AuthService response, and parsing Callback(s) init?(_ authServiceId: String, _ authServiceResponse: [String: Any], _ serverConfig: ServerConfig, _ serviceName: String, _ authIndexType: String, _ oAuth2Config: OAuth2Client? = nil, _ sessionManager: SessionManager? = nil, _ tokenManager: TokenManager? = nil) throws { guard let authId = authServiceResponse[OpenAM.authId] as? String else { FRLog.e("Invalid response: missing 'authId'") throw AuthError.invalidAuthServiceResponse("missing or invalid 'authId'") } self.authServiceId = authServiceId self.stage = authServiceResponse[OpenAM.stage] as? String self.pageHeader = authServiceResponse[OpenAM.header] as? String self.pageDescription = authServiceResponse[OpenAM.description] as? String self.serverConfig = serverConfig self.serviceName = serviceName self.authIndexType = authIndexType self.oAuth2Config = oAuth2Config self.authId = authId self.sessionManager = sessionManager self.tokenManager = tokenManager if let callbacks = authServiceResponse[OpenAM.callbacks] as? [[String: Any]] { for callback in callbacks { // Validate if callback response contains type guard let callbackType = callback["type"] as? String else { FRLog.e("Invalid response: Callback is missing 'type' \n\t\(callback)") throw AuthError.invalidCallbackResponse(String(describing: callback)) } let callbackObj = try Node.transformCallback(callbackType: callbackType, json: callback) self.callbacks.append(callbackObj) // Support AM 6.5.2 stage property workaround with MetadataCallback if let metadataCallback = callbackObj as? MetadataCallback, let outputs = metadataCallback.response["output"] as? [[String: Any]] { for output in outputs { if let outputName = output["name"] as? String, outputName == "data", let outputValue = output["value"] as? [String: String] { self.stage = outputValue["stage"] } } } } } else { FRLog.e("Invalid response: missing or invalid callback attribute \n\t\(authServiceResponse)") throw AuthError.invalidAuthServiceResponse("missing or invalid callback(S) response \(authServiceResponse)") } } static func transformCallback(callbackType: String, json: [String: Any]) throws -> Callback { // Validate if given callback type is supported guard let callbackClass = CallbackFactory.shared.supportedCallbacks[callbackType] else { FRLog.e("Unsupported callback: Callback is not supported in SDK \n\t\(json)") throw AuthError.unsupportedCallback("callback type, \(callbackType), is not supported") } let callback = try callbackClass.init(json: json) return callback } // MARK: - Public methods /// Submits current Node object with Callback(s) and its given value(s) to OpenAM to proceed on authentication flow. /// /// - Parameter completion: NodeCompletion callback which returns the result of Node submission. public func next<T>(completion:@escaping NodeCompletion<T>) { if T.self as AnyObject? === Token.self { next { (token: Token?, node, error) in completion(token as? T, node, error) } } else if T.self as AnyObject? === AccessToken.self { next { (token: AccessToken?, node, error) in completion(token as? T, node, error) } } else if T.self as AnyObject? === FRUser.self { next { (user: FRUser?, node, error) in completion(user as? T, node, error) } } else { completion(nil, nil, AuthError.invalidGenericType) } } // MARK: Private/internal methods to handle different expected type of result /// Submits current node, and returns FRUser instance if result of node returns SSO TOken /// /// - Parameter completion: NodeCompletion<FRUser> callback that returns FRUser upon completion fileprivate func next(completion:@escaping NodeCompletion<FRUser>) { FRLog.v("Called") if let currentUser = FRUser.currentUser { FRLog.i("FRUser.currentUser retrieved from SessionManager; ignoring Node submit") completion(currentUser, nil, nil) } else { self.next { (accessToken: AccessToken?, node, error) in if let token = accessToken { let user = FRUser(token: token, serverConfig: self.serverConfig) self.sessionManager?.setCurrentUser(user: user) completion(user, nil, nil) } else { completion(nil, node, error) } } } } /// Submits current node, and returns AccessToken instance if result of node returns SSO TOken /// /// - Parameter completion: NodeCompletion<AccessToken> callback that returns AccessToken upon completion fileprivate func next(completion:@escaping NodeCompletion<AccessToken>) { FRLog.v("Called") if let accessToken = try? self.sessionManager?.getAccessToken() { FRLog.i("access_token retrieved from SessionManager; ignoring Node submit") completion(accessToken, nil, nil) } else { self.next { (token: Token?, node, error) in if let tokenId = token { // If OAuth2Client is provided (for abstraction layer) if let oAuth2Client = self.oAuth2Config { // Exchange 'tokenId' (SSOToken) to OAuth2 token set oAuth2Client.exchangeToken(token: tokenId, completion: { (accessToken, error) in // Return an error if failed if let error = error { completion(nil, nil, error) } else { if let token = accessToken { try? self.sessionManager?.setAccessToken(token: token) } // Return AccessToken completion(accessToken, nil, nil) } }) } else { completion(nil, nil, AuthError.invalidOAuth2Client) } } else { completion(nil, node, error) } } } } /// Submits current node, and returns Token instance if result of node returns SSO TOken /// /// - Parameter completion: NodeCompletion<Token> callback that returns Token upon completion fileprivate func next(completion:@escaping NodeCompletion<Token>) { let thisRequest = self.buildAuthServiceRequest() FRRestClient.invoke(request: thisRequest, action: Action(type: .AUTHENTICATE, payload: ["tree": self.serviceName, "type": self.authIndexType])) { (result) in switch result { case .success(let response, _): // If authId received if let _ = response[OpenAM.authId] { do { let node = try Node(self.authServiceId, response, self.serverConfig, self.serviceName, self.authIndexType, self.oAuth2Config, self.sessionManager, self.tokenManager) completion(nil, node, nil) } catch let authError as AuthError { completion(nil, nil, authError) } catch { completion(nil, nil, error) } } else if let tokenId = response[OpenAM.tokenId] as? String { let token = Token(tokenId) if let sessionManager = self.sessionManager, let tokenManager = self.tokenManager { let currentSessionToken = sessionManager.getSSOToken() if let _ = try? tokenManager.retrieveAccessTokenFromKeychain(), token.value != currentSessionToken?.value { FRLog.w("SDK identified existing Session Token (\(currentSessionToken?.value ?? "nil")) and received Session Token (\(token.value))'s mismatch; to avoid misled information, SDK automatically revokes OAuth2 token set issued with existing Session Token.") tokenManager.revokeAndEndSession { (error) in FRLog.i("OAuth2 token set was revoked due to mismatch of Session Tokens; \(error?.localizedDescription ?? "")") } } sessionManager.setSSOToken(ssoToken: token) } completion(token, nil, nil) } else { completion(nil, nil, nil) } break case .failure(let error): completion(nil, nil, error) break } } } // - MARK: Private request build helper methods /// Builds Dictionary object for request parameter with given list of Callback(s) /// /// - Returns: Dictionary object containing all values of Callback(s), and AuthService information @objc func buildRequestPayload() -> [String:Any] { var payload: [String: Any] = [:] payload[OpenAM.authId] = self.authId var callbacks: [Any] = [] for callback:Callback in self.callbacks { callbacks.append(callback.buildResponse()) } payload[OpenAM.callbacks] = callbacks return payload } /// Builds Request object for current Node /// /// - Returns: Request object for OpenAM AuthTree submit func buildAuthServiceRequest() -> Request { // AM 6.5.2 - 7.0.0 // // Endpoint: /json/realms/authenticate // API Version: resource=2.1,protocol=1.0 var header: [String: String] = [:] header[OpenAM.acceptAPIVersion] = OpenAM.apiResource21 + "," + OpenAM.apiProtocol10 return Request(url: self.serverConfig.authenticateURL, method: .POST, headers: header, bodyParams: self.buildRequestPayload(), urlParams: [:], requestType: .json, responseType: .json, timeoutInterval: self.serverConfig.timeout) } // - MARK: Objective-C Compatibility @objc(nextWithUserCompletion:) @available(swift, obsoleted: 1.0) public func nextWithUserCompletion(completion:@escaping NodeCompletion<FRUser>) { self.next(completion: completion) } @objc(nextWithAccessTokenCompletion:) @available(swift, obsoleted: 1.0) public func nextWithAccessTokenCompletion(completion:@escaping NodeCompletion<AccessToken>) { self.next(completion: completion) } @objc(nextWithTokenCompletion:) @available(swift, obsoleted: 1.0) public func nextWithTokenCompletion(completion:@escaping NodeCompletion<Token>) { self.next(completion: completion) } }
43.994012
451
0.595345
723f3c6eb24a656365829a45a850cb59bba2b446
2,366
// // UIBezierPath+extensions.swift // Project Name: Pods // // Created by Rakesh Sharma on 10/07/19. // // // #if os(iOS) import Foundation import UIKit extension UIBezierPath { static func ID_Initialize(square: CGRect, numberOfSides: UInt, cornerRadius: CGFloat) -> UIBezierPath? { guard square.width == square.height else { return nil } let squareWidth = square.width guard (numberOfSides > 0) && (cornerRadius >= 0.0) && (2.0 * cornerRadius < squareWidth) && !square.isInfinite && !square.isEmpty && !square.isNull else { return nil } let bezierPath = UIBezierPath() let theta = 2.0 * .pi / CGFloat(numberOfSides) let halfTheta = 0.5 * theta let offset: CGFloat = cornerRadius * CGFloat(tan(halfTheta)) var length = squareWidth - bezierPath.lineWidth if numberOfSides % 4 > 0 { length = length * cos(halfTheta) } let sideLength = length * CGFloat(tan(halfTheta)) let p1 = 0.5 * (squareWidth + sideLength) - offset let p2 = squareWidth - 0.5 * (squareWidth - length) var point = CGPoint(x: p1, y: p2) var angle = CGFloat.pi bezierPath.move(to: point) for _ in 0..<numberOfSides { let x1 = CGFloat(point.x) + ((sideLength - offset * 2.0) * CGFloat(cos(angle))) let y1 = CGFloat(point.y) + ((sideLength - offset * 2.0) * CGFloat(sin(angle))) point = CGPoint(x: x1, y: y1) bezierPath.addLine(to: point) let centerX = point.x + cornerRadius * CGFloat(cos(angle + 0.5 * .pi)) let centerY = point.y + cornerRadius * CGFloat(sin(angle + 0.5 * .pi)) let center = CGPoint(x: centerX, y: centerY) let startAngle = CGFloat(angle) - 0.5 * .pi let endAngle = CGFloat(angle) + CGFloat(theta) - 0.5 * .pi bezierPath.addArc(withCenter: center, radius: cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) point = bezierPath.currentPoint angle += theta } bezierPath.close() return bezierPath } } #endif
31.131579
155
0.543533
6a04acb0f3c89201077c211a7f9e536170efac6f
603
import WMF extension UITabBar: Themeable { public func apply(theme: Theme) { barTintColor = theme.colors.chromeBackground unselectedItemTintColor = theme.colors.unselected isTranslucent = false } } extension UITabBarItem: Themeable { public func apply(theme: Theme) { badgeColor = theme.colors.accent setBadgeTextAttributes(theme.tabBarItemBadgeTextAttributes, for: .normal) setTitleTextAttributes(theme.tabBarTitleTextAttributes, for: .normal) setTitleTextAttributes(theme.tabBarSelectedTitleTextAttributes, for: .selected) } }
31.736842
87
0.729685
089c49877ccd0a51dfc51a30a65f4cf33f04831c
3,189
// // Distribution.swift // ZamzamCore // // Created by Basem Emara on 1/29/17. // Copyright © 2017 Zamzam Inc. All rights reserved. // import Foundation.NSBundle /// Provides details of the current app. public protocol Distribution {} // MARK: - App public extension Distribution { /// App's name. var appDisplayName: String? { // http://stackoverflow.com/questions/28254377/get-app-name-in-swift Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String } /// App's bundle ID. var appBundleID: String? { Bundle.main.bundleIdentifier } /// App's current version. var appVersion: String? { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } /// App current build number. var appBuild: String? { Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String } } // MARK: - Environment public extension Distribution { /// Check if app is an extension target. var isAppExtension: Bool { Bundle.main.bundlePath.hasSuffix(".appex") } /// Check if app is running in TestFlight mode. var isInTestFlight: Bool { // https://stackoverflow.com/questions/18282326/how-can-i-detect-if-the-currently-running-app-was-installed-from-the-app-store !isRunningOnSimulator && Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" && !isAdHocDistributed } /// Check if app is ad-hoc distributed. var isAdHocDistributed: Bool { // https://stackoverflow.com/questions/18282326/how-can-i-detect-if-the-currently-running-app-was-installed-from-the-app-store Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil } /// Check if application is running on simulator (read-only). var isRunningOnSimulator: Bool { // http://stackoverflow.com/questions/24869481/detect-if-app-is-being-built-for-device-or-simulator-in-swift #if targetEnvironment(simulator) return true #else return false #endif } /// Check if application is running in App Store environment. var isRunningInAppStore: Bool { // https://stackoverflow.com/questions/18282326/how-can-i-detect-if-the-currently-running-app-was-installed-from-the-app-store !isRunningOnSimulator && !isInTestFlight && !isRunningOnSimulator } } // MARK: - Device public extension Distribution { var manufacturer: String { "Apple" } var platform: String { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "macOS" #endif } } #if !os(macOS) import UIKit.UIDevice public extension Distribution { var deviceName: String { UIDevice.current.name } var deviceModel: String { UIDevice.current.model } var deviceIdentifier: String { UIDevice.current.identifierForVendor?.uuidString ?? "" } var osName: String { UIDevice.current.systemName } var osVersion: String { UIDevice.current.systemVersion } } #endif
30.084906
134
0.683913
5b300750d0157ff788f7b310b9c5398a6ff3d87b
811
// // String+MD5.swift // The Hitchhiker Prophecy // // Created by Nada Kamel on 15/03/2021. // Copyright © 2021 SWVL. All rights reserved. // import Foundation import CryptoKit //import CommonCrypto extension String { var md5: String { let computed = Insecure.MD5.hash(data: self.data(using: .utf8)!) return computed.map { String(format: "%02hhx", $0) }.joined() } // var md5: String { // let data = Data(self.utf8) // let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in // var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) // CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) // return hash // } // return hash.map { String(format: "%02x", $0) }.joined() // } }
27.965517
89
0.602959
e8d924ff7c4e8e34f32d9a955cdb06a06145470b
1,434
// // AppDelegate.swift // Tumblr_Lab_October_2019 // // Created by Romell Bolton on 10/12/19. // Copyright © 2019 Romell Bolton. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.736842
179
0.750349
26ebd122adc0ef5645b4348b77c2d0c79f7e51fe
6,808
// // settings.swift // Battery // // Created by Serhiy Mytrovtsiy on 15/07/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import StatsKit import ModuleKit import SystemConfiguration internal class Settings: NSView, Settings_v { public var callback: (() -> Void) = {} public var callbackWhenUpdateNumberOfProcesses: (() -> Void) = {} private let title: String private let store: UnsafePointer<Store> private var button: NSPopUpButton? private var numberOfProcesses: Int = 8 private let lowLevelsList: [String] = ["Disabled", "0.03", "0.05", "0.1", "0.15", "0.2", "0.25", "0.3", "0.4", "0.5"] private let highLevelsList: [String] = ["Disabled", "0.5", "0.6", "0.7", "0.75", "0.8", "0.85", "0.9", "0.95", "0.97", "1.0"] private var lowLevelNotification: String { get { return self.store.pointee.string(key: "\(self.title)_lowLevelNotification", defaultValue: "0.15") } } private var highLevelNotification: String { get { return self.store.pointee.string(key: "\(self.title)_highLevelNotification", defaultValue: "Disabled") } } private var timeFormat: String = "short" public init(_ title: String, store: UnsafePointer<Store>) { self.title = title self.store = store self.numberOfProcesses = store.pointee.int(key: "\(self.title)_processes", defaultValue: self.numberOfProcesses) self.timeFormat = store.pointee.string(key: "\(self.title)_timeFormat", defaultValue: self.timeFormat) super.init(frame: CGRect( x: 0, y: 0, width: Constants.Settings.width - (Constants.Settings.margin*2), height: 0 )) self.canDrawConcurrently = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func load(widgets: [widget_t]) { self.subviews.forEach{ $0.removeFromSuperview() } let rowHeight: CGFloat = 30 let num: CGFloat = widgets.filter{ $0 == .battery }.isEmpty ? 3 : 4 let height: CGFloat = ((rowHeight + Constants.Settings.margin) * num) + Constants.Settings.margin let lowLevels: [String] = self.lowLevelsList.map { (v: String) -> String in if let level = Double(v) { return "\(Int(level*100))%" } return v } let highLevels: [String] = self.highLevelsList.map { (v: String) -> String in if let level = Double(v) { return "\(Int(level*100))%" } return v } self.addSubview(SelectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-1), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), title: LocalizedString("Low level notification"), action: #selector(changeUpdateIntervalLow), items: lowLevels, selected: self.lowLevelNotification == "Disabled" ? self.lowLevelNotification : "\(Int((Double(self.lowLevelNotification) ?? 0)*100))%" )) self.addSubview(SelectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-2), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), title: LocalizedString("High level notification"), action: #selector(changeUpdateIntervalHigh), items: highLevels, selected: self.highLevelNotification == "Disabled" ? self.highLevelNotification : "\(Int((Double(self.highLevelNotification) ?? 0)*100))%" )) self.addSubview(SelectTitleRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * (num-3), width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), title: LocalizedString("Number of top processes"), action: #selector(changeNumberOfProcesses), items: NumbersOfProcesses.map{ "\($0)" }, selected: "\(self.numberOfProcesses)" )) if !widgets.filter({ $0 == .battery }).isEmpty { self.addSubview(SelectRow( frame: NSRect( x: Constants.Settings.margin, y: Constants.Settings.margin + (rowHeight + Constants.Settings.margin) * 0, width: self.frame.width - (Constants.Settings.margin*2), height: rowHeight ), title: LocalizedString("Time format"), action: #selector(toggleTimeFormat), items: ShortLong, selected: self.timeFormat )) } self.setFrameSize(NSSize(width: self.frame.width, height: height)) } @objc private func changeUpdateIntervalLow(_ sender: NSMenuItem) { if sender.title == "Disabled" { store.pointee.set(key: "\(self.title)_lowLevelNotification", value: sender.title) } else if let value = Double(sender.title.replacingOccurrences(of: "%", with: "")) { store.pointee.set(key: "\(self.title)_lowLevelNotification", value: "\(value/100)") } } @objc private func changeUpdateIntervalHigh(_ sender: NSMenuItem) { if sender.title == "Disabled" { store.pointee.set(key: "\(self.title)_highLevelNotification", value: sender.title) } else if let value = Double(sender.title.replacingOccurrences(of: "%", with: "")) { store.pointee.set(key: "\(self.title)_highLevelNotification", value: "\(value/100)") } } @objc private func changeNumberOfProcesses(_ sender: NSMenuItem) { if let value = Int(sender.title) { self.numberOfProcesses = value self.store.pointee.set(key: "\(self.title)_processes", value: value) self.callbackWhenUpdateNumberOfProcesses() } } @objc private func toggleTimeFormat(_ sender: NSMenuItem) { guard let key = sender.representedObject as? String else { return } self.timeFormat = key self.store.pointee.set(key: "\(self.title)_timeFormat", value: key) self.callback() } }
39.812865
150
0.577262
d5813105ed31d7abf87c04b6e297000e8ac2227c
2,211
// // AppDelegate.swift // AlamofireSample // // Created by Rudson Lima on 7/21/16. // Copyright © 2016 Rudson Lima. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.statusBarStyle = .LightContent 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:. } }
47.042553
285
0.749887
5b8b6d544111923b98cde01655cbc64f9f19b352
6,387
// // FingerprintUITest.swift // DuckDuckGo // // Copyright © 2020 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // swiftlint:disable line_length import XCTest class FingerprintUITest: XCTestCase { override func setUpWithError() throws { continueAfterFailure = false let app = XCUIApplication() app.launchEnvironment = [ "DAXDIALOGS": "false", "ONBOARDING": "false", "VARIANT": "sc", "UITESTING": "true" ] app.launch() // Add a bookmark to edit to a bookmarklet later app.searchFields["searchEntry"].tap() sleep(1) app .searchFields["searchEntry"] .typeText("https://duckduckgo.com\n") sleep(5) // let site load app.buttons["Browsing Menu"].tap() if app.tables.staticTexts["Add Bookmark"].waitForExistence(timeout: 2) { app.tables.staticTexts["Add Bookmark"].tap() } else if app.tables.staticTexts["Bookmarks"].waitForExistence(timeout: 2) { dismissMenu() removeTheBookmark() app.buttons["Browsing Menu"].tap() if app.tables.staticTexts["Add Bookmark"].waitForExistence(timeout: 2) { app.tables.staticTexts["Add Bookmark"].tap() } else { XCTFail("Could not ensure one bookmark is present") } } } override func tearDownWithError() throws { removeTheBookmark() } func dismissMenu() { let app = XCUIApplication() app.otherElements["Browsing Menu Background"].tap() } func removeTheBookmark() { // Remove the bookmark we added let app = XCUIApplication() app.buttons["Browsing Menu"].tap() if app.tables.staticTexts["Bookmarks"].waitForExistence(timeout: 2) { app.tables.staticTexts["Bookmarks"].tap() } let tablesQuery = app.tables tablesQuery.staticTexts["DuckDuckGo — Privacy, simplified."].swipeLeft() tablesQuery.buttons["Delete"].tap() app.navigationBars["Bookmarks"].buttons["Done"].tap() } func test() throws { let app = XCUIApplication() app.buttons["Browsing Menu"].tap() if app.tables.staticTexts["Bookmarks"].waitForExistence(timeout: 2) { app.tables.staticTexts["Bookmarks"].tap() } else { XCTFail("Bookmarks button missing") } // Edit bookmark into bookmarklet to verify fingerprinting test let bookmarksToolbarButtons = app.toolbars.buttons _ = bookmarksToolbarButtons["Edit"].waitForExistence(timeout: 25) bookmarksToolbarButtons["Edit"].tap() if app.tables.staticTexts["DuckDuckGo — Privacy, simplified."].waitForExistence(timeout: 25) { app.staticTexts["DuckDuckGo — Privacy, simplified."].tap() } else { XCTFail("Could not find bookmark") } app.textFields.matching(identifier: "URL").firstMatch.clear() app.textFields.matching(identifier: "URL").firstMatch .typeText("javascript:(function(){const values = {'screen.availTop': 0,'screen.availLeft': 0,'screen.availWidth': screen.width,'screen.availHeight': screen.height,'screen.colorDepth': 24,'screen.pixelDepth': 24,'window.screenY': 0,'window.screenLeft': 0,'navigator.doNotTrack': undefined};var passed = true;var reason = null;for (const test of results.results) {if (values[test.id] !== undefined) {if (values[test.id] !== test.value) {console.log(test.id, values[test.id]);reason = test.id;passed = false;break;}}}var elem = document.createElement('p');elem.innerHTML = (passed) ? 'TEST PASSED' : 'TEST FAILED: ' + reason;document.body.insertBefore(elem, document.body.childNodes[0]);}());") app.navigationBars.buttons["Save"].tap() app.toolbars.buttons["Done"].tap() app.navigationBars.buttons["Done"].tap() // Clear all tabs and data app.toolbars["Toolbar"].buttons["Fire"].tap() app.sheets.scrollViews.otherElements.buttons["Close Tabs and Clear Data"].tap() sleep(2) // Go to fingerprinting test page app .searchFields["searchEntry"] .tap() app .searchFields["searchEntry"] .typeText("https://privacy-test-pages.glitch.me/privacy-protections/fingerprinting/?run\n") let webview = app.webViews.firstMatch XCTAssertTrue(webview.staticTexts["⚠️ Please note that:"].firstMatch.waitForExistence(timeout: 25), "Page not loaded") // Run the new bookmarklet app.buttons["Browsing Menu"].tap() if app.tables.staticTexts["Bookmarks"].waitForExistence(timeout: 2) { app.tables.staticTexts["Bookmarks"].tap() } else { XCTFail("Bookmarks button missing") } app.tables.staticTexts["DuckDuckGo — Privacy, simplified."].tap() // Verify the test passed XCTAssertTrue(webview.staticTexts["TEST PASSED"].waitForExistence(timeout: 25), "Test not run") } } extension XCUIElement { // https://stackoverflow.com/a/38523252 public func clear() { guard let stringValue = self.value as? String else { XCTFail("Tried to clear and enter text into a non string value") return } let lowerRightCorner = self.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.9)) lowerRightCorner.tap() let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: stringValue.count) self.typeText(deleteString) } } // swiftlint:enable line_length
38.017857
703
0.619383
0ada22e357a91106c128967373097271b228913e
251
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a<H { { } { } func a { protocol a { class a<T where H : a { } func p(a<Int>
16.733333
87
0.697211
8facc7449df9c04674e6d6b49d9acbb464656571
517
// // UIDragPreviewParameters.swift // Panda // // Baby of PandaMom. DO NOT TOUCH. // import UIKit @available(iOS 11.0, *) extension PandaChain where Object: UIDragPreviewParameters { @discardableResult public func visiblePath(_ value: UIBezierPathConvertible?) -> PandaChain { object.visiblePath = unbox(value) return self } @discardableResult public func backgroundColor(_ value: UIColor!) -> PandaChain { object.backgroundColor = value return self } }
21.541667
78
0.678917
fc5d987ed61bfa958a03361056b4ae9123dcb7c1
3,377
// // ComposingUnitCollectionViewCell.swift // Compose // // Created by Bruno Bilescky on 05/10/16. // Copyright © 2016 VivaReal. All rights reserved. // import UIKit /// Generic cell that encapsulates another view inside it. You can use it to fast embed other views inside a UICollectionViewCell. public class ComposingUnitCollectionViewCell<V: UIView>: UICollectionViewCell { private var currentConstraints: [NSLayoutConstraint] = [] /// Embeded view (this view is generated by the CollectionViewCell) public private(set) var innerView: V! /// insets applied to the embeded view. public var insets: UIEdgeInsets = .zero override public init(frame: CGRect) { super.init(frame: frame) commonInit(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported.") } private func commonInit(frame: CGRect) { self.isOpaque = false self.backgroundColor = .clear self.innerView = V(frame: frame) self.contentView.addSubview(innerView) self.innerView.translatesAutoresizingMaskIntoConstraints = false } /// You can apply some ViewTraits to the collectionViewCell, in order to configure it /// /// - parameter traits: an array of ViewTraits public func apply(traits: [ViewTraits]) { self.backgroundColor = .clear let result = ViewTraits.mapStyle(from: traits) self.insets = result.insets self.contentView.isOpaque = result.opaque self.contentView.backgroundColor = result.backgroundColor } /// update the insets of the inner view when moving to superview override public func didMoveToSuperview() { super.didMoveToSuperview() update(insets: insets) } /// Needed in order to update with animation the state of the cell /// /// - parameter layoutAttributes: layout attributes defined by the collectionView layout override public func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { UIView.animate(withDuration: 0.33) { self.update(insets: self.insets) self.layoutIfNeeded() } } private func update(insets: UIEdgeInsets, animated: Bool = false) { let superview = self superview.removeConstraints(currentConstraints) self.innerView.removeConstraints(currentConstraints) let leadingConstraint = NSLayoutConstraint(item: self.innerView, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1, constant: insets.left) let topConstraint = NSLayoutConstraint(item: self.innerView, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1, constant: insets.top) let trailingConstraint = NSLayoutConstraint(item: self.innerView, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1, constant: -insets.right) let bottomConstraint = NSLayoutConstraint(item: self.innerView, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1, constant: -insets.bottom) currentConstraints = [leadingConstraint, topConstraint, trailingConstraint, bottomConstraint] superview.addConstraints(currentConstraints) } }
42.746835
195
0.699141
c167909123c220aefd4b4561feea492881572a12
6,764
// // BalanceChongViewController.swift // Shoping // // Created by qiang.c.fu on 2020/4/17. // Copyright © 2020 付强. All rights reserved. // import UIKit class BalanceChongViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var btn: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var input: UITextField! var data: ChongzhiPage? = nil var selectIndex = 0 @IBOutlet weak var hei: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(notificationAction(noti:)), name: NSNotification.Name(rawValue: "weixinpaymethod"), object: nil) self.navigationController?.setNavigationBarHidden(true, animated: true) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.estimatedRowHeight = 150 tableView.rowHeight = UITableView.automaticDimension tableView.backgroundColor = .white input.delegate = self btn.layer.cornerRadius = 10 btn.layer.masksToBounds = true tableView.register(UINib(nibName: "CreatOrderPayTypeTableViewCell", bundle: nil), forCellReuseIdentifier: "CreatOrderPayTypeTableViewCell") // hei.constant = 120 loadData() } deinit { NotificationCenter.default.removeObserver(self) } @objc private func notificationAction(noti: Notification) { let isRet = noti.object as! String if isRet == "1" { //支付成功 CLProgressHUD.showSuccess(in: self.view, delegate: self, title: "充值成功", duration: 2) self.navigationController?.popViewController(animated: true) } else { //支付失败 CLProgressHUD.showError(in: self.view, delegate: self, title: "充值失败,请重试", duration: 2) } } func textField(_ textField:UITextField, shouldChangeCharactersIn range:NSRange, replacementString string:String) ->Bool{             let futureString:NSMutableString=NSMutableString(string: textField.text!)             futureString.insert(string, at: range.location)             var flag = 0;             let limited = 2;//小数点后需要限制的个数             if !futureString.isEqual(to:"") {                 for i in stride(from: futureString.length-1,through:0, by:-1) {                     let char = Character(UnicodeScalar(futureString.character(at: i))!)                     if char=="." {                         if flag>limited {                             return false                         }                         break                     }                     flag+=1                 }             }             return true         } @IBAction func back(_ sender: Any) { self.navigationController?.setNavigationBarHidden(false, animated: false) self.navigationController?.popViewController(animated: true) } @IBAction func submit(_ sender: Any) { let oneChar = (input.text ?? "")[(input.text ?? "").startIndex] if oneChar == "." { CLProgressHUD.showError(in: self.view, delegate: self, title: "请输入正确充值金额", duration: 2) return } API.chongzhi(price: input.text ?? "1", payment_pfn: data?.data.payment[selectIndex].pfn ?? "").request { (result) in switch result { case .success(let data): print(data) if data.data.plugin?.isEmpty ?? true { return } if self.data?.data.payment[self.selectIndex].pfn == "WeChatPay" { self.wechatPay(data: data) } else { self.aliPay(str: data.data.plugin ?? "") } case .failure(let er): print(er) } } } func wechatPay(data: Chongzhi) { let array : Array = (data.data.plugin ?? "").components(separatedBy: ",") let req = PayReq() req.nonceStr = array[1] req.partnerId = array[3] req.prepayId = array[4] req.timeStamp = UInt32(array[6]) ?? 100000 req.package = array[2] req.sign = array[5] WXApi.send(req) { (item) in print(item) if item { } else { CLProgressHUD.showError(in: self.view, delegate: self, title: "充值失败,请重试", duration: 2) } } } func aliPay(str: String) { AlipaySDK.defaultService()?.payOrder(str, fromScheme: "wojiayoupin", callback: { (reslt) in if reslt!["resultStatus"]as! String == "9000" { CLProgressHUD.showSuccess(in: self.view, delegate: self, title: "充值成功", duration: 2) self.navigationController?.popViewController(animated: true) } else { CLProgressHUD.showError(in: self.view, delegate: self, title: "充值失败,请重试", duration: 2) } }) } func loadData() { API.chongzhiPage().request { (result) in switch result { case .success(let data): self.data = data self.hei.constant = CGFloat(60*data.data.payment.count) self.tableView.reloadData() case .failure(let er): print(er) } } } } extension BalanceChongViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data?.data.payment.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CreatOrderPayTypeTableViewCell") as! CreatOrderPayTypeTableViewCell cell.name.text = data?.data.payment[indexPath.row].name ?? "" cell.img.af_setImage(withURL: URL(string: (data?.data.payment[indexPath.row].icon)!)!) if indexPath.row == selectIndex { cell.selectImg.image = UIImage(named: "选中") } else { cell.selectImg.image = UIImage(named: "未选择") } cell.contentView.backgroundColor = .white cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectIndex = indexPath.row self.tableView.reloadData() } }
32.995122
169
0.569929
489e8875ed3c5edf04bfe85f188da2a6976eba4e
34,626
// // Repository.swift // SwiftGit2 // // Created by Matt Diephouse on 11/7/14. // Copyright (c) 2014 GitHub, Inc. All rights reserved. // import Foundation import Clibgit2 public typealias CheckoutProgressBlock = (String?, Int, Int) -> Void public typealias TransportMessageBlock = (String) -> Void public typealias TransportProgressBlock = (git_transfer_progress) -> Void class FetchOptionsPayload { var credentials: Credentials? var sidebandProgress: TransportMessageBlock? var transportProgress: TransportProgressBlock? } /// Helper function used as the libgit2 progress callback in git_checkout_options. /// This is a function with a type signature of git_checkout_progress_cb. private func checkoutProgressCallback(path: UnsafePointer<Int8>?, completedSteps: Int, totalSteps: Int, payload: UnsafeMutableRawPointer?) { if let payload = payload { let buffer = payload.assumingMemoryBound(to: CheckoutProgressBlock.self) let block: CheckoutProgressBlock if completedSteps < totalSteps { block = buffer.pointee } else { block = buffer.move() buffer.deallocate() } block(path.flatMap(String.init(validatingUTF8:)), completedSteps, totalSteps) } } private func sidebandProgressCallback(str: UnsafePointer<Int8>?, len: Int32, payload: UnsafeMutableRawPointer?) -> Int32 { let fetchOptionsPayload: FetchOptionsPayload = Unmanaged.fromOpaque(.init(payload!)).takeUnretainedValue() if let sidebandProgress = fetchOptionsPayload.sidebandProgress { let data = Data(bytes: .init(str!), count: Int(len)) if let string = String.init(data: data, encoding: .utf8) { sidebandProgress(string) } } return 0 } private func transferProgressCallback(stats: UnsafePointer<git_transfer_progress>?, payload: UnsafeMutableRawPointer?) -> Int32 { let fetchOptionsPayload: FetchOptionsPayload = Unmanaged.fromOpaque(.init(payload!)).takeUnretainedValue() if let transportProgress = fetchOptionsPayload.transportProgress { transportProgress(stats!.pointee) } return 0 } /// Helper function for initializing libgit2 git_checkout_options. /// /// :param: strategy The strategy to be used when checking out the repo, see CheckoutStrategy /// :param: progress A block that's called with the progress of the checkout. /// :returns: Returns a git_checkout_options struct with the progress members set. private func checkoutOptions(strategy: CheckoutStrategy, progress: CheckoutProgressBlock? = nil) -> git_checkout_options { // Do this because GIT_CHECKOUT_OPTIONS_INIT is unavailable in swift let pointer = UnsafeMutablePointer<git_checkout_options>.allocate(capacity: 1) git_checkout_init_options(pointer, UInt32(GIT_CHECKOUT_OPTIONS_VERSION)) var options = pointer.move() pointer.deallocate() options.checkout_strategy = strategy.gitCheckoutStrategy.rawValue if progress != nil { options.progress_cb = checkoutProgressCallback let blockPointer = UnsafeMutablePointer<CheckoutProgressBlock>.allocate(capacity: 1) blockPointer.initialize(to: progress!) options.progress_payload = UnsafeMutableRawPointer(blockPointer) } return options } private func fetchOptions(payload: UnsafeMutableRawPointer) -> git_fetch_options { let pointer = UnsafeMutablePointer<git_fetch_options>.allocate(capacity: 1) git_fetch_init_options(pointer, UInt32(GIT_FETCH_OPTIONS_VERSION)) var options = pointer.move() pointer.deallocate() options.callbacks.payload = .init(payload) options.callbacks.sideband_progress = sidebandProgressCallback options.callbacks.transfer_progress = transferProgressCallback options.callbacks.credentials = credentialsCallback return options } private func cloneOptions(bare: Bool = false, localClone: Bool = false, fetchOptions: git_fetch_options? = nil, checkoutOptions: git_checkout_options? = nil) -> git_clone_options { let pointer = UnsafeMutablePointer<git_clone_options>.allocate(capacity: 1) git_clone_init_options(pointer, UInt32(GIT_CLONE_OPTIONS_VERSION)) var options = pointer.move() pointer.deallocate() options.bare = bare ? 1 : 0 if localClone { options.local = GIT_CLONE_NO_LOCAL } if let checkoutOptions = checkoutOptions { options.checkout_opts = checkoutOptions } if let fetchOptions = fetchOptions { options.fetch_opts = fetchOptions } return options } /// A git repository. public final class Repository { /// MARK: - Initialize libgit2 library, must be called by client before anything else public static func initialize_libgit2() { git_libgit2_init() } // MARK: - Creating Repositories /// Create a new repository at the given URL. /// /// URL - The URL of the repository. /// /// Returns a `Result` with a `Repository` or an error. public class func create(at url: URL) -> Result<Repository, NSError> { var pointer: OpaquePointer? = nil let result = url.withUnsafeFileSystemRepresentation { git_repository_init(&pointer, $0, 0) } guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_repository_init")) } let repository = Repository(pointer!) return Result.success(repository) } /// Load the repository at the given URL. /// /// URL - The URL of the repository. /// /// Returns a `Result` with a `Repository` or an error. public class func at(_ url: URL) -> Result<Repository, NSError> { var pointer: OpaquePointer? = nil let result = url.withUnsafeFileSystemRepresentation { git_repository_open(&pointer, $0) } guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_repository_open")) } let repository = Repository(pointer!) return Result.success(repository) } /// Clone the repository from a given URL. /// /// remoteURL - The URL of the remote repository /// localURL - The URL to clone the remote repository into /// localClone - Will not bypass the git-aware transport, even if remote is local. /// bare - Clone remote as a bare repository. /// credentials - Credentials to be used when connecting to the remote. /// checkoutStrategy - The checkout strategy to use, if being checked out. /// checkoutProgress - A block that's called with the progress of the checkout. /// sidebandProgress - A block that's called with the textual progress from the remote. /// transferProgress - A block that's called with the current count of progress done by the indexer. /// /// Returns a `Result` with a `Repository` or an error. public class func clone(from remoteURL: URL, to localURL: URL, localClone: Bool = false, bare: Bool = false, credentials: Credentials = .default, checkoutStrategy: CheckoutStrategy = .Safe, checkoutProgress: CheckoutProgressBlock? = nil, sidebandProgress: TransportMessageBlock? = nil, transferProgress: TransportProgressBlock? = nil) -> Result<Repository, NSError> { let fetchOptionsPayload = FetchOptionsPayload() fetchOptionsPayload.credentials = credentials fetchOptionsPayload.sidebandProgress = sidebandProgress fetchOptionsPayload.transportProgress = transferProgress var options = cloneOptions( bare: bare, localClone: localClone, fetchOptions: fetchOptions(payload: Unmanaged.passUnretained(fetchOptionsPayload).toOpaque()), checkoutOptions: checkoutOptions(strategy: checkoutStrategy, progress: checkoutProgress)) var pointer: OpaquePointer? = nil let remoteURLString = (remoteURL as NSURL).isFileReferenceURL() ? remoteURL.path : remoteURL.absoluteString let result = localURL.withUnsafeFileSystemRepresentation { localPath in git_clone(&pointer, remoteURLString, localPath, &options) } guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_clone")) } let repository = Repository(pointer!) return Result.success(repository) } // MARK: - Initializers /// Create an instance with a libgit2 `git_repository` object. /// /// The Repository assumes ownership of the `git_repository` object. public init(_ pointer: OpaquePointer) { self.pointer = pointer let path = git_repository_workdir(pointer) self.directoryURL = path.map({ URL(fileURLWithPath: String(validatingUTF8: $0)!, isDirectory: true) }) } deinit { git_repository_free(pointer) } // MARK: - Properties /// The underlying libgit2 `git_repository` object. public let pointer: OpaquePointer /// The URL of the repository's working directory, or `nil` if the /// repository is bare. public let directoryURL: URL? // MARK: - Object Lookups /// Load a libgit2 object and transform it to something else. /// /// oid - The OID of the object to look up. /// type - The type of the object to look up. /// transform - A function that takes the libgit2 object and transforms it /// into something else. /// /// Returns the result of calling `transform` or an error if the object /// cannot be loaded. private func withGitObject<T>(_ oid: OID, type: git_object_t, transform: (OpaquePointer) -> Result<T, NSError>) -> Result<T, NSError> { var pointer: OpaquePointer? = nil var oid = oid.oid let result = git_object_lookup(&pointer, self.pointer, &oid, type) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_object_lookup")) } let value = transform(pointer!) git_object_free(pointer) return value } private func withGitObject<T>(_ oid: OID, type: git_object_t, transform: (OpaquePointer) -> T) -> Result<T, NSError> { return withGitObject(oid, type: type) { Result.success(transform($0)) } } private func withGitObjects<T>(_ oids: [OID], type: git_object_t, transform: ([OpaquePointer]) -> Result<T, NSError>) -> Result<T, NSError> { var pointers = [OpaquePointer]() defer { for pointer in pointers { git_object_free(pointer) } } for oid in oids { var pointer: OpaquePointer? = nil var oid = oid.oid let result = git_object_lookup(&pointer, self.pointer, &oid, type) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_object_lookup")) } pointers.append(pointer!) } return transform(pointers) } /// Loads the object with the given OID. /// /// oid - The OID of the blob to look up. /// /// Returns a `Blob`, `Commit`, `Tag`, or `Tree` if one exists, or an error. public func object(_ oid: OID) -> Result<ObjectType, NSError> { return withGitObject(oid, type: GIT_OBJECT_ANY) { object in let type = git_object_type(object) if type == Blob.type { return Result.success(Blob(object)) } else if type == Commit.type { return Result.success(Commit(object)) } else if type == Tag.type { return Result.success(Tag(object)) } else if type == Tree.type { return Result.success(Tree(object)) } let error = NSError( domain: "org.libgit2.SwiftGit2", code: 1, userInfo: [ NSLocalizedDescriptionKey: "Unrecognized git_object_t '\(type)' for oid '\(oid)'.", ] ) return Result.failure(error) } } /// Loads the blob with the given OID. /// /// oid - The OID of the blob to look up. /// /// Returns the blob if it exists, or an error. public func blob(_ oid: OID) -> Result<Blob, NSError> { return withGitObject(oid, type: GIT_OBJECT_BLOB) { Blob($0) } } /// Loads the commit with the given OID. /// /// oid - The OID of the commit to look up. /// /// Returns the commit if it exists, or an error. public func commit(_ oid: OID) -> Result<Commit, NSError> { return withGitObject(oid, type: GIT_OBJECT_COMMIT) { Commit($0) } } /// Loads the tag with the given OID. /// /// oid - The OID of the tag to look up. /// /// Returns the tag if it exists, or an error. public func tag(_ oid: OID) -> Result<Tag, NSError> { return withGitObject(oid, type: GIT_OBJECT_TAG) { Tag($0) } } /// Loads the tree with the given OID. /// /// oid - The OID of the tree to look up. /// /// Returns the tree if it exists, or an error. public func tree(_ oid: OID) -> Result<Tree, NSError> { return withGitObject(oid, type: GIT_OBJECT_TREE) { Tree($0) } } /// Loads the referenced object from the pointer. /// /// pointer - A pointer to an object. /// /// Returns the object if it exists, or an error. public func object<T>(from pointer: PointerTo<T>) -> Result<T, NSError> { return withGitObject(pointer.oid, type: pointer.type) { T($0) } } /// Loads the referenced object from the pointer. /// /// pointer - A pointer to an object. /// /// Returns the object if it exists, or an error. public func object(from pointer: Pointer) -> Result<ObjectType, NSError> { switch pointer { case let .blob(oid): return blob(oid).map { $0 as ObjectType } case let .commit(oid): return commit(oid).map { $0 as ObjectType } case let .tag(oid): return tag(oid).map { $0 as ObjectType } case let .tree(oid): return tree(oid).map { $0 as ObjectType } } } // MARK: - Remote Lookups /// Loads all the remotes in the repository. /// /// Returns an array of remotes, or an error. public func allRemotes() -> Result<[Remote], NSError> { let pointer = UnsafeMutablePointer<git_strarray>.allocate(capacity: 1) let result = git_remote_list(pointer, self.pointer) guard result == GIT_OK.rawValue else { pointer.deallocate() return Result.failure(NSError(gitError: result, pointOfFailure: "git_remote_list")) } let strarray = pointer.pointee let remotes: [Result<Remote, NSError>] = strarray.map { return self.remote(named: $0) } git_strarray_free(pointer) pointer.deallocate() return remotes.aggregateResult() } private func remoteLookup<A>(named name: String, _ callback: (Result<OpaquePointer, NSError>) -> A) -> A { var pointer: OpaquePointer? = nil defer { git_remote_free(pointer) } let result = git_remote_lookup(&pointer, self.pointer, name) guard result == GIT_OK.rawValue else { return callback(.failure(NSError(gitError: result, pointOfFailure: "git_remote_lookup"))) } return callback(.success(pointer!)) } /// Load a remote from the repository. /// /// name - The name of the remote. /// /// Returns the remote if it exists, or an error. public func remote(named name: String) -> Result<Remote, NSError> { return remoteLookup(named: name) { $0.map(Remote.init) } } /// Download new data and update tips public func fetch(_ remote: Remote) -> Result<(), NSError> { return remoteLookup(named: remote.name) { remote in remote.flatMap { pointer in var opts = git_fetch_options() let resultInit = git_fetch_init_options(&opts, UInt32(GIT_FETCH_OPTIONS_VERSION)) assert(resultInit == GIT_OK.rawValue) let result = git_remote_fetch(pointer, nil, &opts, nil) guard result == GIT_OK.rawValue else { let err = NSError(gitError: result, pointOfFailure: "git_remote_fetch") return .failure(err) } return .success(()) } } } // MARK: - Reference Lookups /// Load all the references with the given prefix (e.g. "refs/heads/") public func references(withPrefix prefix: String) -> Result<[ReferenceType], NSError> { let pointer = UnsafeMutablePointer<git_strarray>.allocate(capacity: 1) let result = git_reference_list(pointer, self.pointer) guard result == GIT_OK.rawValue else { pointer.deallocate() return Result.failure(NSError(gitError: result, pointOfFailure: "git_reference_list")) } let strarray = pointer.pointee let references = strarray .filter { $0.hasPrefix(prefix) } .map { self.reference(named: $0) } git_strarray_free(pointer) pointer.deallocate() return references.aggregateResult() } /// Load the reference with the given long name (e.g. "refs/heads/master") /// /// If the reference is a branch, a `Branch` will be returned. If the /// reference is a tag, a `TagReference` will be returned. Otherwise, a /// `Reference` will be returned. public func reference(named name: String) -> Result<ReferenceType, NSError> { var pointer: OpaquePointer? = nil let result = git_reference_lookup(&pointer, self.pointer, name) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_reference_lookup")) } let value = referenceWithLibGit2Reference(pointer!) git_reference_free(pointer) return Result.success(value) } /// Load and return a list of all local branches. public func localBranches() -> Result<[Branch], NSError> { return references(withPrefix: "refs/heads/") .map { (refs: [ReferenceType]) in return refs.map { $0 as! Branch } } } /// Load and return a list of all remote branches. public func remoteBranches() -> Result<[Branch], NSError> { return references(withPrefix: "refs/remotes/") .map { (refs: [ReferenceType]) in return refs.map { $0 as! Branch } } } /// Load the local branch with the given name (e.g., "master"). public func localBranch(named name: String) -> Result<Branch, NSError> { return reference(named: "refs/heads/" + name).map { $0 as! Branch } } /// Load the remote branch with the given name (e.g., "origin/master"). public func remoteBranch(named name: String) -> Result<Branch, NSError> { return reference(named: "refs/remotes/" + name).map { $0 as! Branch } } /// Load and return a list of all the `TagReference`s. public func allTags() -> Result<[TagReference], NSError> { return references(withPrefix: "refs/tags/") .map { (refs: [ReferenceType]) in return refs.map { $0 as! TagReference } } } /// Load the tag with the given name (e.g., "tag-2"). public func tag(named name: String) -> Result<TagReference, NSError> { return reference(named: "refs/tags/" + name).map { $0 as! TagReference } } // MARK: - Working Directory /// Load the reference pointed at by HEAD. /// /// When on a branch, this will return the current `Branch`. public func HEAD() -> Result<ReferenceType, NSError> { var pointer: OpaquePointer? = nil let result = git_repository_head(&pointer, self.pointer) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_repository_head")) } let value = referenceWithLibGit2Reference(pointer!) git_reference_free(pointer) return Result.success(value) } /// Set HEAD to the given oid (detached). /// /// :param: oid The OID to set as HEAD. /// :returns: Returns a result with void or the error that occurred. public func setHEAD(_ oid: OID) -> Result<(), NSError> { var oid = oid.oid let result = git_repository_set_head_detached(self.pointer, &oid) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_repository_set_head")) } return Result.success(()) } /// Set HEAD to the given reference. /// /// :param: reference The reference to set as HEAD. /// :returns: Returns a result with void or the error that occurred. public func setHEAD(_ reference: ReferenceType) -> Result<(), NSError> { let result = git_repository_set_head(self.pointer, reference.longName) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_repository_set_head")) } return Result.success(()) } /// Check out HEAD. /// /// :param: strategy The checkout strategy to use. /// :param: progress A block that's called with the progress of the checkout. /// :returns: Returns a result with void or the error that occurred. public func checkout(strategy: CheckoutStrategy, progress: CheckoutProgressBlock? = nil) -> Result<(), NSError> { var options = checkoutOptions(strategy: strategy, progress: progress) let result = git_checkout_head(self.pointer, &options) guard result == GIT_OK.rawValue else { return Result.failure(NSError(gitError: result, pointOfFailure: "git_checkout_head")) } return Result.success(()) } /// Check out the given OID. /// /// :param: oid The OID of the commit to check out. /// :param: strategy The checkout strategy to use. /// :param: progress A block that's called with the progress of the checkout. /// :returns: Returns a result with void or the error that occurred. public func checkout(_ oid: OID, strategy: CheckoutStrategy, progress: CheckoutProgressBlock? = nil) -> Result<(), NSError> { return setHEAD(oid).flatMap { self.checkout(strategy: strategy, progress: progress) } } /// Check out the given reference. /// /// :param: reference The reference to check out. /// :param: strategy The checkout strategy to use. /// :param: progress A block that's called with the progress of the checkout. /// :returns: Returns a result with void or the error that occurred. public func checkout(_ reference: ReferenceType, strategy: CheckoutStrategy, progress: CheckoutProgressBlock? = nil) -> Result<(), NSError> { return setHEAD(reference).flatMap { self.checkout(strategy: strategy, progress: progress) } } /// Load all commits in the specified branch in topological & time order descending /// /// :param: branch The branch to get all commits from /// :returns: Returns a result with array of branches or the error that occurred public func commits(in branch: Branch) -> CommitIterator { let iterator = CommitIterator(repo: self, root: branch.oid.oid) return iterator } /// Get the index for the repo. The caller is responsible for freeing the index. func unsafeIndex() -> Result<OpaquePointer, NSError> { var index: OpaquePointer? = nil let result = git_repository_index(&index, self.pointer) guard result == GIT_OK.rawValue && index != nil else { let err = NSError(gitError: result, pointOfFailure: "git_repository_index") return .failure(err) } return .success(index!) } /// Stage the file(s) under the specified path. public func add(path: String) -> Result<(), NSError> { var dirPointer = UnsafeMutablePointer<Int8>(mutating: (path as NSString).utf8String) var paths = withUnsafeMutablePointer(to: &dirPointer) { git_strarray(strings: $0, count: 1) } return unsafeIndex().flatMap { index in defer { git_index_free(index) } let addResult = git_index_add_all(index, &paths, 0, nil, nil) guard addResult == GIT_OK.rawValue else { return .failure(NSError(gitError: addResult, pointOfFailure: "git_index_add_all")) } // write index to disk let writeResult = git_index_write(index) guard writeResult == GIT_OK.rawValue else { return .failure(NSError(gitError: writeResult, pointOfFailure: "git_index_write")) } return .success(()) } } /// Perform a commit with arbitrary numbers of parent commits. public func commit( tree treeOID: OID, parents: [Commit], message: String, signature: Signature ) -> Result<Commit, NSError> { // create commit signature return signature.makeUnsafeSignature().flatMap { signature in defer { git_signature_free(signature) } var tree: OpaquePointer? = nil var treeOIDCopy = treeOID.oid let lookupResult = git_tree_lookup(&tree, self.pointer, &treeOIDCopy) guard lookupResult == GIT_OK.rawValue else { let err = NSError(gitError: lookupResult, pointOfFailure: "git_tree_lookup") return .failure(err) } defer { git_tree_free(tree) } var msgBuf = git_buf() git_message_prettify(&msgBuf, message, 0, /* ascii for # */ 35) defer { git_buf_free(&msgBuf) } // libgit2 expects a C-like array of parent git_commit pointer var parentGitCommits: [OpaquePointer?] = [] defer { for commit in parentGitCommits { git_commit_free(commit) } } for parentCommit in parents { var parent: OpaquePointer? = nil var oid = parentCommit.oid.oid let lookupResult = git_commit_lookup(&parent, self.pointer, &oid) guard lookupResult == GIT_OK.rawValue else { let err = NSError(gitError: lookupResult, pointOfFailure: "git_commit_lookup") return .failure(err) } parentGitCommits.append(parent!) } let parentsContiguous = ContiguousArray(parentGitCommits) return parentsContiguous.withUnsafeBufferPointer { unsafeBuffer in var commitOID = git_oid() let parentsPtr = UnsafeMutablePointer(mutating: unsafeBuffer.baseAddress) let result = git_commit_create( &commitOID, self.pointer, "HEAD", signature, signature, "UTF-8", msgBuf.ptr, tree, parents.count, parentsPtr ) guard result == GIT_OK.rawValue else { return .failure(NSError(gitError: result, pointOfFailure: "git_commit_create")) } return commit(OID(commitOID)) } } } /// Perform a commit of the staged files with the specified message and signature, /// assuming we are not doing a merge and using the current tip as the parent. public func commit(message: String, signature: Signature) -> Result<Commit, NSError> { return unsafeIndex().flatMap { index in defer { git_index_free(index) } var treeOID = git_oid() let treeResult = git_index_write_tree(&treeOID, index) guard treeResult == GIT_OK.rawValue else { let err = NSError(gitError: treeResult, pointOfFailure: "git_index_write_tree") return .failure(err) } var parentID = git_oid() let nameToIDResult = git_reference_name_to_id(&parentID, self.pointer, "HEAD") guard nameToIDResult == GIT_OK.rawValue else { return .failure(NSError(gitError: nameToIDResult, pointOfFailure: "git_reference_name_to_id")) } return commit(OID(parentID)).flatMap { parentCommit in commit(tree: OID(treeOID), parents: [parentCommit], message: message, signature: signature) } } } // MARK: - Diffs public func diff(for commit: Commit) -> Result<Diff, NSError> { guard !commit.parents.isEmpty else { // Initial commit in a repository return self.diff(from: nil, to: commit.oid) } var mergeDiff: OpaquePointer? = nil defer { git_object_free(mergeDiff) } for parent in commit.parents { let error = self.diff(from: parent.oid, to: commit.oid) { switch $0 { case .failure(let error): return error case .success(let newDiff): if mergeDiff == nil { mergeDiff = newDiff } else { let mergeResult = git_diff_merge(mergeDiff, newDiff) guard mergeResult == GIT_OK.rawValue else { return NSError(gitError: mergeResult, pointOfFailure: "git_diff_merge") } } return nil } } if error != nil { return Result<Diff, NSError>.failure(error!) } } return .success(Diff(mergeDiff!)) } private func diff(from oldCommitOid: OID?, to newCommitOid: OID?, transform: (Result<OpaquePointer, NSError>) -> NSError?) -> NSError? { assert(oldCommitOid != nil || newCommitOid != nil, "It is an error to pass nil for both the oldOid and newOid") var oldTree: OpaquePointer? = nil defer { git_object_free(oldTree) } if let oid = oldCommitOid { switch unsafeTreeForCommitId(oid) { case .failure(let error): return transform(.failure(error)) case .success(let value): oldTree = value } } var newTree: OpaquePointer? = nil defer { git_object_free(newTree) } if let oid = newCommitOid { switch unsafeTreeForCommitId(oid) { case .failure(let error): return transform(.failure(error)) case .success(let value): newTree = value } } var diff: OpaquePointer? = nil let diffResult = git_diff_tree_to_tree(&diff, self.pointer, oldTree, newTree, nil) guard diffResult == GIT_OK.rawValue else { return transform(.failure(NSError(gitError: diffResult, pointOfFailure: "git_diff_tree_to_tree"))) } return transform(Result<OpaquePointer, NSError>.success(diff!)) } /// Memory safe private func diff(from oldCommitOid: OID?, to newCommitOid: OID?) -> Result<Diff, NSError> { assert(oldCommitOid != nil || newCommitOid != nil, "It is an error to pass nil for both the oldOid and newOid") var oldTree: Tree? = nil if let oldCommitOid = oldCommitOid { switch safeTreeForCommitId(oldCommitOid) { case .failure(let error): return .failure(error) case .success(let value): oldTree = value } } var newTree: Tree? = nil if let newCommitOid = newCommitOid { switch safeTreeForCommitId(newCommitOid) { case .failure(let error): return .failure(error) case .success(let value): newTree = value } } if oldTree != nil && newTree != nil { return withGitObjects([oldTree!.oid, newTree!.oid], type: GIT_OBJECT_TREE) { objects in var diff: OpaquePointer? = nil let diffResult = git_diff_tree_to_tree(&diff, self.pointer, objects[0], objects[1], nil) return processTreeToTreeDiff(diffResult, diff: diff) } } else if let tree = oldTree { return withGitObject(tree.oid, type: GIT_OBJECT_TREE, transform: { tree in var diff: OpaquePointer? = nil let diffResult = git_diff_tree_to_tree(&diff, self.pointer, tree, nil, nil) return processTreeToTreeDiff(diffResult, diff: diff) }) } else if let tree = newTree { return withGitObject(tree.oid, type: GIT_OBJECT_TREE, transform: { tree in var diff: OpaquePointer? = nil let diffResult = git_diff_tree_to_tree(&diff, self.pointer, nil, tree, nil) return processTreeToTreeDiff(diffResult, diff: diff) }) } return .failure(NSError(gitError: -1, pointOfFailure: "diff(from: to:)")) } private func processTreeToTreeDiff(_ diffResult: Int32, diff: OpaquePointer?) -> Result<Diff, NSError> { guard diffResult == GIT_OK.rawValue else { return .failure(NSError(gitError: diffResult, pointOfFailure: "git_diff_tree_to_tree")) } let diffObj = Diff(diff!) git_diff_free(diff) return .success(diffObj) } private func processDiffDeltas(_ diffResult: OpaquePointer) -> Result<[Diff.Delta], NSError> { var returnDict = [Diff.Delta]() let count = git_diff_num_deltas(diffResult) for i in 0..<count { let delta = git_diff_get_delta(diffResult, i) let gitDiffDelta = Diff.Delta((delta?.pointee)!) returnDict.append(gitDiffDelta) } let result = Result<[Diff.Delta], NSError>.success(returnDict) return result } private func safeTreeForCommitId(_ oid: OID) -> Result<Tree, NSError> { return withGitObject(oid, type: GIT_OBJECT_COMMIT) { commit in let treeId = git_commit_tree_id(commit) return tree(OID(treeId!.pointee)) } } /// Caller responsible to free returned tree with git_object_free private func unsafeTreeForCommitId(_ oid: OID) -> Result<OpaquePointer, NSError> { var commit: OpaquePointer? = nil var oid = oid.oid let commitResult = git_object_lookup(&commit, self.pointer, &oid, GIT_OBJECT_COMMIT) guard commitResult == GIT_OK.rawValue else { return .failure(NSError(gitError: commitResult, pointOfFailure: "git_object_lookup")) } var tree: OpaquePointer? = nil let treeId = git_commit_tree_id(commit) let treeResult = git_object_lookup(&tree, self.pointer, treeId, GIT_OBJECT_TREE) git_object_free(commit) guard treeResult == GIT_OK.rawValue else { return .failure(NSError(gitError: treeResult, pointOfFailure: "git_object_lookup")) } return Result<OpaquePointer, NSError>.success(tree!) } // MARK: - Status public func status(options: StatusOptions = [.includeUntracked]) -> Result<[StatusEntry], NSError> { var returnArray = [StatusEntry]() // Do this because GIT_STATUS_OPTIONS_INIT is unavailable in swift let pointer = UnsafeMutablePointer<git_status_options>.allocate(capacity: 1) let optionsResult = git_status_init_options(pointer, UInt32(GIT_STATUS_OPTIONS_VERSION)) guard optionsResult == GIT_OK.rawValue else { return .failure(NSError(gitError: optionsResult, pointOfFailure: "git_status_init_options")) } var listOptions = pointer.move() listOptions.flags = options.rawValue pointer.deallocate() var unsafeStatus: OpaquePointer? = nil defer { git_status_list_free(unsafeStatus) } let statusResult = git_status_list_new(&unsafeStatus, self.pointer, &listOptions) guard statusResult == GIT_OK.rawValue, let unwrapStatusResult = unsafeStatus else { return .failure(NSError(gitError: statusResult, pointOfFailure: "git_status_list_new")) } let count = git_status_list_entrycount(unwrapStatusResult) for i in 0..<count { let s = git_status_byindex(unwrapStatusResult, i) if s?.pointee.status.rawValue == GIT_STATUS_CURRENT.rawValue { continue } let statusEntry = StatusEntry(from: s!.pointee) returnArray.append(statusEntry) } return .success(returnArray) } // MARK: - Validity/Existence Check /// - returns: `.success(true)` iff there is a git repository at `url`, /// `.success(false)` if there isn't, /// and a `.failure` if there's been an error. public static func isValid(url: URL) -> Result<Bool, NSError> { var pointer: OpaquePointer? let result = url.withUnsafeFileSystemRepresentation { git_repository_open_ext(&pointer, $0, GIT_REPOSITORY_OPEN_NO_SEARCH.rawValue, nil) } switch result { case GIT_ENOTFOUND.rawValue: return .success(false) case GIT_OK.rawValue: return .success(true) default: return .failure(NSError(gitError: result, pointOfFailure: "git_repository_open_ext")) } } } private extension Array { func aggregateResult<Value, Error>() -> Result<[Value], Error> where Element == Result<Value, Error> { var values: [Value] = [] for result in self { switch result { case .success(let value): values.append(value) case .failure(let error): return .failure(error) } } return .success(values) } }
34.283168
142
0.690117
61a7afad393da25d2126dadf66fdb49b2fd1c2df
6,995
// // SBPagesController.swift // SBPagesController // // Created by Salim Braksa on 11/7/15. // Copyright © 2015 Braksa. All rights reserved. // import UIKit import Cartography public protocol SBPagesControllerDataSource: class { func pagesSlider(viewControllerForIndex index: Int) -> UIViewController func numberOfViews() -> Int } public protocol SBPagesControllerDelegate: class { func scrollingFromPageIndex(index: Int, toIndex: Int, progress: Double) func willScrollFromPageIndex(index: Int, toIndex: Int) } public class SBPagesController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { // MARK: Properties public weak var dataSource: SBPagesControllerDataSource? public weak var delegate: SBPagesControllerDelegate? private var views: [UIView] = [] var scrollView: SBScrollView! private var currentIndex: Int! private var currentView: UIView { return views[currentIndex] } private var cancelViewDidAppear = false var initiallyDraggedFromLeft: Bool! // ScrollView behavior var scrollIsCancelled: Bool = false // MARK: View Lifecycle override public func viewDidLoad() { super.viewDidLoad() // Initialize & configure scrollView scrollView = SBScrollView() scrollView.delegate = self scrollView.pagingEnabled = true scrollView.alwaysBounceVertical = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false view.addSubview(scrollView) constrain(scrollView) { scrollView in scrollView.edges == scrollView.superview!.edges } automaticallyAdjustsScrollViewInsets = false // Observe scrollView.addObserver(scrollView, forKeyPath: "contentOffset", options: [.New, .Old], context: nil) // Set scrollView closures scrollView.willMoveFromIndex = { fromIndex, toIndex in self.currentIndex = fromIndex self.delegate?.willScrollFromPageIndex(fromIndex, toIndex: toIndex) } scrollView.movingFromIndex = { fromIndex, toIndex, progress in self.delegate?.scrollingFromPageIndex(fromIndex, toIndex: toIndex, progress: progress) } // Get all views let maximumNumberOfViews = dataSource?.numberOfViews() ?? 0 for i in 0..<maximumNumberOfViews { guard let viewController = dataSource?.pagesSlider(viewControllerForIndex: i) else { return } addChildViewController(viewController) viewController.didMoveToParentViewController(self) } // Get views from view controllers views = childViewControllers.map { return $0.view } // Add all views to scrollView for view in views { view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] view.bounds.size = self.scrollView.bounds.size self.scrollView.addSubview(view) } // At the beginning let's assume that currentIndex and previousIndex are equal currentIndex = 0 } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Don't the parent vc to adjust scrollView insets automatically parentViewController?.automaticallyAdjustsScrollViewInsets = false // Send back view.superview?.sendSubviewToBack(view) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Do not observe contentOffset while relayouting subviews self.scrollView.removeObserver(self.scrollView, forKeyPath: "contentOffset") // Set contentSize scrollView.contentSize = CGSize(width: view.bounds.width * CGFloat(dataSource?.numberOfViews() ?? 0), height: view.bounds.height) // Set views origin for (index, view) in views.enumerate() { let positionX = self.view.bounds.width * CGFloat(index) view.frame.origin = CGPoint(x: positionX, y: 0) } // Scroll to to current index guard let index = currentIndex else { return } scrollToPage(forIndex: index, animated: false) } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Observe contentOffset after relayouting subviews scrollView.addObserver(scrollView, forKeyPath: "contentOffset", options: [.New, .Old], context: nil) } // MARK: Gesture Recognize Delegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // MARK: ScrollView Delegate public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { currentIndex = Int(scrollView.contentOffset.x / scrollView.bounds.width) } // MARK: Internal Helpers private func showPageForIndex(index: Int) { // If index is out of range, then nothing to show if index >= views.count || index < 0 { return } // Okey, index is not out of range, let's get that view let view = views[index] // Check if that view is not shown if view.window != nil { return } scrollView.addSubview(view) } public func scrollToPage(forIndex index: Int, animated: Bool) { // Update scrollView direction if index > currentIndex { scrollView.scrollDirection = .RightToLeft } else if index < currentIndex { scrollView.scrollDirection = .LeftToRight } // Calculate destination point let x = view.bounds.width * CGFloat(index) let y: CGFloat = 0 let point = CGPoint(x: x, y: y) // Scroll scrollView.setContentOffset(point, animated: animated) // Update currentIndex currentIndex = index } private func getVisiblePageIndex() -> Int { return Int(scrollView.contentOffset.x / view.bounds.width) } func panGestureHandler(recognizer: UIPanGestureRecognizer) { // Associated view guard let view = recognizer.view else { return } let velocityX = recognizer.velocityInView(view).x // Switch state switch recognizer.state { case .Began: // Set bool if velocityX != 0 { initiallyDraggedFromLeft = velocityX > 0 } case .Changed: if initiallyDraggedFromLeft == nil { initiallyDraggedFromLeft = velocityX > 0 } case .Ended, .Cancelled, .Failed: break default: break } } }
28.319838
178
0.636741
5d4fca8514e5b2aae5a9d70509f75c70a74890ac
672
// // CALayer+Aimate.swift // danmuDemo // // Created by idlebook on 2017/4/26. // Copyright © 2017年 PM. All rights reserved. // import UIKit extension CALayer{ /// 暂停动画 func pauseAnimate(){ let pausedTime = self.convertTime(CACurrentMediaTime(), from: nil) self.speed = 0.0 self.timeOffset = pausedTime } /// 恢复动画 func resumeAnimate(){ let pausedTime = self.timeOffset self.speed = 1.0 self.timeOffset = 0.0 self.beginTime = 0.0 let timeSincePause = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime self.beginTime = timeSincePause } }
21
91
0.602679
8756f6bd62ce10a72afb72ae0d72604ec1532126
18,395
// // DMItemUses.swift // // Created by Philip DesJean on 9/11/16 // Copyright (c) . All rights reserved. // import Foundation import SwiftyJSON open class DMItemUses: NSObject, NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kDMItemUsesCourierKey: String = "courier" internal let kDMItemUsesTangoKey: String = "tango" internal let kDMItemUsesPowerTreadsKey: String = "power_treads" internal let kDMItemUsesTangoSingleKey: String = "tango_single" internal let kDMItemUsesRingOfBasiliusKey: String = "ring_of_basilius" internal let kDMItemUsesShadowAmuletKey: String = "shadow_amulet" internal let kDMItemUsesBloodthornKey: String = "bloodthorn" internal let kDMItemUsesClarityKey: String = "clarity" internal let kDMItemUsesPipeKey: String = "pipe" internal let kDMItemUsesInvisSwordKey: String = "invis_sword" internal let kDMItemUsesTravelBoots2Key: String = "travel_boots_2" internal let kDMItemUsesWardDispenserKey: String = "ward_dispenser" internal let kDMItemUsesMagicWandKey: String = "magic_wand" internal let kDMItemUsesEnchantedMangoKey: String = "enchanted_mango" internal let kDMItemUsesRiverPainter5Key: String = "river_painter5" internal let kDMItemUsesCrimsonGuardKey: String = "crimson_guard" internal let kDMItemUsesGlimmerCapeKey: String = "glimmer_cape" internal let kDMItemUsesSilverEdgeKey: String = "silver_edge" internal let kDMItemUsesUrnOfShadowsKey: String = "urn_of_shadows" internal let kDMItemUsesHoodOfDefianceKey: String = "hood_of_defiance" internal let kDMItemUsesMantaKey: String = "manta" internal let kDMItemUsesTomeOfKnowledgeKey: String = "tome_of_knowledge" internal let kDMItemUsesBfuryKey: String = "bfury" internal let kDMItemUsesMjollnirKey: String = "mjollnir" internal let kDMItemUsesDustKey: String = "dust" internal let kDMItemUsesFlaskKey: String = "flask" internal let kDMItemUsesWardObserverKey: String = "ward_observer" internal let kDMItemUsesOrchidKey: String = "orchid" internal let kDMItemUsesAncientJanggoKey: String = "ancient_janggo" internal let kDMItemUsesAbyssalBladeKey: String = "abyssal_blade" internal let kDMItemUsesMagicStickKey: String = "magic_stick" internal let kDMItemUsesTravelBootsKey: String = "travel_boots" internal let kDMItemUsesBottleKey: String = "bottle" internal let kDMItemUsesBlackKingBarKey: String = "black_king_bar" internal let kDMItemUsesTpscrollKey: String = "tpscroll" internal let kDMItemUsesFaerieFireKey: String = "faerie_fire" internal let kDMItemUsesPhaseBootsKey: String = "phase_boots" internal let kDMItemUsesMoonShardKey: String = "moon_shard" internal let kDMItemUsesSolarCrestKey: String = "solar_crest" internal let kDMItemUsesWardSentryKey: String = "ward_sentry" internal let kDMItemUsesArmletKey: String = "armlet" internal let kDMItemUsesBranchesKey: String = "branches" internal let kDMItemUsesHandOfMidasKey: String = "hand_of_midas" // MARK: Properties open var courier: Int? open var tango: Int? open var powerTreads: Int? open var tangoSingle: Int? open var ringOfBasilius: Int? open var shadowAmulet: Int? open var bloodthorn: Int? open var clarity: Int? open var pipe: Int? open var invisSword: Int? open var travelBoots2: Int? open var wardDispenser: Int? open var magicWand: Int? open var enchantedMango: Int? open var riverPainter5: Int? open var crimsonGuard: Int? open var glimmerCape: Int? open var silverEdge: Int? open var urnOfShadows: Int? open var hoodOfDefiance: Int? open var manta: Int? open var tomeOfKnowledge: Int? open var bfury: Int? open var mjollnir: Int? open var dust: Int? open var flask: Int? open var wardObserver: Int? open var orchid: Int? open var ancientJanggo: Int? open var abyssalBlade: Int? open var magicStick: Int? open var travelBoots: Int? open var bottle: Int? open var blackKingBar: Int? open var tpscroll: Int? open var faerieFire: Int? open var phaseBoots: Int? open var moonShard: Int? open var solarCrest: Int? open var wardSentry: Int? open var armlet: Int? open var branches: Int? open var handOfMidas: Int? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { courier = json[kDMItemUsesCourierKey].int tango = json[kDMItemUsesTangoKey].int powerTreads = json[kDMItemUsesPowerTreadsKey].int tangoSingle = json[kDMItemUsesTangoSingleKey].int ringOfBasilius = json[kDMItemUsesRingOfBasiliusKey].int shadowAmulet = json[kDMItemUsesShadowAmuletKey].int bloodthorn = json[kDMItemUsesBloodthornKey].int clarity = json[kDMItemUsesClarityKey].int pipe = json[kDMItemUsesPipeKey].int invisSword = json[kDMItemUsesInvisSwordKey].int travelBoots2 = json[kDMItemUsesTravelBoots2Key].int wardDispenser = json[kDMItemUsesWardDispenserKey].int magicWand = json[kDMItemUsesMagicWandKey].int enchantedMango = json[kDMItemUsesEnchantedMangoKey].int riverPainter5 = json[kDMItemUsesRiverPainter5Key].int crimsonGuard = json[kDMItemUsesCrimsonGuardKey].int glimmerCape = json[kDMItemUsesGlimmerCapeKey].int silverEdge = json[kDMItemUsesSilverEdgeKey].int urnOfShadows = json[kDMItemUsesUrnOfShadowsKey].int hoodOfDefiance = json[kDMItemUsesHoodOfDefianceKey].int manta = json[kDMItemUsesMantaKey].int tomeOfKnowledge = json[kDMItemUsesTomeOfKnowledgeKey].int bfury = json[kDMItemUsesBfuryKey].int mjollnir = json[kDMItemUsesMjollnirKey].int dust = json[kDMItemUsesDustKey].int flask = json[kDMItemUsesFlaskKey].int wardObserver = json[kDMItemUsesWardObserverKey].int orchid = json[kDMItemUsesOrchidKey].int ancientJanggo = json[kDMItemUsesAncientJanggoKey].int abyssalBlade = json[kDMItemUsesAbyssalBladeKey].int magicStick = json[kDMItemUsesMagicStickKey].int travelBoots = json[kDMItemUsesTravelBootsKey].int bottle = json[kDMItemUsesBottleKey].int blackKingBar = json[kDMItemUsesBlackKingBarKey].int tpscroll = json[kDMItemUsesTpscrollKey].int faerieFire = json[kDMItemUsesFaerieFireKey].int phaseBoots = json[kDMItemUsesPhaseBootsKey].int moonShard = json[kDMItemUsesMoonShardKey].int solarCrest = json[kDMItemUsesSolarCrestKey].int wardSentry = json[kDMItemUsesWardSentryKey].int armlet = json[kDMItemUsesArmletKey].int branches = json[kDMItemUsesBranchesKey].int handOfMidas = json[kDMItemUsesHandOfMidasKey].int } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ open func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if courier != nil { dictionary.updateValue(courier! as AnyObject, forKey: kDMItemUsesCourierKey) } if tango != nil { dictionary.updateValue(tango! as AnyObject, forKey: kDMItemUsesTangoKey) } if powerTreads != nil { dictionary.updateValue(powerTreads! as AnyObject, forKey: kDMItemUsesPowerTreadsKey) } if tangoSingle != nil { dictionary.updateValue(tangoSingle! as AnyObject, forKey: kDMItemUsesTangoSingleKey) } if ringOfBasilius != nil { dictionary.updateValue(ringOfBasilius! as AnyObject, forKey: kDMItemUsesRingOfBasiliusKey) } if shadowAmulet != nil { dictionary.updateValue(shadowAmulet! as AnyObject, forKey: kDMItemUsesShadowAmuletKey) } if bloodthorn != nil { dictionary.updateValue(bloodthorn! as AnyObject, forKey: kDMItemUsesBloodthornKey) } if clarity != nil { dictionary.updateValue(clarity! as AnyObject, forKey: kDMItemUsesClarityKey) } if pipe != nil { dictionary.updateValue(pipe! as AnyObject, forKey: kDMItemUsesPipeKey) } if invisSword != nil { dictionary.updateValue(invisSword! as AnyObject, forKey: kDMItemUsesInvisSwordKey) } if travelBoots2 != nil { dictionary.updateValue(travelBoots2! as AnyObject, forKey: kDMItemUsesTravelBoots2Key) } if wardDispenser != nil { dictionary.updateValue(wardDispenser! as AnyObject, forKey: kDMItemUsesWardDispenserKey) } if magicWand != nil { dictionary.updateValue(magicWand! as AnyObject, forKey: kDMItemUsesMagicWandKey) } if enchantedMango != nil { dictionary.updateValue(enchantedMango! as AnyObject, forKey: kDMItemUsesEnchantedMangoKey) } if riverPainter5 != nil { dictionary.updateValue(riverPainter5! as AnyObject, forKey: kDMItemUsesRiverPainter5Key) } if crimsonGuard != nil { dictionary.updateValue(crimsonGuard! as AnyObject, forKey: kDMItemUsesCrimsonGuardKey) } if glimmerCape != nil { dictionary.updateValue(glimmerCape! as AnyObject, forKey: kDMItemUsesGlimmerCapeKey) } if silverEdge != nil { dictionary.updateValue(silverEdge! as AnyObject, forKey: kDMItemUsesSilverEdgeKey) } if urnOfShadows != nil { dictionary.updateValue(urnOfShadows! as AnyObject, forKey: kDMItemUsesUrnOfShadowsKey) } if hoodOfDefiance != nil { dictionary.updateValue(hoodOfDefiance! as AnyObject, forKey: kDMItemUsesHoodOfDefianceKey) } if manta != nil { dictionary.updateValue(manta! as AnyObject, forKey: kDMItemUsesMantaKey) } if tomeOfKnowledge != nil { dictionary.updateValue(tomeOfKnowledge! as AnyObject, forKey: kDMItemUsesTomeOfKnowledgeKey) } if bfury != nil { dictionary.updateValue(bfury! as AnyObject, forKey: kDMItemUsesBfuryKey) } if mjollnir != nil { dictionary.updateValue(mjollnir! as AnyObject, forKey: kDMItemUsesMjollnirKey) } if dust != nil { dictionary.updateValue(dust! as AnyObject, forKey: kDMItemUsesDustKey) } if flask != nil { dictionary.updateValue(flask! as AnyObject, forKey: kDMItemUsesFlaskKey) } if wardObserver != nil { dictionary.updateValue(wardObserver! as AnyObject, forKey: kDMItemUsesWardObserverKey) } if orchid != nil { dictionary.updateValue(orchid! as AnyObject, forKey: kDMItemUsesOrchidKey) } if ancientJanggo != nil { dictionary.updateValue(ancientJanggo! as AnyObject, forKey: kDMItemUsesAncientJanggoKey) } if abyssalBlade != nil { dictionary.updateValue(abyssalBlade! as AnyObject, forKey: kDMItemUsesAbyssalBladeKey) } if magicStick != nil { dictionary.updateValue(magicStick! as AnyObject, forKey: kDMItemUsesMagicStickKey) } if travelBoots != nil { dictionary.updateValue(travelBoots! as AnyObject, forKey: kDMItemUsesTravelBootsKey) } if bottle != nil { dictionary.updateValue(bottle! as AnyObject, forKey: kDMItemUsesBottleKey) } if blackKingBar != nil { dictionary.updateValue(blackKingBar! as AnyObject, forKey: kDMItemUsesBlackKingBarKey) } if tpscroll != nil { dictionary.updateValue(tpscroll! as AnyObject, forKey: kDMItemUsesTpscrollKey) } if faerieFire != nil { dictionary.updateValue(faerieFire! as AnyObject, forKey: kDMItemUsesFaerieFireKey) } if phaseBoots != nil { dictionary.updateValue(phaseBoots! as AnyObject, forKey: kDMItemUsesPhaseBootsKey) } if moonShard != nil { dictionary.updateValue(moonShard! as AnyObject, forKey: kDMItemUsesMoonShardKey) } if solarCrest != nil { dictionary.updateValue(solarCrest! as AnyObject, forKey: kDMItemUsesSolarCrestKey) } if wardSentry != nil { dictionary.updateValue(wardSentry! as AnyObject, forKey: kDMItemUsesWardSentryKey) } if armlet != nil { dictionary.updateValue(armlet! as AnyObject, forKey: kDMItemUsesArmletKey) } if branches != nil { dictionary.updateValue(branches! as AnyObject, forKey: kDMItemUsesBranchesKey) } if handOfMidas != nil { dictionary.updateValue(handOfMidas! as AnyObject, forKey: kDMItemUsesHandOfMidasKey) } return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { self.courier = aDecoder.decodeObject(forKey: kDMItemUsesCourierKey) as? Int self.tango = aDecoder.decodeObject(forKey: kDMItemUsesTangoKey) as? Int self.powerTreads = aDecoder.decodeObject(forKey: kDMItemUsesPowerTreadsKey) as? Int self.tangoSingle = aDecoder.decodeObject(forKey: kDMItemUsesTangoSingleKey) as? Int self.ringOfBasilius = aDecoder.decodeObject(forKey: kDMItemUsesRingOfBasiliusKey) as? Int self.shadowAmulet = aDecoder.decodeObject(forKey: kDMItemUsesShadowAmuletKey) as? Int self.bloodthorn = aDecoder.decodeObject(forKey: kDMItemUsesBloodthornKey) as? Int self.clarity = aDecoder.decodeObject(forKey: kDMItemUsesClarityKey) as? Int self.pipe = aDecoder.decodeObject(forKey: kDMItemUsesPipeKey) as? Int self.invisSword = aDecoder.decodeObject(forKey: kDMItemUsesInvisSwordKey) as? Int self.travelBoots2 = aDecoder.decodeObject(forKey: kDMItemUsesTravelBoots2Key) as? Int self.wardDispenser = aDecoder.decodeObject(forKey: kDMItemUsesWardDispenserKey) as? Int self.magicWand = aDecoder.decodeObject(forKey: kDMItemUsesMagicWandKey) as? Int self.enchantedMango = aDecoder.decodeObject(forKey: kDMItemUsesEnchantedMangoKey) as? Int self.riverPainter5 = aDecoder.decodeObject(forKey: kDMItemUsesRiverPainter5Key) as? Int self.crimsonGuard = aDecoder.decodeObject(forKey: kDMItemUsesCrimsonGuardKey) as? Int self.glimmerCape = aDecoder.decodeObject(forKey: kDMItemUsesGlimmerCapeKey) as? Int self.silverEdge = aDecoder.decodeObject(forKey: kDMItemUsesSilverEdgeKey) as? Int self.urnOfShadows = aDecoder.decodeObject(forKey: kDMItemUsesUrnOfShadowsKey) as? Int self.hoodOfDefiance = aDecoder.decodeObject(forKey: kDMItemUsesHoodOfDefianceKey) as? Int self.manta = aDecoder.decodeObject(forKey: kDMItemUsesMantaKey) as? Int self.tomeOfKnowledge = aDecoder.decodeObject(forKey: kDMItemUsesTomeOfKnowledgeKey) as? Int self.bfury = aDecoder.decodeObject(forKey: kDMItemUsesBfuryKey) as? Int self.mjollnir = aDecoder.decodeObject(forKey: kDMItemUsesMjollnirKey) as? Int self.dust = aDecoder.decodeObject(forKey: kDMItemUsesDustKey) as? Int self.flask = aDecoder.decodeObject(forKey: kDMItemUsesFlaskKey) as? Int self.wardObserver = aDecoder.decodeObject(forKey: kDMItemUsesWardObserverKey) as? Int self.orchid = aDecoder.decodeObject(forKey: kDMItemUsesOrchidKey) as? Int self.ancientJanggo = aDecoder.decodeObject(forKey: kDMItemUsesAncientJanggoKey) as? Int self.abyssalBlade = aDecoder.decodeObject(forKey: kDMItemUsesAbyssalBladeKey) as? Int self.magicStick = aDecoder.decodeObject(forKey: kDMItemUsesMagicStickKey) as? Int self.travelBoots = aDecoder.decodeObject(forKey: kDMItemUsesTravelBootsKey) as? Int self.bottle = aDecoder.decodeObject(forKey: kDMItemUsesBottleKey) as? Int self.blackKingBar = aDecoder.decodeObject(forKey: kDMItemUsesBlackKingBarKey) as? Int self.tpscroll = aDecoder.decodeObject(forKey: kDMItemUsesTpscrollKey) as? Int self.faerieFire = aDecoder.decodeObject(forKey: kDMItemUsesFaerieFireKey) as? Int self.phaseBoots = aDecoder.decodeObject(forKey: kDMItemUsesPhaseBootsKey) as? Int self.moonShard = aDecoder.decodeObject(forKey: kDMItemUsesMoonShardKey) as? Int self.solarCrest = aDecoder.decodeObject(forKey: kDMItemUsesSolarCrestKey) as? Int self.wardSentry = aDecoder.decodeObject(forKey: kDMItemUsesWardSentryKey) as? Int self.armlet = aDecoder.decodeObject(forKey: kDMItemUsesArmletKey) as? Int self.branches = aDecoder.decodeObject(forKey: kDMItemUsesBranchesKey) as? Int self.handOfMidas = aDecoder.decodeObject(forKey: kDMItemUsesHandOfMidasKey) as? Int } open func encode(with aCoder: NSCoder) { aCoder.encode(courier, forKey: kDMItemUsesCourierKey) aCoder.encode(tango, forKey: kDMItemUsesTangoKey) aCoder.encode(powerTreads, forKey: kDMItemUsesPowerTreadsKey) aCoder.encode(tangoSingle, forKey: kDMItemUsesTangoSingleKey) aCoder.encode(ringOfBasilius, forKey: kDMItemUsesRingOfBasiliusKey) aCoder.encode(shadowAmulet, forKey: kDMItemUsesShadowAmuletKey) aCoder.encode(bloodthorn, forKey: kDMItemUsesBloodthornKey) aCoder.encode(clarity, forKey: kDMItemUsesClarityKey) aCoder.encode(pipe, forKey: kDMItemUsesPipeKey) aCoder.encode(invisSword, forKey: kDMItemUsesInvisSwordKey) aCoder.encode(travelBoots2, forKey: kDMItemUsesTravelBoots2Key) aCoder.encode(wardDispenser, forKey: kDMItemUsesWardDispenserKey) aCoder.encode(magicWand, forKey: kDMItemUsesMagicWandKey) aCoder.encode(enchantedMango, forKey: kDMItemUsesEnchantedMangoKey) aCoder.encode(riverPainter5, forKey: kDMItemUsesRiverPainter5Key) aCoder.encode(crimsonGuard, forKey: kDMItemUsesCrimsonGuardKey) aCoder.encode(glimmerCape, forKey: kDMItemUsesGlimmerCapeKey) aCoder.encode(silverEdge, forKey: kDMItemUsesSilverEdgeKey) aCoder.encode(urnOfShadows, forKey: kDMItemUsesUrnOfShadowsKey) aCoder.encode(hoodOfDefiance, forKey: kDMItemUsesHoodOfDefianceKey) aCoder.encode(manta, forKey: kDMItemUsesMantaKey) aCoder.encode(tomeOfKnowledge, forKey: kDMItemUsesTomeOfKnowledgeKey) aCoder.encode(bfury, forKey: kDMItemUsesBfuryKey) aCoder.encode(mjollnir, forKey: kDMItemUsesMjollnirKey) aCoder.encode(dust, forKey: kDMItemUsesDustKey) aCoder.encode(flask, forKey: kDMItemUsesFlaskKey) aCoder.encode(wardObserver, forKey: kDMItemUsesWardObserverKey) aCoder.encode(orchid, forKey: kDMItemUsesOrchidKey) aCoder.encode(ancientJanggo, forKey: kDMItemUsesAncientJanggoKey) aCoder.encode(abyssalBlade, forKey: kDMItemUsesAbyssalBladeKey) aCoder.encode(magicStick, forKey: kDMItemUsesMagicStickKey) aCoder.encode(travelBoots, forKey: kDMItemUsesTravelBootsKey) aCoder.encode(bottle, forKey: kDMItemUsesBottleKey) aCoder.encode(blackKingBar, forKey: kDMItemUsesBlackKingBarKey) aCoder.encode(tpscroll, forKey: kDMItemUsesTpscrollKey) aCoder.encode(faerieFire, forKey: kDMItemUsesFaerieFireKey) aCoder.encode(phaseBoots, forKey: kDMItemUsesPhaseBootsKey) aCoder.encode(moonShard, forKey: kDMItemUsesMoonShardKey) aCoder.encode(solarCrest, forKey: kDMItemUsesSolarCrestKey) aCoder.encode(wardSentry, forKey: kDMItemUsesWardSentryKey) aCoder.encode(armlet, forKey: kDMItemUsesArmletKey) aCoder.encode(branches, forKey: kDMItemUsesBranchesKey) aCoder.encode(handOfMidas, forKey: kDMItemUsesHandOfMidasKey) } }
45.532178
95
0.788203
01765c9fe07e2c5824017a5c12b71e2c2a79bb12
1,670
// // AlbumsViewModel.swift // JSONPhotos // // Created by Merle Anthony on 21/02/2022. // import Foundation import RxSwift import RxRelay typealias AlbumsViewState = LoadingState<[Album]> protocol AlbumsViewModelType { var viewLoaded: PublishRelay<Void> { get } var retryTap: PublishRelay<Void> { get } func didSelect(photo: Photo) func didSelect(album: Album) var state: BehaviorRelay<AlbumsViewState> { get } } class AlbumsViewModel { let viewLoaded = PublishRelay<Void>() let retryTap = PublishRelay<Void>() let state = BehaviorRelay<AlbumsViewState>(value: .loading) private let disposeBag = DisposeBag() let coordinator: AlbumsCoordinatorType let dataService: AlbumsDataServiceType init( coordinator: AlbumsCoordinatorType, dataService: AlbumsDataServiceType ) { self.coordinator = coordinator self.dataService = dataService setupBindings() } private func setupBindings() { Observable .merge( viewLoaded.asObservable(), retryTap.asObservable()) .flatMap({ [dataService] _ in dataService .fetchAlbums() .map(AlbumsViewState.loaded) .catchAndReturn(.failed) }) .bind(to: state) .disposed(by: disposeBag) } } extension AlbumsViewModel: AlbumsViewModelType { func didSelect( photo: Photo ) { coordinator .showPhoto(photo) } func didSelect( album: Album ) { coordinator .showAlbum(album) } }
21.973684
63
0.606587
d980ae2093584f39e61bc5848eb24c00b9754300
2,464
// // SnippetsPost.swift // SnippetsFramework // // Created by Jonathan Hays on 10/24/18. // Copyright © 2018 Jonathan Hays. All rights reserved. // #if os(macOS) import AppKit import UUSwift #else import UIKit import UUSwift #endif open class SnippetsPost : NSObject { public convenience init(_ dictionary : [String : Any]) { self.init() self.loadFromDictionary(dictionary) } @objc public var identifier = "" @objc public var owner = SnippetsUser() @objc public var htmlText = "" @objc public var path = "" @objc public var publishedDate : Date? @objc public var hasConversation : Bool = false @objc public var replies : [SnippetsPost] = [] @objc public var isDraft : Bool = false } extension SnippetsPost { func loadFromDictionary(_ sourceDictionary : [String : Any]) { var dictionary = sourceDictionary // Test to see if we have the micropub version of this dictionary if let properties = dictionary["properties"] as? [String : Any] { dictionary = properties if let urlArray = dictionary["url"] as? [String]{ self.path = urlArray[0] } if let contentArray = dictionary["content"] as? [String] { self.htmlText = contentArray[0] } if let publishedArray = dictionary["published"] as? [String] { let dateString = publishedArray[0] self.publishedDate = dateString.uuParseDate(format: "yyyy-MM-dd'T'HH:mm:ssZ") } if let draftStatusArray = dictionary["post-status"] as? [String] { let draftStatus = draftStatusArray[0] self.isDraft = (draftStatus == "draft") } } if let microblogDictionary = dictionary["_microblog"] as? [String : Any] { if let conversation = microblogDictionary["is_conversation"] as? NSNumber { self.hasConversation = conversation.intValue > 0 } } if let identifier = dictionary["id"] as? String { self.identifier = identifier } if let postText = dictionary["content_html"] as? String { self.htmlText = postText } if let authorDictionary = dictionary["author"] as? [String : Any] { self.owner.loadFromDictionary(authorDictionary) } if let path = dictionary["url"] as? String { self.path = path } if let dateString = dictionary["date_published"] as? String { self.publishedDate = dateString.uuParseDate(format: "yyyy-MM-dd'T'HH:mm:ssZ") } if let draftStatus = dictionary["post-status"] as? String { self.isDraft = (draftStatus == "draft") } } }
23.245283
81
0.675325
1e9c0d3542702d09b87a0b22705dedd67fec9e64
1,330
// // Helpers.swift // WeScan // // Created by Ayoub Nouri on 10/05/2019. // Copyright © 2019 WeTransfer. All rights reserved. // class Rotation { // MARK: - Params private var rotationAngle = Measurement<UnitAngle>(value: 0, unit: .degrees) private var enhancedImageIsAvailable = false private var isCurrentlyDisplayingEnhancedImage = false var image: UIImage! private let results: ImageScannerResults // MARK: - Init init(results: ImageScannerResults) { self.image = results.scannedImage self.results = results } // MARK: - Methods @objc private func reloadImage() { print("reloadImage") if enhancedImageIsAvailable, isCurrentlyDisplayingEnhancedImage { image = results.enhancedImage?.rotated(by: rotationAngle) ?? results.enhancedImage } else { image = results.scannedImage.rotated(by: rotationAngle) ?? results.scannedImage } // image = results.scannedImage.rotated(by: rotationAngle) } @objc func rotateImage() { print("rotateImage") rotationAngle.value += 90 if rotationAngle.value == 360 { rotationAngle.value = 0 } print("rotateImage \(rotationAngle)") reloadImage() } }
26.078431
94
0.620301
75aa7e2d8716810d45037ef8b21ecb795eff2cab
2,333
// // Open5eSpellDataSourceReader.swift // SwiftUITest // // Created by Thomas Visser on 12/11/2019. // Copyright © 2019 Thomas Visser. All rights reserved. // import Foundation import Foundation import Combine class Open5eSpellDataSourceReader: CompendiumDataSourceReader { static let name = "Open5eSpellDataSourceReader" let dataSource: CompendiumDataSource init(dataSource: CompendiumDataSource) { self.dataSource = dataSource } func read() -> CompendiumDataSourceReaderJob { return Job(data: dataSource.read()) } class Job: CompendiumDataSourceReaderJob { let progress = Progress(totalUnitCount: 0) let items: AnyPublisher<CompendiumItem, Error> init(data: AnyPublisher<Data, Error>) { items = data.flatMap { data -> AnyPublisher<CompendiumItem, Error> in do { let spells = try JSONDecoder().decode([O5e.Spell].self, from: data) return Publishers.Sequence(sequence: spells.compactMap { m in Spell(open5eSpell: m, realm: .core) }).eraseToAnyPublisher() } catch { return Fail(error: error).eraseToAnyPublisher() } }.eraseToAnyPublisher() } } } private extension Spell { init?(open5eSpell s: O5e.Spell, realm: CompendiumItemKey.Realm) { self.realm = realm self.name = s.name self.level = s.levelInt == 0 ? nil : s.levelInt self.castingTime = s.castingTime self.range = s.range self.components = s.components.components(separatedBy: ",").compactMap { switch $0.trimmingCharacters(in: CharacterSet.whitespaces) { case "V": return .verbal case "S": return .somatic case "M": return .material default: return nil } } self.ritual = s.ritual == "yes" self.duration = s.duration self.school = s.school self.concentration = s.concentration == "yes" self.description = s.desc self.higherLevelDescription = s.higherLevel self.classes = s.spellClass.components(separatedBy: ",").map { $0.trimmingCharacters(in: CharacterSet.whitespaces) } self.material = s.material } }
31.106667
124
0.610802
913dcf60500ec44164fdb309c145a915542c36a1
2,538
import Foundation class TreeNode<T> { var data: T var leftNode: TreeNode? var rightNode: TreeNode? init(data: T, leftNode: TreeNode? = nil, rightNode: TreeNode? = nil) { self.data = data self.leftNode = leftNode self.rightNode = rightNode } } class BinarySearchTree<T: Comparable & CustomStringConvertible> { private var rootNode: TreeNode<T>? func insert(element: T) { let node = TreeNode(data: element) if let rootNode = self.rootNode { self.insert(rootNode, node) } else { self.rootNode = node } } // RECURSIVE FUNCTION private func insert(_ rootNode: TreeNode<T>, _ node: TreeNode<T>) { if rootNode.data > node.data { if let leftNode = rootNode.leftNode { self.insert(leftNode, node) } else { rootNode.leftNode = node } } else { if let rightNode = rootNode.rightNode { self.insert(rightNode, node) } else { rootNode.rightNode = node } } } func traverse() { print("\nPRE-ORDER TRAVERSAL") self.preorder(self.rootNode) print("\n\nIN-ORDER TRAVERSAL") self.inorder(self.rootNode) print("\n\nPOST-ORDER TRAVERSAL") self.postorder(self.rootNode) print("\n") } // LNR : LEFT NODE RIGHT private func inorder(_ node: TreeNode<T>?) { guard let _ = node else { return } self.inorder(node?.leftNode) print("\(node!.data)", terminator: " ") self.inorder(node?.rightNode) } // NLR : NODE LEFT RIGHT private func preorder(_ node: TreeNode<T>?) { guard let _ = node else { return } print("\(node!.data)", terminator: " ") self.preorder(node?.leftNode) self.preorder(node?.rightNode) } // LRN : LEFT RIGHT NODE private func postorder(_ node: TreeNode<T>?) { guard let _ = node else { return } self.postorder(node?.leftNode) self.postorder(node?.rightNode) print("\(node!.data)", terminator: " ") } } let bst = BinarySearchTree<String>() bst.insert(element: "F") bst.insert(element: "G") bst.insert(element: "H") bst.insert(element: "D") bst.insert(element: "E") bst.insert(element: "I") bst.insert(element: "J") bst.insert(element: "A") bst.insert(element: "B") bst.insert(element: "C") bst.traverse()
25.897959
71
0.559496
8f8f9a3f27673c0d0f74284f37c6c7fe9bde391a
2,975
// Kevin Li - 8:26 PM - 7/29/20 import Foundation /// The properties of a `ColorNode` instance being updated. public struct NodeStyleConfiguration { /// The `ColorNode` associated with the given state changes. public let node: ColorNode /// Whether or not the node is currently being first shown. public var isFirstShown: Bool /// Whether or not the node is currently being pressed down by the user. public let isPressed: Bool /// Whether or not the node matches the selected `PaletteColor`. public let isSelected: Bool /// Whether or not the node is currently in the process of moving towards /// its focused location. public let isFocusing: Bool /// Whether or not the node is currently focused. /// /// Focused means that this node is the node the user most recently tapped on /// and it has arrived at its focus location. public let isFocused: Bool } extension NodeStyleConfiguration { static func firstShown(_ node: ColorNode, isSelected: Bool) -> NodeStyleConfiguration { NodeStyleConfiguration(node: node, isFirstShown: true, isPressed: false, isSelected: isSelected, isFocusing: false, isFocused: false) } static func touchedDown(_ node: ColorNode, isSelected: Bool, isFocused: Bool) -> NodeStyleConfiguration { NodeStyleConfiguration(node: node, isFirstShown: false, isPressed: true, isSelected: isSelected, isFocusing: false, isFocused: isFocused) } static func touchedUp(_ node: ColorNode, isSelected: Bool, isFocusing: Bool, isFocused: Bool) -> NodeStyleConfiguration { NodeStyleConfiguration(node: node, isFirstShown: false, isPressed: false, isSelected: isSelected, isFocusing: isFocusing, isFocused: isFocused) } static func unselected(_ node: ColorNode) -> NodeStyleConfiguration { NodeStyleConfiguration(node: node, isFirstShown: false, isPressed: false, isSelected: false, isFocusing: false, isFocused: false) } static func selectedAndFocused(_ node: ColorNode) -> NodeStyleConfiguration { NodeStyleConfiguration(node: node, isFirstShown: false, isPressed: false, isSelected: true, isFocusing: false, isFocused: true) } }
37.1875
125
0.537479
768ca77184955bf333e4bb18360752669cb50856
7,878
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 SKSupport import Basic import Foundation /// A single compilation database command. /// /// See https://clang.llvm.org/docs/JSONCompilationDatabase.html public struct CompilationDatabaseCompileCommand: Equatable { /// The working directory for the compilation. public var directory: String /// The path of the main file for the compilation, which may be relative to `directory`. public var filename: String /// The compile command as a list of strings, with the program name first. public var commandLine: [String] /// The name of the build output, or nil. public var output: String? = nil } extension CompilationDatabase.Command { /// The `URL` for this file. If `filename` is relative and `directory` is /// absolute, returns the concatenation. However, if both paths are relative, /// it falls back to `filename`, which is more likely to be the identifier /// that a caller will be looking for. public var url: URL { if filename.hasPrefix("/") || !directory.hasPrefix("/") { return URL(fileURLWithPath: filename) } else { return URL(fileURLWithPath: directory).appendingPathComponent(filename, isDirectory: false) } } } /// A clang-compatible compilation database. /// /// See https://clang.llvm.org/docs/JSONCompilationDatabase.html public protocol CompilationDatabase { typealias Command = CompilationDatabaseCompileCommand subscript(_ path: URL) -> [Command] { get } } /// Loads the compilation database located in `directory`, if any. public func tryLoadCompilationDatabase( directory: AbsolutePath, fileSystem: FileSystem = localFileSystem ) -> CompilationDatabase? { return orLog("could not open compilation database for \(directory.asString)", level: .error) { try JSONCompilationDatabase(directory: directory, fileSystem: fileSystem) } // TODO: Support fixed compilation database (compile_flags.txt). } /// The JSON clang-compatible compilation database. /// /// Example: /// /// ``` /// [ /// { /// "directory": "/src", /// "file": "/src/file.cpp", /// "command": "clang++ file.cpp" /// } /// ] /// ``` /// /// See https://clang.llvm.org/docs/JSONCompilationDatabase.html public struct JSONCompilationDatabase: CompilationDatabase, Equatable { var pathToCommands: [URL: [Int]] = [:] var commands: [Command] = [] public init(_ commands: [Command] = []) { commands.forEach { add($0) } } public subscript(_ url: URL) -> [Command] { if let indices = pathToCommands[url] { return indices.map { commands[$0] } } if let indices = pathToCommands[url.resolvingSymlinksInPath()] { return indices.map { commands[$0] } } return [] } public mutating func add(_ command: Command) { let url = command.url pathToCommands[url, default: []].append(commands.count) let canonical = url.resolvingSymlinksInPath() if canonical != url { pathToCommands[canonical, default: []].append(commands.count) } commands.append(command) } } extension JSONCompilationDatabase: Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() while !container.isAtEnd { self.add(try container.decode(Command.self)) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try commands.forEach { try container.encode($0) } } } extension JSONCompilationDatabase { public init(directory: AbsolutePath, fileSystem: FileSystem = localFileSystem) throws { let path = directory.appending(component: "compile_commands.json") let bytes = try fileSystem.readFileContents(path) try bytes.withUnsafeData { data in self = try JSONDecoder().decode(JSONCompilationDatabase.self, from: data) } } } enum CompilationDatabaseDecodingError: Error { case missingCommandOrArguments } extension CompilationDatabase.Command: Codable { private enum CodingKeys: String, CodingKey { case directory case file case command case arguments case output } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.directory = try container.decode(String.self, forKey: .directory) self.filename = try container.decode(String.self, forKey: .file) self.output = try container.decodeIfPresent(String.self, forKey: .output) if let arguments = try container.decodeIfPresent([String].self, forKey: .arguments) { self.commandLine = arguments } else if let command = try container.decodeIfPresent(String.self, forKey: .command) { self.commandLine = splitShellEscapedCommand(command) } else { throw CompilationDatabaseDecodingError.missingCommandOrArguments } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(directory, forKey: .directory) try container.encode(filename, forKey: .file) try container.encode(commandLine, forKey: .arguments) try container.encodeIfPresent(output, forKey: .output) } } /// Split and unescape a shell-escaped command line invocation. /// /// Examples: /// /// ``` /// abc def -> ["abc", "def"] /// abc\ def -> ["abc def"] /// abc"\""def -> ["abc\"def"] /// abc'\"'def -> ["abc\\"def"] /// ``` /// /// See clang's `unescapeCommandLine()`. public func splitShellEscapedCommand(_ cmd: String) -> [String] { struct Parser { var rest: Substring var result: [String] = [] init(_ string: Substring) { self.rest = string } var ch: Character { return rest.first! } var done: Bool { return rest.isEmpty } @discardableResult mutating func next() -> Character? { return rest.removeFirst() } mutating func next(expect c: Character) { assert(c == ch) next() } mutating func parse() -> [String] { while !done { switch ch { case " ": next() default: parseString() } } return result } mutating func parseString() { var str = "" STRING: while !done { switch ch { case " ": break STRING case "\"": parseDoubleQuotedString(into: &str) case "\'": parseSingleQuotedString(into: &str) default: parsePlainString(into: &str) } } result.append(str) } mutating func parseDoubleQuotedString(into str: inout String) { next(expect: "\"") while !done { switch ch { case "\"": next() return case "\\": next() if !done { fallthrough } default: str.append(ch) next() } } } mutating func parseSingleQuotedString(into str: inout String) { next(expect: "\'") while !done { switch ch { case "\'": next() return default: str.append(ch) next() } } } mutating func parsePlainString(into str: inout String) { while !done { switch ch { case "\"", "\'", " ": return case "\\": next() if !done { fallthrough } default: str.append(ch) next() } } } } var parser = Parser(cmd[...]) return parser.parse() }
27.837456
97
0.632013
3a69ba3621b3c5a2582f21a574b70219fe9f1d62
3,151
// // NetworkResource.swift // kayako-messenger-SDK // // Created by Robin Malhotra on 15/02/17. // Copyright © 2017 Robin Malhotra. All rights reserved. // import Foundation import Unbox public enum MultiResource<T>: Pathable { //: eventually support other forms of pagination like cursors case paginated(parents: [(parentName: String, suffix: String?)]?, offset: Int?, limit: Int?) func path() -> (path: String, params: [String: String]) { switch self { case .paginated(let parents, let offset, _): let params: [String: String] = { var dict: [String: String] = [:] offset.flatMap{ dict["offset"] = "\($0)"} // limit.flatMap{ dict["limit"] = "\($0)" } dict["limit"] = "100" return dict }() let parents = parents?.flatMap{ $0 }.reduce("", { (result, parent) -> String in return result + [parent.parentName, parent.suffix].flatMap{ $0 }.joined(separator: "/") + "/" }) ?? "" switch T.self { case is Array<Conversation>.Type: return (parents + "conversations", params) case is Array<UserMinimal>.Type: return (parents + "users", params) case is Array<Message>.Type: return (parents + "messages", params) default: #if DEBUG fatalError("type not implemented: \(T.self)") #else return ("", [:]) #endif } } } } extension MultiResource: Equatable { public static func ==(lhs: MultiResource, rhs: MultiResource) -> Bool { #if DEBUG fatalError("Comparing 2 paginated network resources doesn't really make sense") #else return false #endif } } public enum NetworkResource<T>: Pathable { case url(URL) case id(parents: [(parentName: String, suffix: String?)]?, id: Int) case standalone func path() -> (path: String, params: [String: String]) { switch self { case .url(url: _): return ("",[:]) case .id(let parents, let id): let params: [String: String] = [:] let parents = parents?.flatMap{ $0 }.reduce("", { (result, parent) -> String in return result + [parent.parentName, parent.suffix].flatMap{ $0 }.joined(separator: "/") + "/" }) ?? "" switch T.self { case is Conversation.Type: return (parents + "conversations/\(id)", params) case is UserMinimal.Type: return (parents + "users/\(id)", params) case is Message.Type: return (parents + "messages/\(id)", params) default: #if DEBUG fatalError("type not implemented: \(T.self)") #else return ("", [:]) #endif } case .standalone: switch T.self { case is StarterData.Type: return ("conversations/starter", [:]) default: #if DEBUG fatalError("type not implemented: \(T.self)") #else return ("", [:]) #endif } } } } extension NetworkResource: Equatable { public static func ==(lhs: NetworkResource<T>, rhs: NetworkResource<T>) -> Bool { switch (lhs, rhs) { case (.url(let lhs), .url(let rhs)): return lhs == rhs case (.id(_), .id(_)): #if DEBUG fatalError("Comparing 2 network resources doesn't really make sense") #else return false #endif case (.standalone, .standalone): return true default: break } return false } }
25.827869
97
0.622025
cc0a226842a3bfc3c424374f6bbc1fbb30231e75
14,512
import Foundation import UIKit import AsyncDisplayKit import Display import Postbox import TelegramCore import SyncCore import TelegramPresentationData import LocalizedPeerData enum ChatMessageForwardInfoType: Equatable { case bubble(incoming: Bool) case standalone } private final class InfoButtonNode: HighlightableButtonNode { private let pressed: () -> Void let iconNode: ASImageNode private var theme: ChatPresentationThemeData? private var type: ChatMessageForwardInfoType? init(pressed: @escaping () -> Void) { self.pressed = pressed self.iconNode = ASImageNode() self.iconNode.displaysAsynchronously = false super.init() self.addSubnode(self.iconNode) self.addTarget(self, action: #selector(self.pressedEvent), forControlEvents: .touchUpInside) } @objc private func pressedEvent() { self.pressed() } func update(size: CGSize, theme: ChatPresentationThemeData, type: ChatMessageForwardInfoType) { if self.theme !== theme || self.type != type { self.theme = theme self.type = type let color: UIColor switch type { case let .bubble(incoming): color = incoming ? theme.theme.chat.message.incoming.accentControlColor : theme.theme.chat.message.outgoing.accentControlColor case .standalone: let serviceColor = serviceMessageColorComponents(theme: theme.theme, wallpaper: theme.wallpaper) color = serviceColor.primaryText } self.iconNode.image = PresentationResourcesChat.chatPsaInfo(theme.theme, color: color.argb) } if let image = self.iconNode.image { self.iconNode.frame = CGRect(origin: CGPoint(x: floor((size.width - image.size.width) / 2.0), y: floor((size.height - image.size.height) / 2.0)), size: image.size) } } } class ChatMessageForwardInfoNode: ASDisplayNode { private var textNode: TextNode? private var credibilityIconNode: ASImageNode? private var infoNode: InfoButtonNode? var openPsa: ((String, ASDisplayNode) -> Void)? override init() { super.init() } func hasAction(at point: CGPoint) -> Bool { if let infoNode = self.infoNode, infoNode.frame.contains(point) { return true } else { return false } } func updatePsaButtonDisplay(isVisible: Bool, animated: Bool) { if let infoNode = self.infoNode { if isVisible != !infoNode.iconNode.alpha.isZero { let transition: ContainedViewLayoutTransition if animated { transition = .animated(duration: 0.25, curve: .easeInOut) } else { transition = .immediate } transition.updateAlpha(node: infoNode.iconNode, alpha: isVisible ? 1.0 : 0.0) transition.updateSublayerTransformScale(node: infoNode, scale: isVisible ? 1.0 : 0.1) } } } class func asyncLayout(_ maybeNode: ChatMessageForwardInfoNode?) -> (_ presentationData: ChatPresentationData, _ strings: PresentationStrings, _ type: ChatMessageForwardInfoType, _ peer: Peer?, _ authorName: String?, _ psaType: String?, _ constrainedSize: CGSize) -> (CGSize, (CGFloat) -> ChatMessageForwardInfoNode) { let textNodeLayout = TextNode.asyncLayout(maybeNode?.textNode) return { presentationData, strings, type, peer, authorName, psaType, constrainedSize in let fontSize = floor(presentationData.fontSize.baseDisplaySize * 13.0 / 17.0) let prefixFont = Font.regular(fontSize) let peerFont = Font.medium(fontSize) let peerString: String if let peer = peer { if let authorName = authorName { peerString = "\(peer.displayTitle(strings: strings, displayOrder: presentationData.nameDisplayOrder)) (\(authorName))" } else { peerString = peer.displayTitle(strings: strings, displayOrder: presentationData.nameDisplayOrder) } } else if let authorName = authorName { peerString = authorName } else { peerString = "" } var hasPsaInfo = false if let _ = psaType { hasPsaInfo = true } let titleColor: UIColor let completeSourceString: (String, [(Int, NSRange)]) switch type { case let .bubble(incoming): if let psaType = psaType { titleColor = incoming ? presentationData.theme.theme.chat.message.incoming.polls.barPositive : presentationData.theme.theme.chat.message.outgoing.polls.barPositive var customFormat: String? let key = "Message.ForwardedPsa.\(psaType)" if let string = presentationData.strings.primaryComponent.dict[key] { customFormat = string } else if let string = presentationData.strings.secondaryComponent?.dict[key] { customFormat = string } if let customFormat = customFormat { if let range = customFormat.range(of: "%@") { let leftPart = String(customFormat[customFormat.startIndex ..< range.lowerBound]) let rightPart = String(customFormat[range.upperBound...]) let formattedText = leftPart + peerString + rightPart completeSourceString = (formattedText, [(0, NSRange(location: leftPart.count, length: peerString.count))]) } else { completeSourceString = (customFormat, []) } } else { completeSourceString = strings.Message_GenericForwardedPsa(peerString) } } else { titleColor = incoming ? presentationData.theme.theme.chat.message.incoming.accentTextColor : presentationData.theme.theme.chat.message.outgoing.accentTextColor completeSourceString = strings.Message_ForwardedMessage(peerString) } case .standalone: let serviceColor = serviceMessageColorComponents(theme: presentationData.theme.theme, wallpaper: presentationData.theme.wallpaper) titleColor = serviceColor.primaryText if let psaType = psaType { var customFormat: String? let key = "Message.ForwardedPsa.\(psaType)" if let string = presentationData.strings.primaryComponent.dict[key] { customFormat = string } else if let string = presentationData.strings.secondaryComponent?.dict[key] { customFormat = string } if let customFormat = customFormat { if let range = customFormat.range(of: "%@") { let leftPart = String(customFormat[customFormat.startIndex ..< range.lowerBound]) let rightPart = String(customFormat[range.upperBound...]) let formattedText = leftPart + peerString + rightPart completeSourceString = (formattedText, [(0, NSRange(location: leftPart.count, length: peerString.count))]) } else { completeSourceString = (customFormat, []) } } else { completeSourceString = strings.Message_GenericForwardedPsa(peerString) } } else { completeSourceString = strings.Message_ForwardedMessageShort(peerString) } } var currentCredibilityIconImage: UIImage? var highlight = true if let peer = peer { if let channel = peer as? TelegramChannel, channel.username == nil { if case let .broadcast(info) = channel.info, info.flags.contains(.hasDiscussionGroup) { } else if case .member = channel.participationStatus { } else { highlight = false } } if peer.isFake { switch type { case let .bubble(incoming): currentCredibilityIconImage = PresentationResourcesChatList.fakeIcon(presentationData.theme.theme, strings: presentationData.strings, type: incoming ? .regular : .outgoing) case .standalone: currentCredibilityIconImage = PresentationResourcesChatList.fakeIcon(presentationData.theme.theme, strings: presentationData.strings, type: .service) } } else if peer.isScam { switch type { case let .bubble(incoming): currentCredibilityIconImage = PresentationResourcesChatList.scamIcon(presentationData.theme.theme, strings: presentationData.strings, type: incoming ? .regular : .outgoing) case .standalone: currentCredibilityIconImage = PresentationResourcesChatList.scamIcon(presentationData.theme.theme, strings: presentationData.strings, type: .service) } } else { currentCredibilityIconImage = nil } } else { highlight = false } let completeString: NSString = completeSourceString.0 as NSString let string = NSMutableAttributedString(string: completeString as String, attributes: [NSAttributedString.Key.foregroundColor: titleColor, NSAttributedString.Key.font: prefixFont]) if highlight, let range = completeSourceString.1.first?.1 { string.addAttributes([NSAttributedString.Key.font: peerFont], range: range) } var credibilityIconWidth: CGFloat = 0.0 if let icon = currentCredibilityIconImage { credibilityIconWidth += icon.size.width + 4.0 } var infoWidth: CGFloat = 0.0 if hasPsaInfo { infoWidth += 32.0 } let (textLayout, textApply) = textNodeLayout(TextNodeLayoutArguments(attributedString: string, backgroundColor: nil, maximumNumberOfLines: 2, truncationType: .end, constrainedSize: CGSize(width: constrainedSize.width - credibilityIconWidth - infoWidth, height: constrainedSize.height), alignment: .natural, cutout: nil, insets: UIEdgeInsets())) return (CGSize(width: textLayout.size.width + credibilityIconWidth + infoWidth, height: textLayout.size.height), { width in let node: ChatMessageForwardInfoNode if let maybeNode = maybeNode { node = maybeNode } else { node = ChatMessageForwardInfoNode() } let textNode = textApply() if node.textNode == nil { textNode.isUserInteractionEnabled = false node.textNode = textNode node.addSubnode(textNode) } textNode.frame = CGRect(origin: CGPoint(), size: textLayout.size) if let credibilityIconImage = currentCredibilityIconImage { let credibilityIconNode: ASImageNode if let node = node.credibilityIconNode { credibilityIconNode = node } else { credibilityIconNode = ASImageNode() node.credibilityIconNode = credibilityIconNode node.addSubnode(credibilityIconNode) } credibilityIconNode.frame = CGRect(origin: CGPoint(x: textLayout.size.width + 4.0, y: 16.0), size: credibilityIconImage.size) credibilityIconNode.image = credibilityIconImage } else { node.credibilityIconNode?.removeFromSupernode() node.credibilityIconNode = nil } if hasPsaInfo { let infoNode: InfoButtonNode if let current = node.infoNode { infoNode = current } else { infoNode = InfoButtonNode(pressed: { [weak node] in guard let node = node else { return } if let psaType = psaType, let infoNode = node.infoNode { node.openPsa?(psaType, infoNode) } }) node.infoNode = infoNode node.addSubnode(infoNode) } let infoButtonSize = CGSize(width: 32.0, height: 32.0) let infoButtonFrame = CGRect(origin: CGPoint(x: width - infoButtonSize.width - 2.0, y: 1.0), size: infoButtonSize) infoNode.frame = infoButtonFrame infoNode.update(size: infoButtonFrame.size, theme: presentationData.theme, type: type) } else if let infoNode = node.infoNode { node.infoNode = nil infoNode.removeFromSupernode() } return node }) } } }
48.861953
356
0.539071
5bc722ff42542eb575a16953c7f17581a4836afb
1,645
// // MEGeneralFactory.swift // GBook // // Created by 马伟 on 2017/6/6. // Copyright © 2017年 马伟. All rights reserved. // import UIKit let ME_FunctionalButton_Top_Margin : CGFloat = 30.0 let ME_FunctionalButton_Height : CGFloat = 20.0 let ME_FunctionalButton_Width : CGFloat = 40.0 class MEGeneralFactory: NSObject { //MARK: 设置常见的功能性按钮(关闭和确认) static func setupNormalFunctionalButton(_ forTarget : UIViewController , leftTitle : String = "关闭", rightTitle : String = "确认") { let leftBtn = UIButton(frame: CGRect(x: 10, y: ME_FunctionalButton_Top_Margin, width: ME_FunctionalButton_Width, height: ME_FunctionalButton_Height)) leftBtn.setTitle(leftTitle, for: .normal) leftBtn.setTitleColor(Main_Color, for: .normal) leftBtn.contentHorizontalAlignment = .left leftBtn.titleLabel?.font = UIFont(name: My_Font_Name, size: 14) leftBtn.addTarget(forTarget, action: Selector(("leftButtonClick")), for: .touchUpInside) leftBtn.tag = 111 forTarget.view.addSubview(leftBtn) let rightBtn = UIButton(frame: CGRect(x: SCREEN_WIDTH - 50, y: ME_FunctionalButton_Top_Margin, width: ME_FunctionalButton_Width, height: ME_FunctionalButton_Height)) rightBtn.setTitle(rightTitle, for: .normal) rightBtn.setTitleColor(Main_Color, for: .normal) rightBtn.contentHorizontalAlignment = .left rightBtn.titleLabel?.font = UIFont(name: My_Font_Name, size: 14) rightBtn.addTarget(forTarget, action: Selector(("rightButtonClick")), for: .touchUpInside) rightBtn.tag = 112 forTarget.view.addSubview(rightBtn) } }
41.125
173
0.710638
72d3d27b4449d6150bcf2d9acc5fd04580615256
1,779
// // Paint Fill: Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color. // // 11 12 13 // 21 22 23 // 31 32 33 //TimeComp: SpaceCompl: O(k) - k is number of points with the original color import SwiftUI public class Screen { public var points = [[Color]]() public init(points: [[Color]]) { self.points = points } public func paint(row: Int, column: Int, newColor: Color) { guard row >= 0, column >= 0, row < points.count && column < points[row].count else { return } let oColor = points[row][column] if oColor == newColor { return } paint(row: row, column: column, oColor: oColor, nColor: newColor) } private func paint(row: Int, column: Int, oColor: Color, nColor: Color) { guard row >= 0, column >= 0, row < points.count, column < points[row].count, points[row][column] == oColor else { return } points[row][column] = nColor paint(row: row - 1, column: column, oColor: oColor, nColor: nColor) paint(row: row + 1, column: column, oColor: oColor, nColor: nColor) paint(row: row, column: column - 1, oColor: oColor, nColor: nColor) paint(row: row, column: column + 1, oColor: oColor, nColor: nColor) paint(row: row - 1, column: column - 1, oColor: oColor, nColor: nColor) paint(row: row + 1, column: column + 1, oColor: oColor, nColor: nColor) paint(row: row - 1, column: column + 1, oColor: oColor, nColor: nColor) paint(row: row + 1, column: column - 1, oColor: oColor, nColor: nColor) } }
41.372093
282
0.631254
757e44c06fac0ebe65f18bc2d46196f271e97b8d
2,090
// // ToDo.swift // ToDoSample // // Created by Yusaku Ueda on 2018/08/08. // Copyright © 2018年 Yusaku Ueda. All rights reserved. // import Foundation import Firebase class ToDoItem: Codable { var documentID: String var authorId: String var title: String var updated: Date private enum CodingKeys: String, CodingKey { case authorId = "author_id" case title case updated } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) documentID = "" authorId = try values.decode(String.self, forKey: .authorId) title = try values.decode(String.self, forKey: .title) updated = try values.decode(Date.self, forKey: .updated) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(authorId, forKey: .authorId) try container.encode(title, forKey: .title) try container.encode(updated, forKey: .updated) } init(_ id: String, authorId: String, title: String, updated: Date = Date()) { self.documentID = id self.authorId = authorId self.title = title self.updated = updated } convenience init(from document: DocumentSnapshot) { let data = document.data() ?? [:] let authorId = data[CodingKeys.authorId.rawValue] as? String ?? "" let title = data[CodingKeys.title.rawValue] as? String ?? "" let updated = (data[CodingKeys.updated.rawValue] as? Timestamp)?.dateValue() ?? Date(timeIntervalSince1970: 0) self.init(document.documentID, authorId: authorId, title: title, updated: updated) } func asDictionary() -> [String: Any] { let props: [(key: CodingKeys, value: Any)] = [ (key: .authorId, value: authorId), (key: .title, value: title), (key: .updated, value: Timestamp(date: updated)), ] return props.reduce(into: [:]) { $0[$1.key.rawValue] = $1.value } } }
32.153846
118
0.620096
e00121fd3c2d2a529c23347bab0bd91eed68897c
5,100
/** * Copyright IBM Corporation 2016-2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest import Foundation @testable import KituraWebSocket import KituraNet class TestWebSocketService: WebSocketService { let closeReason: WebSocketCloseReasonCode let pingMessage: String? let testServerRequest: Bool var connectionTimeout: Int? var connections: [String: WebSocketConnection] public init(closeReason: WebSocketCloseReasonCode, testServerRequest: Bool, pingMessage: String?, connectionTimeout: Int? = nil) { self.closeReason = closeReason self.testServerRequest = testServerRequest self.pingMessage = pingMessage self.connectionTimeout = connectionTimeout self.connections = [:] } public func connected(connection: WebSocketConnection) { connections[connection.id] = connection if let pingMessage = pingMessage { if pingMessage.count > 0 { connection.ping(withMessage: pingMessage) } else { connection.ping() } } if testServerRequest { performServerRequestTests(request: connection.request) sleep(2) performServerRequestTests(request: connection.request) } } private func performServerRequestTests(request: ServerRequest) { XCTAssertEqual(request.method, "GET", "The method of the request should be GET, it was \(request.method))") XCTAssertEqual(request.httpVersionMajor, 1, "HTTP version major should be 1, it was \(String(describing: request.httpVersionMajor))") XCTAssertEqual(request.httpVersionMinor, 1, "HTTP version major should be 1, it was \(String(describing: request.httpVersionMinor))") XCTAssertEqual(request.urlURL.pathComponents[1], "wstester", "Path of the request should be /wstester, it was /\(request.urlURL.pathComponents[1])") XCTAssertEqual(request.url, "/wstester".data(using: .utf8)!, "Path of the request should be /wstester, it was \(String(data: request.url, encoding: .utf8) ?? "Not UTF-8")") let protocolVersion = request.headers["Sec-WebSocket-Version"] XCTAssertNotNil(protocolVersion, "The Sec-WebSocket-Version header wasn't in the headers") XCTAssertEqual(protocolVersion!.count, 1, "The Sec-WebSocket-Version header should have one value") XCTAssertEqual(protocolVersion![0], "13", "The Sec-WebSocket-Version header value should be 13, it was \(protocolVersion![0])") do { let bodyString = try request.readString() XCTAssertNil(bodyString, "Read of body should have returned nil, it returned \"\(String(describing: bodyString))\"") var body = Data() var count = try request.read(into: &body) XCTAssertEqual(count, 0, "Read of body into a Data should have returned 0, it returned \(count)") count = try request.readAllData(into: &body) XCTAssertEqual(count, 0, "Read of entire body into a Data should have returned 0, it returned \(count)") } catch { XCTFail("Failed to read from the body. Error=\(error)") } } public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) { XCTAssertNotNil(connections[connection.id], "Client ID from connect wasn't client ID from disconnect") XCTAssert((closeReason.code() == reason.code()), "Excpected close reason code of \(closeReason) received \(reason)") connections[connection.id] = nil } public func received(message: Data, from: WebSocketConnection) { print("Received a binary message of length \(message.count)") from.send(message: message) } public func received(message: String, from: WebSocketConnection) { print("Received a String message of length \(message.count)") from.send(message: message) if message == "close" { from.close(reason: .goingAway, description: "Going away...") } else if message == "drop" { from.drop(reason: .policyViolation, description: "Droping...") } else if message == "ping" { from.ping(withMessage: "Hello") } } } extension TestWebSocketService: CustomStringConvertible { /// Generate a printable version of this enum. public var description: String { return "TestWebSocketService(closeReason: \(closeReason))" } }
43.589744
180
0.663922
916e61218d11e09470717e7bef6abf3b8bbbdbe5
2,286
// // SceneDelegate.swift // Tip // // Created by Kinza Rehman on 11/11/20. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.132075
147
0.712161
2978ef34b52950c9d672baca20f928914b8362c7
1,394
// // ClendarWidgetTimeline.swift // ClendarWidgetExtension // // Created by Vinh Nguyen on 10/31/20. // Copyright © 2020 Vinh Nguyen. All rights reserved. // import SwiftUI import WidgetKit import Shift // Reference: https://wwdcbysundell.com/2020/getting-started-with-widgetkit/ struct DateInfoWidgetTimelineProvider: TimelineProvider { typealias Entry = WidgetEntry func getSnapshot(in _: Context, completion: @escaping (WidgetEntry) -> Void) { let entry = WidgetEntry(date: Date()) completion(entry) } func getTimeline(in _: Context, completion: @escaping (Timeline<WidgetEntry>) -> Void) { let currentDate = Date() // swiftlint:disable:next force_unwrapping let interval = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: currentDate)! Task { var entries = [WidgetEntry]() let events = (try? await Shift.shared.fetchEventsRangeUntilEndOfDay(from: currentDate)) ?? [] let clendarEvents = events.compactMap(ClendarEvent.init) let entry = WidgetEntry(date: interval, events: clendarEvents) entries.append(entry) let timeline = Timeline(entries: entries, policy: .after(interval)) completion(timeline) } } func placeholder(in _: Context) -> WidgetEntry { WidgetEntry(date: Date()) } }
30.304348
105
0.663558
037b455ec2b6bf4f99626bb9b8fc74b82a1cbc79
6,572
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import CwlPreconditionTesting @testable import Amplify @testable import AmplifyTestCommon /// Tests of the default AWSUnifiedLoggingPlugin /// /// NOTE: Tests in this class invoke log methods with hardcoded strings directly inline with the method call. This is /// important. The `message` arguments are auto-closures, and we're relying on that fact to determine whether a message /// is being evaluated or not. In other words, don't assign the message to a variable, and then pass it to the logging /// method. class DefaultLoggingPluginTests: XCTestCase { override func setUp() { Amplify.reset() let config = AmplifyConfiguration() do { try Amplify.configure(config) } catch { XCTFail("Error setting up Amplify: \(error)") } } override func tearDown() { Amplify.reset() } /// Given: An Amplify system configured with default values /// When: I invoke Amplify.configure() /// Then: I have access to the framework-provided Logging plugin func testDefaultPluginAssigned() throws { let plugin = try? Amplify.Logging.getPlugin(for: "AWSUnifiedLoggingPlugin") XCTAssertNotNil(plugin) XCTAssertEqual(plugin?.key, "AWSUnifiedLoggingPlugin") } /// - Given: A default Amplify configuration /// - When: /// - I log messages using `Amplify.Logging` /// - Then: /// - It uses the default logging level func testUsesDefaultLoggingLevel() { // Relies on Amplify.Logging.logLevel defaulting to `.error` let errorMessageCorrectlyEvaluated = expectation(description: "error message was correctly evaluated") Amplify.Logging.error("error \(errorMessageCorrectlyEvaluated.fulfill())") let warnMessageIncorrectlyEvaluated = expectation(description: "warn message was incorrectly evaluated") warnMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.warn("warn \(warnMessageIncorrectlyEvaluated.fulfill())") let infoMessageIncorrectlyEvaluated = expectation(description: "info message was incorrectly evaluated") infoMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.info("info \(infoMessageIncorrectlyEvaluated.fulfill())") let debugMessageIncorrectlyEvaluated = expectation(description: "debug message was incorrectly evaluated") debugMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.debug("debug \(debugMessageIncorrectlyEvaluated.fulfill())") let verboseMessageIncorrectlyEvaluated = expectation(description: "verbose message was incorrectly evaluated") verboseMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.verbose("verbose \(verboseMessageIncorrectlyEvaluated.fulfill())") waitForExpectations(timeout: 0.1) } /// - Given: default configuration /// - When: /// - I change the global Amplify.Logging.logLevel /// - Then: /// - My log statements are evaluated appropriately func testRespectsChangedDefaultLogLevel() { Amplify.Logging.logLevel = .error let warnMessageIncorrectlyEvaluated = expectation(description: "warn message was incorrectly evaluated") warnMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.warn("warn \(warnMessageIncorrectlyEvaluated.fulfill())") let infoMessageIncorrectlyEvaluated = expectation(description: "info message was incorrectly evaluated") infoMessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.info("info \(infoMessageIncorrectlyEvaluated.fulfill())") Amplify.Logging.logLevel = .warn let warnMessageCorrectlyEvaluated = expectation(description: "warn message was correctly evaluated") Amplify.Logging.warn("warn \(warnMessageCorrectlyEvaluated.fulfill())") let infoMessageIncorrectlyEvaluatedAgain = expectation(description: "info message was incorrectly evaluated second time") infoMessageIncorrectlyEvaluatedAgain.isInverted = true Amplify.Logging.info("info \(infoMessageIncorrectlyEvaluatedAgain.fulfill())") waitForExpectations(timeout: 0.1) } /// Although we can't assert it, the messages in the console log are expected to have different "category" tags /// /// - Given: default configuration /// - When: /// - I obtain a category-specific log /// - Then: /// - I can send messages to it func testCategorySpecificLog() { let logger1MessageCorrectlyEvaluated = expectation(description: "logger1 message was correctly evaluated") let logger2MessageCorrectlyEvaluated = expectation(description: "logger2 message was correctly evaluated") let exception: BadInstructionException? = catchBadInstruction { let logger1 = Amplify.Logging.logger(forCategory: "Logger1") let logger2 = Amplify.Logging.logger(forCategory: "Logger2") logger1.error("logger1 \(logger1MessageCorrectlyEvaluated.fulfill())") logger2.error("logger2 \(logger2MessageCorrectlyEvaluated.fulfill())") } XCTAssertNil(exception) waitForExpectations(timeout: 0.1) } /// - Given: default configuration /// - When: /// - I obtain category specific logs with different log levels /// - Then: /// - Each category-specific log evalutes at the appropriate level func testDifferentLoggersWithDifferentLogLevels() { let globalMessageCorrectlyEvaluated = expectation(description: "global message was correctly evaluated") let logger1MessageCorrectlyEvaluated = expectation(description: "logger1 message was correctly evaluated") let logger2MessageIncorrectlyEvaluated = expectation(description: "logger2 message was incorrectly evaluated") logger2MessageIncorrectlyEvaluated.isInverted = true Amplify.Logging.logLevel = .info let logger1 = Amplify.Logging.logger(forCategory: "Logger1", logLevel: .debug) let logger2 = Amplify.Logging.logger(forCategory: "Logger2", logLevel: .warn) Amplify.Logging.info("global \(globalMessageCorrectlyEvaluated.fulfill())") logger1.info("logger1 \(logger1MessageCorrectlyEvaluated.fulfill())") logger2.info("logger2 \(logger2MessageIncorrectlyEvaluated.fulfill())") waitForExpectations(timeout: 0.1) } }
43.813333
119
0.71196
1d80bf9c8ecef5b1de7a4696aabb6a5437405d05
2,906
// // ViewController.swift // OpenSansSwiftExample // // Created by Hemanta Sapkota on 21/02/2015. // Copyright (c) 2015 Open Learning Pty Ltd. All rights reserved. // import UIKit import OpenSansSwift class ViewController: UIViewController { let size = CGSize(width: 400, height: 50) func makeFontLabel(x:CGFloat, y:CGFloat, font:UIFont) -> UILabel { let lbl1 = UILabel(frame: CGRectMake(x, y, size.width, size.height)) lbl1.font = font lbl1.text = font.fontName return lbl1 } override func viewDidLoad() { super.viewDidLoad() //Register Open Sans fonts OpenSans.registerFonts() let x = UIScreen.mainScreen().bounds.width / 2 var x1 = x - size.width / 3 var y1 = CGFloat(100) // let fontNames = [ // "OpenSans-Regular", // "OpenSans-Bold", // "OpenSans-BoldItalic", // "OpenSans-ExtraBold", // "OpenSans-ExtraBoldItalic", // "OpenSans-Italic", // "OpenSans-Light", // "OpenSans-LightItalic", // "OpenSans-Semibold", // "OpenSans-SemiboldItalic" // ] let f1 = UIFont.openSansFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f1)) y1 += 50 let f2 = UIFont.openSansBoldFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f2)) y1 += 50 let f3 = UIFont.openSansBoldItalicFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f3)) y1 += 50 let f4 = UIFont.openSansExtraBoldFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f4)) y1 += 50 let f5 = UIFont.openSansExtraBoldItalicFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f5)) y1 += 50 let f6 = UIFont.openSansItalicFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f6)) y1 += 50 let f7 = UIFont.openSansLightFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f7)) y1 += 50 let f8 = UIFont.openSansLightItalicFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f8)) y1 += 50 let f9 = UIFont.openSansSemiboldFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f9)) y1 += 50 let f10 = UIFont.openSansSemiboldItalicFontOfSize(30) self.view.addSubview(makeFontLabel(x1, y: y1, font: f10)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
28.213592
76
0.562973
87243af7c5a1b74a69a09ed8b5b0c9028e7010e4
17,909
// // DialogsSelectionVC.swift // sample-chat-swift // // Created by Injoit on 10/11/19. // Copyright © 2019 Quickblox. All rights reserved. // import UIKit struct DialogsSelectionConstant { static let forwarded = "Message forwarded" } class DialogsSelectionVC: UITableViewController { //MARK: - Properties private let chatManager = ChatManager.instance private var dialogs: [QBChatDialog] = [] private var selectedPaths = Set<IndexPath>() private var titleView = TitleView() var action: ChatActions? var message: QBChatMessage? internal var senderID: UInt = 0 //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() let currentUser = Profile() guard currentUser.isFull == true else { return } senderID = currentUser.ID navigationItem.titleView = titleView setupNavigationTitle() let backButtonItem = UIBarButtonItem(image: UIImage(named: "chevron"), style: .plain, target: self, action: #selector(didTapBack(_:))) navigationItem.leftBarButtonItem = backButtonItem backButtonItem.tintColor = .white if let action = action { if action == .Delete { let deleteButtonItem = UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(didTapDelete(_:))) navigationItem.rightBarButtonItem = deleteButtonItem deleteButtonItem.tintColor = .white } else if action == .Forward { let sendButtonItem = UIBarButtonItem(title: "Send", style: .plain, target: self, action: #selector(didTapSend(_:))) navigationItem.rightBarButtonItem = sendButtonItem sendButtonItem.tintColor = .white } } navigationItem.rightBarButtonItem?.isEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadContent() chatManager.delegate = self } //MARK: - Actions private func checkNavRightBarButtonEnabled() { navigationItem.rightBarButtonItem?.isEnabled = selectedPaths.isEmpty == true ? false : true } @objc func didTapSend(_ sender: UIBarButtonItem) { guard let originMessage = message else { return } let sendGroup = DispatchGroup() SVProgressHUD.show() for indexPath in self.selectedPaths { let dialog = self.dialogs[indexPath.row] guard let dialogID = dialog.id else { continue } sendGroup.enter() let forwardedMessage = QBChatMessage.markable() forwardedMessage.senderID = senderID forwardedMessage.deliveredIDs = [(NSNumber(value: senderID))] forwardedMessage.readIDs = [(NSNumber(value: senderID))] forwardedMessage.dateSent = Date() forwardedMessage.customParameters["save_to_history"] = true let originSenderUser = chatManager.storage.user(withID: originMessage.senderID) if let fullName = originSenderUser?.fullName { forwardedMessage.customParameters[ChatDataSourceConstant.forwardedMessage] = fullName } else { let currentUser = Profile() forwardedMessage.customParameters[ChatDataSourceConstant.forwardedMessage] = currentUser.fullName } forwardedMessage.dialogID = dialogID if let attachment = originMessage.attachments?.first { forwardedMessage.text = "[Attachment]" forwardedMessage.attachments = [attachment] } else { forwardedMessage.text = originMessage.text } chatManager.send(forwardedMessage, to: dialog) { (error) in sendGroup.leave() if let error = error { debugPrint("[DialogsSelectionVC] sendMessage error: \(error.localizedDescription)") return } } } sendGroup.notify(queue: DispatchQueue.main) { SVProgressHUD.dismiss() self.dismiss(animated: false, completion: nil) } } @objc func didTapDelete(_ sender: UIBarButtonItem) { if Reachability.instance.networkConnectionStatus() == .notConnection { SVProgressHUD.dismiss() showAlertView(LoginConstant.checkInternet, message: LoginConstant.checkInternetMessage) return } let alertController = UIAlertController(title: "SA_STR_WARNING".localized, message: "SA_STR_DO_YOU_REALLY_WANT_TO_DELETE_SELECTED_DIALOGS".localized, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "SA_STR_CANCEL".localized, style: .cancel, handler: nil) let leaveAction = UIAlertAction(title: "SA_STR_DELETE".localized, style: .default) { (action:UIAlertAction) in SVProgressHUD.show(withStatus: "SA_STR_DELETING".localized) let deleteGroup = DispatchGroup() for indexPath in self.selectedPaths { let dialog = self.dialogs[indexPath.row] guard let dialogID = dialog.id else { SVProgressHUD.dismiss() return } if dialog.type == .private { deleteGroup.enter() self.chatManager.leaveDialog(withID: dialogID) { error in if error == nil { self.selectedPaths.remove(indexPath) } deleteGroup.leave() } } else if dialog.type == .publicGroup { continue } else { // group deleteGroup.enter() let currentUser = Profile() dialog.pullOccupantsIDs = [(NSNumber(value: currentUser.ID)).stringValue] let message = "\(currentUser.fullName) " + "SA_STR_USER_HAS_LEFT".localized // Notifies occupants that user left the dialog. self.chatManager.sendLeaveMessage(message, to: dialog, completion: { (error) in if let error = error { debugPrint("[DialogsViewController] sendLeaveMessage error: \(error.localizedDescription)") SVProgressHUD.dismiss() return } self.chatManager.leaveDialog(withID: dialogID) { error in if error == nil { self.selectedPaths.remove(indexPath) } deleteGroup.leave() } }) } } deleteGroup.notify(queue: DispatchQueue.main) { self.dismiss(animated: false, completion: nil) } } alertController.addAction(cancelAction) alertController.addAction(leaveAction) present(alertController, animated: true, completion: nil) } @objc func didTapBack(_ sender: UIBarButtonItem) { dismiss(animated: false, completion: nil) } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dialogs.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DialogCell", for: indexPath) as? DialogCell else { return UITableViewCell() } cell.isExclusiveTouch = true cell.contentView.isExclusiveTouch = true cell.tag = indexPath.row let chatDialog = dialogs[indexPath.row] let cellModel = DialogTableViewCellModel(dialog: chatDialog) if action == ChatActions.Delete, chatDialog.type == .publicGroup { cell.contentView.backgroundColor = .clear cell.checkBoxView.backgroundColor = .clear cell.checkBoxView.isHidden = true cell.checkBoxImageView.isHidden = true cell.lastMessageDateLabel.isHidden = true } else { tableView.allowsMultipleSelection = true cell.checkBoxView.isHidden = false cell.unreadMessageCounterLabel.isHidden = true cell.unreadMessageCounterHolder.isHidden = true cell.lastMessageDateLabel.isHidden = true if self.selectedPaths.contains(indexPath) { cell.contentView.backgroundColor = UIColor(red:0.85, green:0.89, blue:0.97, alpha:1) cell.checkBoxImageView.isHidden = false cell.checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 0.0, color: UIColor(red:0.22, green:0.47, blue:0.99, alpha:1), borderColor: UIColor(red:0.22, green:0.47, blue:0.99, alpha:1)) } else { cell.contentView.backgroundColor = .clear cell.checkBoxView.backgroundColor = .clear cell.checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 1.0, borderColor: UIColor(red:0.42, green:0.48, blue:0.57, alpha:1)) cell.checkBoxImageView.isHidden = true } } cell.dialogLastMessage.text = chatDialog.lastMessageText if chatDialog.lastMessageText == nil && chatDialog.lastMessageID != nil { cell.dialogLastMessage.text = "[Attachment]" } cell.dialogName.text = cellModel.textLabelText cell.dialogAvatarLabel.backgroundColor = UInt(chatDialog.createdAt!.timeIntervalSince1970).generateColor() cell.dialogAvatarLabel.text = String(cellModel.textLabelText.stringByTrimingWhitespace().capitalized.first ?? Character("C")) return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let dialog = dialogs[indexPath.row] if let action = action, action == .Delete, dialog.type == .publicGroup { let alertController = UIAlertController(title: "You cannot leave \(dialog.name ?? "Public chat")".localized, message: nil, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "SA_STR_CANCEL".localized, style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) return } if selectedPaths.contains(indexPath) { selectedPaths.remove(indexPath) } else { selectedPaths.insert(indexPath) } checkNavRightBarButtonEnabled() setupNavigationTitle() tableView.reloadData() } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let dialog = dialogs[indexPath.row] if let action = action, action == .Delete, dialog.type == .publicGroup { return } if selectedPaths.contains(indexPath) { selectedPaths.remove(indexPath) } else { selectedPaths.insert(indexPath) } checkNavRightBarButtonEnabled() setupNavigationTitle() tableView.reloadData() } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let dialog = dialogs[indexPath.row] if let action = action, action != .Delete || dialog.type == .publicGroup { return false } return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if Reachability.instance.networkConnectionStatus() == .notConnection { showAlertView(LoginConstant.checkInternet, message: LoginConstant.checkInternetMessage) return } let dialog = dialogs[indexPath.row] if editingStyle != .delete || dialog.type == .publicGroup { return } let alertController = UIAlertController(title: "SA_STR_WARNING".localized, message: "SA_STR_DO_YOU_REALLY_WANT_TO_DELETE_SELECTED_DIALOG".localized, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "SA_STR_CANCEL".localized, style: .cancel, handler: nil) let leaveAction = UIAlertAction(title: "SA_STR_DELETE".localized, style: .default) { (action:UIAlertAction) in SVProgressHUD.show(withStatus: "SA_STR_DELETING".localized) guard let dialogID = dialog.id else { SVProgressHUD.dismiss() return } if dialog.type == .private { self.chatManager.leaveDialog(withID: dialogID) { error in if error == nil { self.dismiss(animated: false, completion: nil) } } } else { let currentUser = Profile() // group dialog.pullOccupantsIDs = [(NSNumber(value: currentUser.ID)).stringValue] let message = "\(currentUser.fullName) " + "SA_STR_USER_HAS_LEFT".localized // Notifies occupants that user left the dialog. self.chatManager.sendLeaveMessage(message, to: dialog, completion: { (error) in if let error = error { debugPrint("[DialogsViewController] sendLeaveMessage error: \(error.localizedDescription)") SVProgressHUD.dismiss() return } self.chatManager.leaveDialog(withID: dialogID) { error in if error == nil { self.dismiss(animated: false, completion: nil) } } }) } } alertController.addAction(cancelAction) alertController.addAction(leaveAction) present(alertController, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "SA_STR_DELETE".localized } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SA_STR_SEGUE_GO_TO_CHAT".localized { if let chatVC = segue.destination as? ChatViewController { chatVC.dialogID = sender as? String } } } // MARK: - Helpers private func reloadContent() { dialogs = chatManager.storage.dialogsSortByUpdatedAt() setupNavigationTitle() tableView.reloadData() } private func setupNavigationTitle() { var title = DialogsConstant.forward if let action = action, action == .Delete { title = DialogsConstant.deleteChats } var chats = "chat" if selectedPaths.count > 1 { chats = "chats" } let numberChats = "\(selectedPaths.count) \(chats) selected" titleView.setupTitleView(title: title, subTitle: numberChats) } } // MARK: - ChatManagerDelegate extension DialogsSelectionVC: ChatManagerDelegate { func chatManager(_ chatManager: ChatManager, didUpdateChatDialog chatDialog: QBChatDialog) { reloadContent() SVProgressHUD.dismiss() } func chatManager(_ chatManager: ChatManager, didFailUpdateStorage message: String) { SVProgressHUD.showError(withStatus: message) } func chatManager(_ chatManager: ChatManager, didUpdateStorage message: String) { reloadContent() SVProgressHUD.dismiss() } func chatManagerWillUpdateStorage(_ chatManager: ChatManager) { } }
41.456019
133
0.55313
50d81cd3641d189fbbd2416a1d58dceaa242931d
679
// // BSMessage.swift // botsocial // // Created by Aamir on 25/03/18. // Copyright © 2018 AamirAnwar. All rights reserved. // import UIKit class BSMessage: NSObject { var id:String! var text:String! var senderID:String! var senderName:String! var chatID:String! static func initWith(id:String, dict:[String:AnyObject]) -> BSMessage{ let message = BSMessage() message.id = id message.senderID = dict["sender_id"] as! String message.senderName = dict["sender_name"] as! String message.text = dict["text"] as! String message.chatID = dict["chat_id"] as! String return message } }
23.413793
74
0.62592
e25aa90ddb479dc61e3c1ea57b157c2345b556af
8,991
// // AnimatedField+Protocols.swift // FashTime // // Created by Alberto Aznar de los Ríos on 02/04/2019. // Copyright © 2019 FashTime Ltd. All rights reserved. // import UIKit public protocol AnimatedFieldDataSource: class { /** ------------------------------------------------------------------------------------------ Returns boolean to check if field can be changed ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - parameter range: character range - parameter string: character - returns: boolean */ func animatedField(_ animatedField: AnimatedField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool? /** ------------------------------------------------------------------------------------------ Returns boolean to check if field can return ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: boolean */ func animatedFieldShouldReturn(_ animatedField: AnimatedField) -> Bool /** ------------------------------------------------------------------------------------------ Returns characters limit ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: maximum of characters you want for this field */ func animatedFieldLimit(_ animatedField: AnimatedField) -> Int? /** ------------------------------------------------------------------------------------------ Returns regular expression to filter characters when user is typing ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: regular expression you want to apply to this field */ func animatedFieldTypingMatches(_ animatedField: AnimatedField) -> String? /** ------------------------------------------------------------------------------------------ Returns regular expression to filter field when user ends editing ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: regular expression you want to apply to this field */ func animatedFieldValidationMatches(_ animatedField: AnimatedField) -> String? /** ------------------------------------------------------------------------------------------ Returns alert message when validation fails ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: validation error message */ func animatedFieldValidationError(_ animatedField: AnimatedField) -> String? /** ------------------------------------------------------------------------------------------ Returns alert message when price exceeded limits (only for price type) ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - returns: validation error message */ func animatedFieldPriceExceededError(_ animatedField: AnimatedField) -> String? } public extension AnimatedFieldDataSource { func animatedField(_ animatedField: AnimatedField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool? { // Optional return nil } func animatedFieldShouldReturn(_ animatedField: AnimatedField) -> Bool { // Optional return true } func animatedFieldLimit(_ animatedField: AnimatedField) -> Int? { // Optional return Int.max } func animatedFieldTypingMatches(_ animatedField: AnimatedField) -> String? { // Optional return nil } func animatedFieldValidationMatches(_ animatedField: AnimatedField) -> String? { // Optional return nil } func animatedFieldValidationError(_ animatedField: AnimatedField) -> String? { // Optional return nil } func animatedFieldPriceExceededError(_ animatedField: AnimatedField) -> String? { // Optional return nil } } public protocol AnimatedFieldDelegate: class { /** ------------------------------------------------------------------------------------------ Is called when text field begin editing ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField */ func animatedFieldDidBeginEditing(_ animatedField: AnimatedField) /** ------------------------------------------------------------------------------------------ Is called when text field end editing ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField */ func animatedFieldDidEndEditing(_ animatedField: AnimatedField) /** ------------------------------------------------------------------------------------------ Is called when field (multiline) is resized ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - parameter height: current height */ func animatedField(_ animatedField: AnimatedField, didResizeHeight height: CGFloat) /** ------------------------------------------------------------------------------------------ Is called when secure button is pressed ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - parameter secure: secured text */ func animatedField(_ animatedField: AnimatedField, didSecureText secure: Bool) /** ------------------------------------------------------------------------------------------ Is called when picker value is changed ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - parameter value: selected value text */ func animatedField(_ animatedField: AnimatedField, didChangePickerValue value: String) /** ------------------------------------------------------------------------------------------ Is called when alert message is shown ------------------------------------------------------------------------------------------ - parameter animatedField: current animatedField - parameter value: alert text */ func animatedField(_ animatedField: AnimatedField, didShowAlertMessage text: String) } public extension AnimatedFieldDelegate { func animatedFieldDidBeginEditing(_ animatedField: AnimatedField) { // Optional } func animatedFieldDidEndEditing(_ animatedField: AnimatedField) { // Optional } func animatedField(_ animatedField: AnimatedField, didResizeHeight height: CGFloat) { // Optional } func animatedField(_ animatedField: AnimatedField, didSecureText secure: Bool) { // Optional } func animatedField(_ animatedField: AnimatedField, didChangePickerValue value: String) { // Optional } func animatedField(_ animatedField: AnimatedField, didShowAlertMessage text: String) { // Optional } } public protocol AnimatedFieldInterface { /** ------------------------------------------------------------------------------------------ Restart field ------------------------------------------------------------------------------------------ */ func restart() /** ------------------------------------------------------------------------------------------ Show alert status ------------------------------------------------------------------------------------------ - parameter message: alert message */ func showAlert(_ message: String?) /** ------------------------------------------------------------------------------------------ Hide alert message ------------------------------------------------------------------------------------------ */ func hideAlert() /** ------------------------------------------------------------------------------------------ Secure field with dots (no visible) ------------------------------------------------------------------------------------------ */ func secureField(_ secure: Bool) }
39.091304
140
0.432321
8f13ed3234bb0c09fcdab63975cdbe14635d2bd9
5,737
import Foundation final class AccountManagementWireframe: AccountManagementWireframeProtocol, AuthorizationPresentable { func showCreateAccount( from view: ControllerBackedProtocol?, wallet: MetaAccountModel, chainId: ChainModel.Id, isEthereumBased: Bool ) { guard let createAccountView = AccountCreateViewFactory.createViewForReplaceChainAccount( metaAccountModel: wallet, chainModelId: chainId, isEthereumBased: isEthereumBased ) else { return } let controller = createAccountView.controller controller.hidesBottomBarWhenPushed = true if let navigationController = view?.controller.navigationController { navigationController.pushViewController(controller, animated: true) } } func showImportAccount( from view: ControllerBackedProtocol?, wallet: MetaAccountModel, chainId: ChainModel.Id, isEthereumBased: Bool ) { let options = SecretSource.displayOptions let handler: (Int) -> Void = { [weak self] selectedIndex in self?.presentImport( from: view, secretSource: options[selectedIndex], wallet: wallet, chainId: chainId, isEthereumBased: isEthereumBased ) } guard let picker = ModalPickerFactory.createPickerListForSecretSource( options: options, delegate: self, context: ModalPickerClosureContext(handler: handler) ) else { return } view?.controller.present(picker, animated: true, completion: nil) } func showExportAccount( for wallet: MetaAccountModel, chain: ChainModel, options: [SecretSource], from view: AccountManagementViewProtocol? ) { authorize(animated: true, cancellable: true) { [weak self] success in if success { self?.performExportPresentation( for: wallet, chain: chain, options: options, from: view ) } } } // MARK: Private private func performExportPresentation( for wallet: MetaAccountModel, chain: ChainModel, options: [SecretSource], from view: AccountManagementViewProtocol? ) { let handler: (Int) -> Void = { [weak self] selectedIndex in switch options[selectedIndex] { case .keystore: self?.showKeystoreExport(for: wallet, chain: chain, from: view) case .seed: self?.showSeedExport(for: wallet, chain: chain, from: view) case .mnemonic: self?.showMnemonicExport(for: wallet, chain: chain, from: view) } } guard let picker = ModalPickerFactory.createPickerListForSecretSource( options: options, delegate: self, context: ModalPickerClosureContext(handler: handler) ) else { return } view?.controller.present(picker, animated: true, completion: nil) } private func showMnemonicExport( for metaAccount: MetaAccountModel, chain: ChainModel, from view: AccountManagementViewProtocol? ) { guard let mnemonicView = ExportMnemonicViewFactory.createViewForMetaAccount(metaAccount, chain: chain) else { return } view?.controller.navigationController?.pushViewController( mnemonicView.controller, animated: true ) } private func showKeystoreExport( for wallet: MetaAccountModel, chain: ChainModel, from view: AccountManagementViewProtocol? ) { guard let passwordView = AccountExportPasswordViewFactory.createView( with: wallet, chain: chain ) else { return } view?.controller.navigationController?.pushViewController( passwordView.controller, animated: true ) } private func showSeedExport( for wallet: MetaAccountModel, chain: ChainModel, from view: AccountManagementViewProtocol? ) { guard let seedView = ExportSeedViewFactory.createViewForMetaAccount(wallet, chain: chain) else { return } view?.controller.navigationController?.pushViewController( seedView.controller, animated: true ) } private func presentImport( from view: ControllerBackedProtocol?, secretSource: SecretSource, wallet: MetaAccountModel, chainId: ChainModel.Id, isEthereumBased: Bool ) { guard let importAccountView = AccountImportViewFactory.createViewForReplaceChainAccount( secretSource: secretSource, modelId: chainId, isEthereumBased: isEthereumBased, in: wallet ) else { return } let controller = importAccountView.controller controller.hidesBottomBarWhenPushed = true if let navigationController = view?.controller.navigationController { navigationController.pushViewController(controller, animated: true) } } } extension AccountManagementWireframe: ModalPickerViewControllerDelegate { func modalPickerDidSelectModelAtIndex(_ index: Int, context: AnyObject?) { guard let closureContext = context as? ModalPickerClosureContext else { return } closureContext.process(selectedIndex: index) } }
31.349727
117
0.610249
ccc941e6b87672aa4cb75c7b8c0db5b075fbb542
890
// // OSRouterTests.swift // OSRouterTests // // Created by 张飞 on 2019/11/18. // Copyright © 2019 张飞. All rights reserved. // import XCTest @testable import OSRouter class OSRouterTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.428571
111
0.650562
8a442e080bc17265b88034e11524130d7cbbd182
948
// // Copyright © 2019 MBition GmbH. All rights reserved. // import Foundation /// Representation of a dealer item of a vehicle public struct VehicleDealerItemModel { public let dealerId: String public let role: DealerRole public let merchant: DealerMerchantModel? } // MARK: - Equatable extension VehicleDealerItemModel: Equatable { public static func == (lhs: VehicleDealerItemModel, rhs: VehicleDealerItemModel) -> Bool { return lhs.dealerId == rhs.dealerId && lhs.role.rawValue == rhs.role.rawValue } } // MARK: - VehicleDealerUpdateModel public struct VehicleDealerUpdateModel { public let dealerId: String public let role: DealerRole // MARK: - Init public init(dealerId: String, role: DealerRole) { self.dealerId = dealerId self.role = role } } // MARK: - APIVehicleDealerUpdateModel public struct APIVehicleDealerUpdateModel: Codable { public let dealerId: String public let role: DealerRole }
18.588235
91
0.740506
8a6ebe58da9cefa7318ac515cfc1810526a8d2dd
1,879
import AppKit extension NSPopUpButton { var selectedTitle: String { return self.selectedItem?.title ?? "" } func setItems(titles: [String]) { let selectedTitle = self.selectedTitle self.removeAllItems() self.addItems(withTitles: titles) self.selectItem(withTitle: selectedTitle) if self.selectedItem == nil && self.numberOfItems > 0 { self.selectItem(at: 0) } } func set<T>(items: [T], getTitle: (T) -> String, getGroup: (T) -> String) { let menu = NSMenu() menu.autoenablesItems = false menu.set(items: items, getTitle: getTitle, getGroup: getGroup) self.menu = menu if let index = menu.items.index(where: { $0.indentationLevel == 1 }) { self.selectItem(at: index) } } } extension NSPopUpButton: Validatable { var isValid: Bool { return !self.selectedTitle.isEmpty } } private extension NSMenu { func set<T>(items: [T], getTitle: (T) -> String, getGroup: (T) -> String) { var groups = [String]() var titlesForGroup = [String: [String]]() for item in items { let group = getGroup(item) if !groups.contains(group) { groups.append(group) } let names = titlesForGroup[group] ?? [] titlesForGroup[group] = names + [getTitle(item)] } for group in groups { let titles = titlesForGroup[group]! let topLevelItem = NSMenuItem() topLevelItem.isEnabled = false topLevelItem.title = group self.addItem(topLevelItem) for title in titles { let item = NSMenuItem() item.title = title item.indentationLevel = 1 self.addItem(item) } } } }
28.469697
79
0.550293
20dab8201385d9fb21daecae1d053e3f5cf1b9ae
3,919
// // ViewController.swift // HelloMap.Swift // // Created by Aare Undo on 22/09/16. // Copyright © 2016 Aare Undo. All rights reserved. // import UIKit import CartoMobileSDK class ViewController: UIViewController { var mapView: NTMapView? override func viewDidLoad() { super.viewDidLoad() // Miminal sample code follows title = "Hello Map" // Create NTMapView mapView = NTMapView() view = mapView // Set common options. Use EPSG4326 projection so that longitude/latitude can be directly used for coordinates. let proj = NTEPSG4326() mapView?.getOptions()?.setBaseProjection(proj) mapView?.getOptions()?.setRenderProjectionMode(NTRenderProjectionMode.RENDER_PROJECTION_MODE_SPHERICAL) mapView?.getOptions()?.setZoomGestures(true) // Create base map layer let baseLayer = NTCartoOnlineVectorTileLayer(style: NTCartoBaseMapStyle.CARTO_BASEMAP_STYLE_VOYAGER) mapView?.getLayers().add(baseLayer) // Create map position located at Tallinn, Estonia let tallinn = NTMapPos(x: 24.646469, y: 59.426939) // Animate map to Tallinn, Estonia mapView?.setFocus(tallinn, durationSeconds: 0) mapView?.setRotation(0, durationSeconds: 0) mapView?.setZoom(3, durationSeconds: 0) mapView?.setZoom(4, durationSeconds: 2) // Initialize a local vector data source let vectorDataSource = NTLocalVectorDataSource(projection: proj) // Initialize a vector layer with the created data source let vectorLayer = NTVectorLayer(dataSource: vectorDataSource) // Add the created layer to the map mapView?.getLayers().add(vectorLayer) // Create a marker marker style let markerStyleBuilder = NTMarkerStyleBuilder() markerStyleBuilder?.setSize(15) markerStyleBuilder?.setColor(NTColor(r: 0, g: 255, b: 0, a: 255)) let markerStyle = markerStyleBuilder?.buildStyle() // Create a marker with the previously defined style and add it to the data source let marker = NTMarker(pos: tallinn, style: markerStyle) vectorDataSource?.add(marker) // Create a map listener so that we will receive click events on a map let listener = HelloMapListener(vectorDataSource: vectorDataSource!) mapView?.setMapEventListener(listener) } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Disconnect listener from the mapView to avoid leaks let mapView = view as! NTMapView mapView.setMapEventListener(nil) } } public class HelloMapListener : NTMapEventListener { var vectorDataSource: NTLocalVectorDataSource! convenience init(vectorDataSource: NTLocalVectorDataSource!) { self.init() self.vectorDataSource = vectorDataSource } override public func onMapClicked(_ mapClickInfo: NTMapClickInfo!) { // Create a new marker with random style at the clicked location let markerStyleBuilder = NTMarkerStyleBuilder() let size = Float(arc4random_uniform(20) + 10) markerStyleBuilder?.setSize(size) var colors = [ NTColor(r: 255, g: 255, b: 255, a: 255), NTColor(r: 0, g: 0, b: 255, a: 255), NTColor(r: 255, g: 0, b: 0, a: 255), NTColor(r: 0, g: 255, b: 0, a: 255), NTColor(r: 0, g: 200, b: 0, a: 255), ] let color = colors[Int(arc4random_uniform(4))] markerStyleBuilder?.setColor(color) let markerStyle = markerStyleBuilder?.buildStyle() let marker = NTMarker(pos: mapClickInfo.getClickPos(), style: markerStyle) self.vectorDataSource.add(marker) } }
35.954128
119
0.643276
1161f3b4419bc84d1f818c5c6ed54bd303373964
1,907
@_exported import ObjectiveC // Clang module // The iOS/arm64 target uses _Bool for Objective C's BOOL. We include // x86_64 here as well because the iOS simulator also uses _Bool. #if ((os(iOS) || os(tvOS)) && (arch(arm64) || arch(x86_64))) || os(watchOS) public struct ObjCBool : BooleanType { private var value : Bool public init(_ value: Bool) { self.value = value } /// \brief Allow use in a Boolean context. public var boolValue: Bool { return value } } #else public struct ObjCBool : BooleanType { private var value : UInt8 public init(_ value: Bool) { self.value = value ? 1 : 0 } public init(_ value: UInt8) { self.value = value } /// \brief Allow use in a Boolean context. public var boolValue: Bool { if value == 0 { return false } return true } } #endif extension ObjCBool : BooleanLiteralConvertible { public init(booleanLiteral: Bool) { self.init(booleanLiteral) } } public struct Selector : StringLiteralConvertible { private var ptr : COpaquePointer public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init (stringLiteral value: String) { self = sel_registerName(value) } } public struct NSZone: NilLiteralConvertible { public var pointer : COpaquePointer @_transparent public init(nilLiteral: ()) { pointer = COpaquePointer() } } internal func _convertBoolToObjCBool(x: Bool) -> ObjCBool { return ObjCBool(x) } internal func _convertObjCBoolToBool(x: ObjCBool) -> Bool { return Bool(x) } public func ~=(x: NSObject, y: NSObject) -> Bool { return true } extension NSObject : Equatable, Hashable { public var hashValue: Int { return hash } } public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) }
20.728261
75
0.686943
01955dd60834657063df898c1748742d412642da
2,120
// // DateFieldElementTest.swift // StripeUICoreTests // // Created by Mel Ludowise on 10/8/21. // import XCTest @_spi(STP) @testable import StripeUICore final class DateFieldElementTest: XCTestCase { // Mock dates let oct1_2021 = Date(timeIntervalSince1970: 1633046400) let oct3_2021 = Date(timeIntervalSince1970: 1633219200) func testNoDefault() { let element = DateFieldElement(label: "") XCTAssertNil(element.selectedDate) } func testWithDefault() { let element = DateFieldElement(label: "", defaultDate: oct1_2021) XCTAssertEqual(element.selectedDate, oct1_2021) } func testDefaultExceedsMax() { let element = DateFieldElement(label: "", defaultDate: oct3_2021, maximumDate: oct1_2021) XCTAssertNil(element.selectedDate) } func testDefaultExceedsMin() { let element = DateFieldElement(label: "", defaultDate: oct1_2021, minimumDate: oct3_2021) XCTAssertNil(element.selectedDate) } func testDidUpdate() { var date: Date? let element = DateFieldElement(label: "", didUpdate: { date = $0 }) XCTAssertNil(date) // Emulate a user changing the picker and hitting done button element.datePickerView.date = oct3_2021 element.didSelectDate() element.didFinish(element.pickerFieldView) XCTAssertEqual(date, oct3_2021) } func testDidUpdateToDefault() { // Ensure `didUpdate` is not called if the selection doesn't change var date: Date? let element = DateFieldElement(label: "", defaultDate: oct1_2021, didUpdate: { date = $0 }) XCTAssertNil(date) // Emulate a user changing the picker element.datePickerView.date = oct3_2021 element.didSelectDate() XCTAssertNil(date) // Emulate the user changing the picker back element.datePickerView.date = oct1_2021 element.didSelectDate() XCTAssertNil(date) // Emulate user hitting the done button element.didFinish(element.pickerFieldView) XCTAssertNil(date) } }
30.724638
99
0.668868
6248754790c60bdcd280f7ed4f7b4aba21ff027d
2,291
// // SceneDelegate.swift // CP-Prework // // Created by Tyler Dakin on 1/11/22. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.226415
147
0.712353
79ef055b63d07908c4236c20ac6bfd92d37d85e1
190
// // RewardReq.swift // GoodieCore // // Created by GoodieMac2 on 19/06/19. // import Foundation struct RewardReq: Codable { var rewardId: String var quantity: Int }
11.875
38
0.631579
11084525364d63a82b48004dfbe44dce2aa181e6
5,268
import Foundation public extension Date { var firstDayOfCurrentMonth: Date { return (Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self)))! } var isFirstDayOfCurrentMonth: Bool { return self == firstDayOfCurrentMonth } var firstHourOfCurrentDate: Date { return (Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self)))! } var lastDayOfCurrentMonth: Date { return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: firstDayOfCurrentMonth)! } var year: Int { let calendar = Calendar.current return calendar.component(.year, from: self) } var month: Int { let calendar = Calendar.current return calendar.component(.month, from: self) } var day: Int { let calendar = Calendar.current return calendar.component(.day, from: self) } var hour: Int { let calendar = Calendar.current return calendar.component(.hour, from: self) } var minute: Int { let calendar = Calendar.current return calendar.component(.minute, from: self) } func toFormattedSpanishDateString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" let converted = dateFormatter.string(from: self) return converted } func toFormattedSpanishFullDateString(useHourSuffix: Bool = true) -> String { let dateFormatter = DateFormatter() if useHourSuffix { dateFormatter.dateFormat = "dd/MM/yyyy - HH:mm'h.'" } else { dateFormatter.dateFormat = "dd/MM/yyyy - HH:mm" } let converted = dateFormatter.string(from: self) return converted } func toFormattedSpanishFullDateString(withEndDate end: Date, useHourSuffix: Bool = true) -> String { let datef = DateFormatter() datef.dateFormat = "dd/MM/yyyy" let timef = DateFormatter() if useHourSuffix { timef.dateFormat = "HH:mm'h.'" } else { timef.dateFormat = "HH:mm" } return "\(datef.string(from: self)) - \(timef.string(from: self)) a \(timef.string(from: end))" } func toFormattedSpanishMonthName() -> String { let datef = DateFormatter() datef.dateFormat = "M MMMM" return "\(datef.string(from: self))" } func toFormattedJsonDateString(useUtc: Bool = true) -> String { let dateFormatter = DateFormatter() if useUtc { dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" } else { dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" } let converted = dateFormatter.string(from: self) return converted } func toFormattedPOSIXDate() -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter.string(from: self) } func dateByAdding(years: Int) -> Date { let components = DateComponents(year: years) return Calendar.current.date(byAdding: components, to: self)! } func dateByAdding(days: Int) -> Date { let components = DateComponents(day: days) return Calendar.current.date(byAdding: components, to: self)! } func dateByAdding(months: Int) -> Date { let components = DateComponents(month: months) return Calendar.current.date(byAdding: components, to: self)! } func dateByAdding(hours: Int) -> Date { let components = DateComponents(minute: minute) return Calendar.current.date(byAdding: components, to: self)! } func dateByAdding(minutes: Int) -> Date { let components = DateComponents(minute: minute) return Calendar.current.date(byAdding: components, to: self)! } func totalDays(from date: Date) -> Int { if self < date { return 0 } return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } func days(from date: Date) -> [Date] { var days = [Date]() for iterator in 0...self.totalDays(from: date) { days.append(date.dateByAdding(days: iterator)) } return days } func totalMonths(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date.firstDayOfCurrentMonth, to: self.firstDayOfCurrentMonth).month ?? 0 } func totalAbsoluteMonths(from date: Date) -> Int { return self.totalMonths(from: date) + 1 } var localTime: Time { let timef = DateFormatter() timef.dateFormat = "HH:mm:ss" let timeString = timef.string(from: self) let components = timeString.components(separatedBy: ":") return Time(hours: Int(components[0])!, minutes: Int(components[1])!, seconds: Int(components[2])!) } }
32.720497
135
0.608011
4bdd789df4be1aa0c09e4758f536289dd08792d1
2,174
// // The MIT License (MIT) // // Copyright (c) 2017 Tommaso Madonia // // 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. // // MARK: - Logger protocol public protocol Logger { var enabled: Bool { get set } var level: LogLevel { get set } func debug(_ message: @autoclosure () -> String) func info(_ message: @autoclosure () -> String) func warn(_ message: @autoclosure () -> String) func error(_ message: @autoclosure () -> String) } // MARK: - LoggerLevel enum public enum LogLevel: CustomStringConvertible, Comparable { case debug, info, warning, error public var description: String { switch self { case .debug: return "DEBUG" case .info: return "INFO" case .warning: return "WARN" case .error: return "ERROR" } } public static func <(lhs: LogLevel, rhs: LogLevel) -> Bool { switch (lhs, rhs) { case (let lhs, .debug) where lhs != .debug: return true case (.warning, .info), (.error, .info): return true case (.error, .warning): return true default: return false } } }
33.96875
81
0.673413
9144ee32fbb11a62444e5081100fe9791c6748be
26,818
/* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ import Foundation import Markdown import SymbolKit /// A programming symbol semantic type. /// /// This class's properties are represented using ``DocumentationDataVariants`` values which encode the different variants for each piece of information /// about the symbol. For example, if a symbol is available in multiple programming languages, the ``titleVariants`` property represents the title of the symbol /// for each programming language it's available in. Use a ``DocumentationDataVariantsTrait`` to access a specific variant. /// /// ## Topics /// /// ### Properties /// /// - ``titleVariants`` /// - ``subHeadingVariants`` /// - ``navigatorVariants`` /// - ``roleHeadingVariants`` /// - ``kindVariants`` /// - ``platformNameVariants`` /// - ``moduleNameVariants`` /// - ``extendedModuleVariants`` /// - ``bystanderModuleNamesVariants`` /// - ``isRequiredVariants`` /// - ``externalIDVariants`` /// - ``accessLevelVariants`` /// - ``deprecatedSummaryVariants`` /// - ``declarationVariants`` /// - ``locationVariants`` /// - ``constraintsVariants`` /// - ``originVariants`` /// - ``availabilityVariants`` /// - ``relationshipsVariants`` /// - ``abstractSectionVariants`` /// - ``discussionVariants`` /// - ``topicsVariants`` /// - ``defaultImplementationsVariants`` /// - ``seeAlsoVariants`` /// - ``returnsSectionVariants`` /// - ``parametersSectionVariants`` /// - ``redirectsVariants`` /// - ``abstractVariants`` /// - ``isDeprecatedVariants`` /// - ``isSPIVariants`` /// /// ### First Variant Accessors /// /// Convenience APIs for accessing the first variant of the symbol's properties. /// /// - ``kind`` /// - ``title`` /// - ``subHeading`` /// - ``navigator`` /// - ``roleHeading`` /// - ``platformName`` /// - ``moduleName`` /// - ``isRequired`` /// - ``externalID`` /// - ``extendedModule`` /// - ``bystanderModuleNames`` /// - ``deprecatedSummary`` /// - ``declaration`` /// - ``location`` /// - ``constraints`` /// - ``origin`` /// - ``availability`` /// - ``relationships`` /// - ``accessLevel`` /// - ``discussion`` /// - ``abstractSection`` /// - ``topics`` /// - ``defaultImplementations`` /// - ``seeAlso`` /// - ``redirects`` /// - ``returnsSection`` /// - ``parametersSection`` /// - ``abstract`` /// - ``isDeprecated`` /// - ``isSPI`` /// /// ### Variants /// /// - ``DocumentationDataVariants`` /// - ``DocumentationDataVariantsTrait`` public final class Symbol: Semantic, Abstracted, Redirected, AutomaticTaskGroupsProviding { /// The title of the symbol in each language variant the symbol is available in. internal(set) public var titleVariants: DocumentationDataVariants<String> /// The simplified version of the symbol's declaration in each language variant the symbol is available in. internal(set) public var subHeadingVariants: DocumentationDataVariants<[SymbolGraph.Symbol.DeclarationFragments.Fragment]> /// The simplified version of this symbol's declaration in each language variant the symbol is available in. internal(set) public var navigatorVariants: DocumentationDataVariants<[SymbolGraph.Symbol.DeclarationFragments.Fragment]> /// The presentation-friendly version of the symbol's kind in each language variant the symbol is available in. internal(set) public var roleHeadingVariants: DocumentationDataVariants<String> /// The kind of the symbol in each language variant the symbol is available in. internal(set) public var kindVariants: DocumentationDataVariants<SymbolGraph.Symbol.Kind> /// The symbol's platform in each language variant the symbol is available in. internal(set) public var platformNameVariants: DocumentationDataVariants<PlatformName> /// The presentation-friendly name of the symbol's framework in each language variant the symbol is available in. internal(set) public var moduleNameVariants: DocumentationDataVariants<String> /// The name of the module extension in which the symbol is defined, if applicable, in each language variant the symbol is available in. internal(set) public var extendedModuleVariants: DocumentationDataVariants<String> /// Optional cross-import module names of the symbol, in each language variant the symbol is available in. internal(set) public var bystanderModuleNamesVariants: DocumentationDataVariants<[String]> /// Whether the symbol is required in its context, in each language variant the symbol is available in. public var isRequiredVariants: DocumentationDataVariants<Bool> /// The symbol's external identifier, if available, in each language variant the symbol is available in. public var externalIDVariants: DocumentationDataVariants<String> /// The symbol's access level, if available, in each language variant the symbol is available in. public var accessLevelVariants: DocumentationDataVariants<String> /// The symbol's deprecation information, if deprecated, in each language variant the symbol is available in. public var deprecatedSummaryVariants: DocumentationDataVariants<DeprecatedSection> /// The symbol's declarations in each language variant the symbol is available in. public var declarationVariants = DocumentationDataVariants<[[PlatformName?]: SymbolGraph.Symbol.DeclarationFragments]>( defaultVariantValue: [:] ) public var locationVariants = DocumentationDataVariants<SymbolGraph.Symbol.Location>() /// The symbol's availability or conformance constraints, in each language variant the symbol is available in. public var constraintsVariants = DocumentationDataVariants<[SymbolGraph.Symbol.Swift.GenericConstraint]>() /// The inheritance information for the symbol in each language variant the symbol is available in. public var originVariants: DocumentationDataVariants<SymbolGraph.Relationship.SourceOrigin> /// The platforms on which the symbol is available in each language variant the symbol is available in. /// /// - Note: Updating this property recalculates ``isDeprecatedVariants``. public var availabilityVariants: DocumentationDataVariants<SymbolGraph.Symbol.Availability> { didSet { for (trait, variant) in availabilityVariants.allValues { // When appending more platform availabilities to the symbol // update its deprecation status isDeprecatedVariants[trait] = AvailabilityParser(variant).isDeprecated() } } } /// The presentation-friendly relationships of this symbol to other symbols, in each language variant the symbol is available in. public var relationshipsVariants = DocumentationDataVariants<RelationshipsSection>(defaultVariantValue: .init()) /// An optional, abstract summary for the symbol, in each language variant the symbol is available in. public var abstractSectionVariants: DocumentationDataVariants<AbstractSection> /// An optional discussion for the symbol, in each language variant the symbol is available in. public var discussionVariants: DocumentationDataVariants<DiscussionSection> /// The topics task groups for the symbol, in each language variant the symbol is available in. public var topicsVariants: DocumentationDataVariants<TopicsSection> /// Any default implementations of the symbol, if the symbol is a protocol requirement, in each language variant the symbol is available in. public var defaultImplementationsVariants = DocumentationDataVariants<DefaultImplementationsSection>(defaultVariantValue: .init()) /// Any See Also groups of the symbol, in each language variant the symbol is available in. public var seeAlsoVariants: DocumentationDataVariants<SeeAlsoSection> /// Any return value information of the symbol, if the symbol returns, in each language variant the symbol is available in. public var returnsSectionVariants: DocumentationDataVariants<ReturnsSection> /// Any parameters of the symbol, if the symbol accepts parameters, in each language variant the symbol is available in. public var parametersSectionVariants: DocumentationDataVariants<ParametersSection> /// Any redirect information of the symbol, if the symbol has been moved from another location, in each language variant the symbol is available in. public var redirectsVariants: DocumentationDataVariants<[Redirect]> /// The symbol's abstract summary as a single paragraph, in each language variant the symbol is available in. public var abstractVariants: DocumentationDataVariants<Paragraph> { DocumentationDataVariants( values: Dictionary(uniqueKeysWithValues: abstractSectionVariants.allValues.map { ($0, $1.paragraph) }) ) } /// Whether the symbol is deprecated, in each language variant the symbol is available in. public var isDeprecatedVariants = DocumentationDataVariants<Bool>(defaultVariantValue: false) /// Whether the symbol is declared as an SPI, in each language variant the symbol is available in. public var isSPIVariants = DocumentationDataVariants<Bool>(defaultVariantValue: false) /// The mixins of the symbol, in each language variant the symbol is available in. var mixinsVariants: DocumentationDataVariants<[String: Mixin]> /// Any automatically created task groups of the symbol, in each language variant the symbol is available in. var automaticTaskGroupsVariants: DocumentationDataVariants<[AutomaticTaskGroupSection]> /// Creates a new symbol with the given data. init( kindVariants: DocumentationDataVariants<SymbolGraph.Symbol.Kind>, titleVariants: DocumentationDataVariants<String>, subHeadingVariants: DocumentationDataVariants<[SymbolGraph.Symbol.DeclarationFragments.Fragment]>, navigatorVariants: DocumentationDataVariants<[SymbolGraph.Symbol.DeclarationFragments.Fragment]>, roleHeadingVariants: DocumentationDataVariants<String>, platformNameVariants: DocumentationDataVariants<PlatformName>, moduleNameVariants: DocumentationDataVariants<String>, extendedModuleVariants: DocumentationDataVariants<String> = .init(), requiredVariants: DocumentationDataVariants<Bool> = .init(defaultVariantValue: false), externalIDVariants: DocumentationDataVariants<String>, accessLevelVariants: DocumentationDataVariants<String>, availabilityVariants: DocumentationDataVariants<SymbolGraph.Symbol.Availability>, deprecatedSummaryVariants: DocumentationDataVariants<DeprecatedSection>, mixinsVariants: DocumentationDataVariants<[String: Mixin]>, declarationVariants: DocumentationDataVariants<[[PlatformName?]: SymbolGraph.Symbol.DeclarationFragments]> = .init(defaultVariantValue: [:]), defaultImplementationsVariants: DocumentationDataVariants<DefaultImplementationsSection> = .init(defaultVariantValue: .init()), relationshipsVariants: DocumentationDataVariants<RelationshipsSection> = .init(), abstractSectionVariants: DocumentationDataVariants<AbstractSection>, discussionVariants: DocumentationDataVariants<DiscussionSection>, topicsVariants: DocumentationDataVariants<TopicsSection>, seeAlsoVariants: DocumentationDataVariants<SeeAlsoSection>, returnsSectionVariants: DocumentationDataVariants<ReturnsSection>, parametersSectionVariants: DocumentationDataVariants<ParametersSection>, redirectsVariants: DocumentationDataVariants<[Redirect]>, bystanderModuleNamesVariants: DocumentationDataVariants<[String]> = .init(), originVariants: DocumentationDataVariants<SymbolGraph.Relationship.SourceOrigin> = .init(), automaticTaskGroupsVariants: DocumentationDataVariants<[AutomaticTaskGroupSection]> = .init(defaultVariantValue: []) ) { self.kindVariants = kindVariants self.titleVariants = titleVariants self.subHeadingVariants = subHeadingVariants self.navigatorVariants = navigatorVariants self.roleHeadingVariants = roleHeadingVariants self.platformNameVariants = platformNameVariants self.moduleNameVariants = moduleNameVariants self.bystanderModuleNamesVariants = bystanderModuleNamesVariants self.isRequiredVariants = requiredVariants self.externalIDVariants = externalIDVariants self.accessLevelVariants = accessLevelVariants self.availabilityVariants = availabilityVariants for (trait, variant) in availabilityVariants.allValues { self.isDeprecatedVariants[trait] = AvailabilityParser(variant).isDeprecated() } self.deprecatedSummaryVariants = deprecatedSummaryVariants self.declarationVariants = declarationVariants self.mixinsVariants = mixinsVariants for (trait, variant) in mixinsVariants.allValues { for item in variant.values { switch item { case let declaration as SymbolGraph.Symbol.DeclarationFragments: // If declaration wasn't set explicitly use the one from the mixins. if !self.declarationVariants.hasVariant(for: trait) { self.declarationVariants[trait] = [[platformNameVariants[trait]]: declaration] } case let extensionConstraints as SymbolGraph.Symbol.Swift.Extension where !extensionConstraints.constraints.isEmpty: self.constraintsVariants[trait] = extensionConstraints.constraints case let location as SymbolGraph.Symbol.Location: self.locationVariants[trait] = location case let spi as SymbolGraph.Symbol.SPI: self.isSPIVariants[trait] = spi.isSPI default: break; } } } if !relationshipsVariants.isEmpty { self.relationshipsVariants = relationshipsVariants } self.defaultImplementationsVariants = defaultImplementationsVariants self.abstractSectionVariants = abstractSectionVariants self.discussionVariants = discussionVariants self.topicsVariants = topicsVariants self.seeAlsoVariants = seeAlsoVariants self.returnsSectionVariants = returnsSectionVariants self.parametersSectionVariants = parametersSectionVariants self.redirectsVariants = redirectsVariants self.originVariants = originVariants self.automaticTaskGroupsVariants = automaticTaskGroupsVariants self.extendedModuleVariants = extendedModuleVariants } public override func accept<V: SemanticVisitor>(_ visitor: inout V) -> V.Result { return visitor.visitSymbol(self) } } extension Symbol { /// Merges a symbol declaration from another symbol graph into the current symbol. /// /// When building multi-platform documentation symbols might have more than one declaration /// depending on variances in their implementation across platforms (e.g. use `NSPoint` vs `CGPoint` parameter in a method). /// This method finds matching symbols between graphs and merges their declarations in case there are differences. func mergeDeclaration(mergingDeclaration: SymbolGraph.Symbol.DeclarationFragments, identifier: String, symbolAvailability: SymbolGraph.Symbol.Availability?, selector: UnifiedSymbolGraph.Selector) throws { let trait = DocumentationDataVariantsTrait(interfaceLanguage: selector.interfaceLanguage) let platformName = selector.platform if let platformName = platformName, let existingKey = declarationVariants[trait]?.first( where: { pair in return pair.value.declarationFragments == mergingDeclaration.declarationFragments } )?.key { guard !existingKey.contains(nil) else { throw DocumentationContext.ContextError.unexpectedEmptyPlatformName(identifier) } let platform = PlatformName(operatingSystemName: platformName) if !existingKey.contains(platform) { // Matches one of the existing declarations, append to the existing key. let currentDeclaration = declarationVariants[trait]?.removeValue(forKey: existingKey)! declarationVariants[trait]?[existingKey + [platform]] = currentDeclaration } } else { // Add new declaration if let name = platformName { declarationVariants[trait]?[[PlatformName.init(operatingSystemName: name)]] = mergingDeclaration } else { declarationVariants[trait]?[[nil]] = mergingDeclaration } } // Merge the new symbol with the existing availability. If a value already exist, only override if it's for this platform. if let symbolAvailability = symbolAvailability, symbolAvailability.availability.isEmpty == false || availabilityVariants[trait]?.availability.isEmpty == false // Nothing to merge if both are empty { var items = availabilityVariants[trait]?.availability ?? [] // Add all the domains that don't already have availability information for availability in symbolAvailability.availability { guard !items.contains(where: { $0.domain?.rawValue == availability.domain?.rawValue }) else { continue } items.append(availability) } // Override the availability for all domains that apply to this platform if let modulePlatformName = platformName.map(PlatformName.init) { let symbolAvailabilityForPlatform = symbolAvailability.filterItems(thatApplyTo: modulePlatformName) for availability in symbolAvailabilityForPlatform.availability { items.removeAll(where: { $0.domain?.rawValue == availability.domain?.rawValue }) items.append(availability) } } availabilityVariants[trait] = SymbolGraph.Symbol.Availability(availability: items) } } func mergeDeclarations(unifiedSymbol: UnifiedSymbolGraph.Symbol) throws { for (selector, mixins) in unifiedSymbol.mixins { if let mergingDeclaration = mixins[SymbolGraph.Symbol.DeclarationFragments.mixinKey] as? SymbolGraph.Symbol.DeclarationFragments { let availability = mixins[SymbolGraph.Symbol.Availability.mixinKey] as? SymbolGraph.Symbol.Availability try mergeDeclaration(mergingDeclaration: mergingDeclaration, identifier: unifiedSymbol.uniqueIdentifier, symbolAvailability: availability, selector: selector) } } } } extension Dictionary where Key == String, Value == Mixin { func getValueIfPresent<T>(for mixinType: T.Type) -> T? where T: Mixin { return self[mixinType.mixinKey] as? T } } // MARK: Accessors for the first variant of symbol properties. extension Symbol { /// The kind of the first variant of this symbol, such as protocol or variable. public var kind: SymbolGraph.Symbol.Kind { kindVariants.firstValue! } /// The title of the first variant of this symbol, usually a simplified version of the declaration. public var title: String { titleVariants.firstValue! } /// The simplified version of the first variant of this symbol's declaration to use inside groups that may contain multiple links. public var subHeading: [SymbolGraph.Symbol.DeclarationFragments.Fragment]? { subHeadingVariants.firstValue } /// The simplified version of the first variant of this symbol's declaration to use in navigation UI. public var navigator: [SymbolGraph.Symbol.DeclarationFragments.Fragment]? { navigatorVariants.firstValue } /// The presentation-friendly version of the first variant of the symbol's kind. public var roleHeading: String { roleHeadingVariants.firstValue! } /// The first variant of the symbol's platform, if available. public var platformName: PlatformName? { platformNameVariants.firstValue } /// The presentation-friendly name of the first variant of the symbol's framework. public var moduleName: String { moduleNameVariants.firstValue! } /// Whether the first variant of the symbol is required in its context. public var isRequired: Bool { get { isRequiredVariants.firstValue! } set { isRequiredVariants.firstValue = newValue } } /// The first variant of the symbol's external identifier, if available. public var externalID: String? { get { externalIDVariants.firstValue } set { externalIDVariants.firstValue = nil } } /// The name of the module extension in which the first variant of the symbol is defined, if applicable. public var extendedModule: String? { extendedModuleVariants.firstValue } /// Optional cross-import module names of the first variant of the symbol. public var bystanderModuleNames: [String]? { bystanderModuleNamesVariants.firstValue } /// The first variant of the symbol's deprecation information, if deprecated. public var deprecatedSummary: DeprecatedSection? { get { deprecatedSummaryVariants.firstValue } set { deprecatedSummaryVariants.firstValue = newValue } } /// The first variant of the symbol's declarations. public var declaration: [[PlatformName?]: SymbolGraph.Symbol.DeclarationFragments] { get { declarationVariants.firstValue! } set { declarationVariants.firstValue = newValue } } /// The place where the first variant of the symbol was originally declared in a source file. public var location: SymbolGraph.Symbol.Location? { get { locationVariants.firstValue } set { locationVariants.firstValue = newValue } } /// The first variant of the symbol's availability or conformance constraints. public var constraints: [SymbolGraph.Symbol.Swift.GenericConstraint]? { get { constraintsVariants.firstValue } set { constraintsVariants.firstValue = newValue } } /// The inheritance information for the first variant of the symbol. public var origin: SymbolGraph.Relationship.SourceOrigin? { get { originVariants.firstValue } set { originVariants.firstValue = newValue } } /// The platforms on which the first variant of the symbol is available. /// - note: Updating this property recalculates `isDeprecated`. public var availability: SymbolGraph.Symbol.Availability? { get { availabilityVariants.firstValue } set { availabilityVariants.firstValue = newValue } } /// The presentation-friendly relationships of the first variant of this symbol to other symbols. public var relationships: RelationshipsSection { get { relationshipsVariants.firstValue! } set { relationshipsVariants.firstValue = newValue } } /// The first variant of the symbol's access level, if available. public var accessLevel: String? { get { accessLevelVariants.firstValue } set { accessLevelVariants.firstValue = newValue } } /// An optional discussion for the first variant of the symbol. public var discussion: DiscussionSection? { get { discussionVariants.firstValue } set { discussionVariants.firstValue = newValue } } /// An optional, abstract summary for the first variant of the symbol. public var abstractSection: AbstractSection? { get { abstractSectionVariants.firstValue } set { abstractSectionVariants.firstValue = newValue } } /// The topics task groups for the first variant of the symbol. public var topics: TopicsSection? { get { topicsVariants.firstValue } set { topicsVariants.firstValue = newValue } } /// Any default implementations of the first variant of the symbol, if the symbol is a protocol requirement. public var defaultImplementations: DefaultImplementationsSection { get { defaultImplementationsVariants.firstValue! } set { defaultImplementationsVariants.firstValue = newValue } } /// Any See Also groups of the first variant of the symbol. public var seeAlso: SeeAlsoSection? { get { seeAlsoVariants.firstValue } set { seeAlsoVariants.firstValue = newValue } } /// Any redirect information of the first variant of the symbol, if the symbol has been moved from another location. public var redirects: [Redirect]? { get { redirectsVariants.firstValue } set { redirectsVariants.firstValue = newValue } } /// Any return value information of the first variant of the symbol, if the symbol returns. public var returnsSection: ReturnsSection? { get { returnsSectionVariants.firstValue } set { returnsSectionVariants.firstValue = newValue } } /// Any parameters of the first variant of the symbol, if the symbol accepts parameters. public var parametersSection: ParametersSection? { get { parametersSectionVariants.firstValue } set { parametersSectionVariants.firstValue = newValue } } /// The first variant of the symbol's abstract summary as a single paragraph. public var abstract: Paragraph? { abstractVariants.firstValue } /// Whether the first variant of the symbol is deprecated. public var isDeprecated: Bool { get { isDeprecatedVariants.firstValue! } set { isDeprecatedVariants.firstValue = newValue } } /// Whether the first variant of the symbol is declared as an SPI. public var isSPI: Bool { get { isSPIVariants.firstValue! } set { isSPIVariants.firstValue = newValue } } /// The mixins of the first variant of the symbol. var mixins: [String: Mixin]? { get { mixinsVariants.firstValue } set { mixinsVariants.firstValue = newValue } } /// Any automatically created task groups of the first variant of the symbol. var automaticTaskGroups: [AutomaticTaskGroupSection] { get { automaticTaskGroupsVariants.firstValue! } set { automaticTaskGroupsVariants.firstValue = newValue } } }
48.937956
208
0.709971
d5c9dd9c0d49c6dbceecda9c1b006a827cce901d
48
// // File.swift // Pia // import Foundation
6.857143
17
0.583333
bf827266b13fd13f682ed73f7247bdcfb3264412
1,748
extension PostgreSQLMessage { /// Authentication request returned by the server. enum AuthenticationRequest { /// AuthenticationOk /// Specifies that the authentication was successful. case ok /// AuthenticationCleartextPassword /// Specifies that a clear-text password is required. case plaintext /// AuthenticationMD5Password /// Specifies that an MD5-encrypted password is required. case md5(Data) } } // MARK: String extension PostgreSQLMessage.AuthenticationRequest: CustomStringConvertible { /// See `CustomStringConvertible`. var description: String { switch self { case .ok: return "Ok" case .plaintext: return "CleartextPassword" case .md5(let salt): return "MD5Password(salt: 0x\(salt.hexEncodedString())" } } } // MARK: Parse extension PostgreSQLMessage.AuthenticationRequest { /// Parses an instance of this message type from a byte buffer. static func parse(from buffer: inout ByteBuffer) throws -> PostgreSQLMessage.AuthenticationRequest { guard let type = buffer.readInteger(as: Int32.self) else { throw PostgreSQLError.protocol(reason: "Could not read authentication message type.") } switch type { case 0: return .ok case 3: return .plaintext case 5: guard let salt = buffer.readData(length: 4) else { throw PostgreSQLError.protocol(reason: "Could not parse MD5 salt from authentication message.") } return .md5(salt) default: throw PostgreSQLError.protocol(reason: "Unkonwn authentication request type: \(type).") } } }
33.615385
111
0.641876
677512b24c46600f134153bd81ddb7c001b2c748
384
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing d = [ [ [ [ [ [ [ [ { { { enum b { let f = [ [ [ [ [ [ { for { { { case { { { h = [ { struct A { protocol c { { } protocol c { { } let end = [ { func c{ deinit { { { { { { class A { let a { { if true { class case ,
9.846154
87
0.5625
d9a310d0390bc00cf72ba7f954440a45efc8eb01
10,310
// // Ribbon.swift // Ribbon 🎀 // // Created by Chris Zielinski on 7/19/19. // Copyright © 2019 Big Z Labs. All rights reserved. // #if canImport(UIKit) import UIKit #else import AppKit #endif open class Ribbon: RibbonShim { // MARK: - Type Methods public static func load(from bundle: Bundle, target: AnyObject?, delegate: RibbonDelegate? = nil) throws -> Ribbon { return Ribbon(configuration: try RibbonConfiguration.readFromBundle(bundle, delegate: delegate), target: target, delegate: delegate) } public static func loadFromMainBundle(target: AnyObject?, delegate: RibbonDelegate? = nil) throws -> Ribbon { return try load(from: .main, target: target, delegate: delegate) } // MARK: - Stored Properties // MARK: Type #if canImport(UIKit) private static let registerAppearance: Void = { let lightRibbonProxy: Ribbon let lightButtonProxy: RibbonButton if #available(iOS 12.0, *) { lightRibbonProxy = Ribbon.appearance(for: UITraitCollection(userInterfaceStyle: .light)) lightButtonProxy = RibbonButton.appearance(for: UITraitCollection(userInterfaceStyle: .light)) } else { lightRibbonProxy = Ribbon.appearance() lightButtonProxy = RibbonButton.appearance() } lightRibbonProxy.setBorderColor(RibbonColor.lightRibbonBorder) lightButtonProxy.backgroundColor = RibbonColor.lightButtonBackground lightButtonProxy.setBorderColor(RibbonColor.lightButtonBorder) lightButtonProxy.tintColor = RibbonColor.lightButtonTint lightButtonProxy.setTitleColor(RibbonColor.lightButtonTint, for: .normal) lightButtonProxy.setTitleColor(RibbonColor.lightButtonHighlightedTitle, for: .highlighted) if #available(iOS 12.0, *) { let darkRibbonProxy = Ribbon.appearance(for: UITraitCollection(userInterfaceStyle: .dark)) darkRibbonProxy.setBorderColor(RibbonColor.darkRibbonBorder) let darkButtonProxy = RibbonButton.appearance(for: UITraitCollection(userInterfaceStyle: .dark)) darkButtonProxy.backgroundColor = RibbonColor.darkButtonBackground darkButtonProxy.setBorderColor(RibbonColor.darkButtonBorder) darkButtonProxy.tintColor = RibbonColor.darkButtonTint darkButtonProxy.setTitleColor(RibbonColor.darkButtonTint, for: .normal) darkButtonProxy.setTitleColor(RibbonColor.darkButtonHighlightedTitle, for: .highlighted) } }() #endif // MARK: Weak References public weak var delegate: RibbonDelegate? public weak var target: AnyObject? // MARK: Constant public let items: [RibbonItem] // MARK: Variable public private(set) var configuration: RibbonConfiguration? // MARK: Lazy #if canImport(AppKit) public lazy var toolbar: NSToolbar = NSToolbar(ribbon: self) #endif // MARK: - Computed Properties // MARK: Private #if canImport(UIKit) private var visualEffectContentView: UIView? { return (toolbarView as? UIVisualEffectView)?.contentView } #endif // MARK: Public #if canImport(AppKit) public var menuItems: [NSMenuItem] { return items.map { $0.initializeMenuItemIfNeeded() return $0.menuItem! } } #endif // MARK: Open #if canImport(UIKit) open var toolbarView: UIView? { return subviews.first } open var scrollView: UIScrollView? { return visualEffectContentView?.subviews.first as? UIScrollView } open var stackView: UIStackView? { return scrollView?.viewWithTag((\Ribbon.stackView).hashValue) as? UIStackView } open var topBorder: CALayer? { return visualEffectContentView?.layer.sublayer(named: String((\Ribbon.topBorder).hashValue)) } open var bottomBorder: CALayer? { return visualEffectContentView?.layer.sublayer(named: String((\Ribbon.bottomBorder).hashValue)) } #endif // MARK: - Initializers // MARK: Designated public init(items: [RibbonItem], target: AnyObject?, delegate: RibbonDelegate? = nil) { self.items = items self.target = target self.delegate = delegate #if canImport(UIKit) Ribbon.registerAppearance super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 40)) autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(createInputAccessoryView()) if let stackView = stackView, let scrollView = scrollView { NSLayoutConstraint.activate([ stackView.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor), stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor) ]) } setNeedsLayout() #else super.init() #endif items.forEach { $0.ribbon = self } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Convenience public convenience init(configuration: RibbonConfiguration, target: AnyObject?, delegate: RibbonDelegate? = nil) { self.init(items: configuration.items, target: target, delegate: delegate) self.configuration = configuration } // MARK: - Overridden Methods #if canImport(UIKit) open override func layoutSubviews() { if let stackView = stackView { scrollView?.contentSize.width = stackView.arrangedSubviews.reduce(0) { $0 + $1.bounds.width + 8 } } topBorder?.frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 0.5)) bottomBorder?.frame = CGRect(origin: CGPoint(x: 0, y: bounds.maxY - 1), size: CGSize(width: bounds.width, height: 0.5)) super.layoutSubviews() } #endif // MARK: - Item Retrieval Methods open func item(withIdentifier identifier: RibbonItem.Identifier) -> RibbonItem? { return items.first { $0.identifier == identifier } } // MARK: - Subview Creation Methods #if canImport(UIKit) open func createInputAccessoryView() -> UIView { let topBorder = CALayer() topBorder.name = String((\Ribbon.topBorder).hashValue) let bottomBorder = CALayer() bottomBorder.name = String((\Ribbon.bottomBorder).hashValue) let visualEffectView = UIVisualEffectView(frame: bounds) visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.effect = UIBlurEffect(style: .prominent) visualEffectView.contentView.layer.addSublayer(topBorder) visualEffectView.contentView.layer.addSublayer(bottomBorder) visualEffectView.contentView.addSubview(createScrollView()) return visualEffectView } open func createScrollView() -> UIScrollView { let scrollView = UIScrollView(frame: bounds) scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.backgroundColor = .clear scrollView.showsHorizontalScrollIndicator = false scrollView.alwaysBounceHorizontal = true scrollView.contentInset = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 4) scrollView.addSubview(createStackView()) return scrollView } open func createStackView() -> UIStackView { let stackView = UIStackView(arrangedSubviews: items.reduce([], { $0 + $1.controls })) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.alignment = .center stackView.axis = .horizontal stackView.spacing = 8 stackView.tag = (\Ribbon.stackView).hashValue return stackView } #endif // MARK: - Appearance Customization Methods #if canImport(UIKit) @available(iOS, introduced: 12.0, obsoleted: 13.0) open func setUserInterfaceStyle(_ style: UIUserInterfaceStyle) { let proxy = Ribbon.appearance(for: UITraitCollection(userInterfaceStyle: style)) if let borderColor = proxy.borderColor() { setBorderColor(borderColor) } if style == .dark { (toolbarView as? UIVisualEffectView)?.effect = UIBlurEffect(style: .dark) } else { (toolbarView as? UIVisualEffectView)?.effect = UIBlurEffect(style: .prominent) } items.forEach { $0.setUserInterfaceStyle(style) } } #endif } // MARK: - UIAppearanceContainer Protocol #if canImport(UIKit) extension Ribbon { @objc public dynamic func borderColor() -> UIColor? { guard let cgColor = topBorder?.backgroundColor else { return nil } return UIColor(cgColor: cgColor) } @objc public dynamic func setBorderColor(_ color: UIColor) { topBorder?.backgroundColor = color.cgColor bottomBorder?.backgroundColor = color.cgColor } } #endif // MARK: - UIInputViewAudioFeedback Protocol #if canImport(UIKit) extension Ribbon: UIInputViewAudioFeedback { open var enableInputClicksWhenVisible: Bool { return true } } #endif // MARK: - NSToolbarDelegate Protocol #if canImport(AppKit) extension Ribbon: NSToolbarDelegate { open func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return items.compactMap({ $0.identifier }) + [.flexibleSpace, .space] } open func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { return items.first(where: { $0.identifier == itemIdentifier })?.toolbarItem } open func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return configuration?.toolbar?.defaultItems?.map({ NSToolbarItem.Identifier($0) }) ?? [] } open func toolbarWillAddItem(_ notification: Notification) { NSApp.mainWindow?.layoutIfNeeded() } open func toolbarDidRemoveItem(_ notification: Notification) { NSApp.mainWindow?.layoutIfNeeded() } } #endif
31.723077
120
0.664016
fe8c11d765eda4fefe274f4e303bfc672f507c8c
20,641
// // Created by Tapash Majumder on 3/19/20. // Copyright © 2020 Iterable. All rights reserved. // import Foundation import IterableSDK @objc(ReactIterableAPI) class ReactIterableAPI: RCTEventEmitter { @objc static override func moduleName() -> String! { return "RNIterableAPI" } override var methodQueue: DispatchQueue! { _methodQueue } @objc override static func requiresMainQueueSetup() -> Bool { false } enum EventName: String, CaseIterable { case handleUrlCalled case handleCustomActionCalled case handleInAppCalled case handleAuthCalled } override func supportedEvents() -> [String]! { var result = [String]() EventName.allCases.forEach { result.append($0.rawValue) } return result } override func startObserving() { ITBInfo() shouldEmit = true } override func stopObserving() { ITBInfo() shouldEmit = false } @objc(initializeWithApiKey:config:version:resolver:rejecter:) func initialize(apiKey: String, config configDict: [AnyHashable: Any], version: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { ITBInfo() initialize(withApiKey: apiKey, config: configDict, version: version, resolver: resolver, rejecter: rejecter) } @objc(initialize2WithApiKey:config:apiEndPointOverride:version:resolver:rejecter:) func initialize2(apiKey: String, config configDict: [AnyHashable: Any], version: String, apiEndPointOverride: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { ITBInfo() initialize(withApiKey: apiKey, config: configDict, version: version, apiEndPointOverride: apiEndPointOverride, resolver: resolver, rejecter: rejecter) } @objc(setEmail:) func set(email: String?) { ITBInfo() IterableAPI.email = email } @objc(getEmail:rejecter:) func getEmail(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.email) } @objc(setUserId:) func set(userId: String?) { ITBInfo() IterableAPI.userId = userId } @objc(getUserId:rejecter:) func getUserId(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.userId) } @objc(setInAppShowResponse:) func set(inAppShowResponse number: NSNumber) { ITBInfo() self.inAppShowResponse = InAppShowResponse.from(number: number) inAppHandlerSemaphore.signal() } @objc(disableDeviceForCurrentUser) func disableDeviceForCurrentUser() { ITBInfo() IterableAPI.disableDeviceForCurrentUser() } @objc(getLastPushPayload:rejecter:) func getLastPushPayload(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.lastPushPayload) } @objc(getAttributionInfo:rejecter:) func getAttributionInfo(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.attributionInfo.map(SerializationUtil.encodableToDictionary)) } @objc(setAttributionInfo:) func set(attributionInfo dict: [AnyHashable: Any]?) { ITBInfo() guard let dict = dict else { IterableAPI.attributionInfo = nil return } IterableAPI.attributionInfo = SerializationUtil.dictionaryToDecodable(dict: dict) } @objc(trackPushOpenWithCampaignId:templateId:messageId:appAlreadyRunning:dataFields:) func trackPushOpen(campaignId: NSNumber, templateId: NSNumber?, messageId: String, appAlreadyRunning: Bool, dataFields: [AnyHashable: Any]?) { ITBInfo() IterableAPI.track(pushOpen: campaignId, templateId: templateId, messageId: messageId, appAlreadyRunning: appAlreadyRunning, dataFields: dataFields) } @objc(updateCart:) func updateCart(items: [[AnyHashable: Any]]) { ITBInfo() IterableAPI.updateCart(items: items.compactMap(CommerceItem.from(dict:))) } @objc(trackPurchase:items:dataFields:) func trackPurchase(total: NSNumber, items: [[AnyHashable: Any]], dataFields: [AnyHashable: Any]?) { ITBInfo() IterableAPI.track(purchase: total, items: items.compactMap(CommerceItem.from(dict:)), dataFields: dataFields) } @objc(trackInAppOpen:location:) func trackInAppOpen(messageId: String, location locationNumber: NSNumber) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } IterableAPI.track(inAppOpen: message, location: InAppLocation.from(number: locationNumber)) } @objc(trackInAppClick:location:clickedUrl:) func trackInAppClick(messageId: String, location locationNumber: NSNumber, clickedUrl: String) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } IterableAPI.track(inAppClick: message, location: InAppLocation.from(number: locationNumber), clickedUrl: clickedUrl) } @objc(trackInAppClose:location:source:clickedUrl:) func trackInAppClose(messageId: String, location locationNumber: NSNumber, source sourceNumber: NSNumber, clickedUrl: String) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } if let inAppCloseSource = InAppCloseSource.from(number: sourceNumber) { IterableAPI.track(inAppClose: message, location: InAppLocation.from(number: locationNumber), source: inAppCloseSource, clickedUrl: clickedUrl) } else { IterableAPI.track(inAppClose: message, location: InAppLocation.from(number: locationNumber), clickedUrl: clickedUrl) } } @objc(inAppConsume:location:source:) func inAppConsume(messageId: String, location locationNumber: NSNumber, source sourceNumber: NSNumber) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } if let inAppDeleteSource = InAppDeleteSource.from(number: sourceNumber) { IterableAPI.inAppConsume(message: message, location: InAppLocation.from(number: locationNumber), source: inAppDeleteSource) } else { IterableAPI.inAppConsume(message: message, location: InAppLocation.from(number: locationNumber)) } } @objc(getHtmlInAppContentForMessage:resolver:rejecter:) func getHtmlInAppContent(messageId: String, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") rejecter("", "Could not find message with id: \(messageId)", nil) return } guard let content = message.content as? IterableHtmlInAppContent else { ITBError("Could not parse message content as HTML") rejecter("", "Could not parse message content as HTML", nil) return } resolver(content.toDict()) } @objc(trackEvent:dataFields:) func trackEvent(name: String, dataFields: [AnyHashable: Any]?) { ITBInfo() IterableAPI.track(event: name, dataFields: dataFields) } @objc(updateUser:mergeNestedObjects:) func updateUser(dataFields: [AnyHashable: Any], mergeNestedObjects: Bool) { ITBInfo() IterableAPI.updateUser(dataFields, mergeNestedObjects: mergeNestedObjects) } @objc(updateEmail:) func updateEmail(email: String) { ITBInfo() IterableAPI.updateEmail(email, onSuccess: nil, onFailure: nil) } @objc(handleAppLink:resolver:rejecter:) func handle(appLink: String, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() if let url = URL(string: appLink) { resolver(IterableAPI.handle(universalLink: url)) } else { rejecter("", "invalid URL", nil) } } // MARK: In-App Manager methods @objc(getInAppMessages:rejecter:) func getInAppMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.inAppManager.getMessages().map{ $0.toDict() }) } @objc(getInboxMessages:rejecter:) func getInboxMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.inAppManager.getInboxMessages().map{ $0.toDict() }) } @objc(getUnreadInboxMessagesCount:rejecter:) func getUnreadInboxMessagesCount(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() resolver(IterableAPI.inAppManager.getUnreadInboxMessagesCount()) } @objc(showMessage:consume:resolver:rejecter:) func show(messageId: String, consume: Bool, resolver: @escaping RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } IterableAPI.inAppManager.show(message: message, consume: consume) { (url) in resolver(url.map({$0.absoluteString})) } } @objc(removeMessage:location:source:) func remove(messageId: String, location locationNumber: NSNumber, source sourceNumber: NSNumber) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } if let inAppDeleteSource = InAppDeleteSource.from(number: sourceNumber) { IterableAPI.inAppManager.remove(message: message, location: InAppLocation.from(number: locationNumber), source: inAppDeleteSource) } else { IterableAPI.inAppManager.remove(message: message, location: InAppLocation.from(number: locationNumber)) } } @objc(updateSubscriptions:unsubscribedChannelIds:unsubscribedMessageTypeIds:subscribedMessageTypeIds:campaignId:templateId:) func updateSubscriptions(emailListIds: [NSNumber]?, unsubscribedChannelIds: [NSNumber]?, unsubscribedMessageTypeIds: [NSNumber]?, subscribedMessageTypeIds: [NSNumber]?, campaignId: NSNumber, templateId: NSNumber) { ITBInfo() let finalCampaignId: NSNumber? = campaignId.intValue <= 0 ? nil : campaignId let finalTemplateId: NSNumber? = templateId.intValue <= 0 ? nil : templateId IterableAPI.updateSubscriptions(emailListIds, unsubscribedChannelIds: unsubscribedChannelIds, unsubscribedMessageTypeIds: unsubscribedMessageTypeIds, subscribedMessageTypeIds: subscribedMessageTypeIds, campaignId: finalCampaignId, templateId: finalTemplateId) } @objc(setReadForMessage:read:) func setRead(for messageId: String, read: Bool) { ITBInfo() guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else { ITBError("Could not find message with id: \(messageId)") return } IterableAPI.inAppManager.set(read: read, forMessage: message) } @objc(setAutoDisplayPaused:) func set(autoDisplayPaused: Bool) { ITBInfo() DispatchQueue.main.async { IterableAPI.inAppManager.isAutoDisplayPaused = autoDisplayPaused } } @objc(passAlongAuthToken:) func passAlong(authToken: String?) { ITBInfo() passedAuthToken = authToken authHandlerSemaphore.signal() } // MARK: Private private var shouldEmit = false private let _methodQueue = DispatchQueue(label: String(describing: ReactIterableAPI.self)) // Handling in-app delegate private var inAppShowResponse = InAppShowResponse.show private var inAppHandlerSemaphore = DispatchSemaphore(value: 0) private var passedAuthToken: String? private var authHandlerSemaphore = DispatchSemaphore(value: 0) private func initialize(withApiKey apiKey: String, config configDict: [AnyHashable: Any], version: String, apiEndPointOverride: String? = nil, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { ITBInfo() let launchOptions = createLaunchOptions() let iterableConfig = IterableConfig.from(dict: configDict) if let urlHandlerPresent = configDict["urlHandlerPresent"] as? Bool, urlHandlerPresent == true { iterableConfig.urlDelegate = self } if let customActionHandlerPresent = configDict["customActionHandlerPresent"] as? Bool, customActionHandlerPresent == true { iterableConfig.customActionDelegate = self } if let inAppHandlerPresent = configDict["inAppHandlerPresent"] as? Bool, inAppHandlerPresent == true { iterableConfig.inAppDelegate = self } if let authHandlerPresent = configDict["authHandlerPresent"] as? Bool, authHandlerPresent { iterableConfig.authDelegate = self } DispatchQueue.main.async { IterableAPI.initialize2(apiKey: apiKey, launchOptions: launchOptions, config: iterableConfig, apiEndPointOverride: apiEndPointOverride) { result in resolver(result) } IterableAPI.setDeviceAttribute(name: "reactNativeSDKVersion", value: version) } } private func createLaunchOptions() -> [UIApplication.LaunchOptionsKey: Any]? { guard let bridge = bridge else { return nil } return ReactIterableAPI.createLaunchOptions(bridgeLaunchOptions: bridge.launchOptions) } private static func createLaunchOptions(bridgeLaunchOptions: [AnyHashable: Any]?) -> [UIApplication.LaunchOptionsKey: Any]? { guard let bridgeLaunchOptions = bridgeLaunchOptions, let remoteNotification = bridgeLaunchOptions[UIApplication.LaunchOptionsKey.remoteNotification.rawValue] else { return nil } var result = [UIApplication.LaunchOptionsKey: Any]() result[UIApplication.LaunchOptionsKey.remoteNotification] = remoteNotification return result } } extension ReactIterableAPI: IterableURLDelegate { func handle(iterableURL url: URL, inContext context: IterableActionContext) -> Bool { ITBInfo() guard shouldEmit else { return false } let contextDict = ReactIterableAPI.contextToDictionary(context: context) sendEvent(withName: EventName.handleUrlCalled.rawValue, body: ["url": url.absoluteString, "context": contextDict]) return true } private static func contextToDictionary(context: IterableActionContext) -> [AnyHashable: Any] { var result = [AnyHashable: Any]() let actionDict = actionToDictionary(action: context.action) result["action"] = actionDict result["source"] = context.source.rawValue return result } private static func actionToDictionary(action: IterableAction) -> [AnyHashable: Any] { var actionDict = [AnyHashable: Any]() actionDict["type"] = action.type if let data = action.data { actionDict["data"] = data } if let userInput = action.userInput { actionDict["userInput"] = userInput } return actionDict } } extension ReactIterableAPI: IterableCustomActionDelegate { func handle(iterableCustomAction action: IterableAction, inContext context: IterableActionContext) -> Bool { ITBInfo() let actionDict = ReactIterableAPI.actionToDictionary(action: action) let contextDict = ReactIterableAPI.contextToDictionary(context: context) sendEvent(withName: EventName.handleCustomActionCalled.rawValue, body: ["action": actionDict, "context": contextDict]) return true } } extension ReactIterableAPI: IterableInAppDelegate { func onNew(message: IterableInAppMessage) -> InAppShowResponse { ITBInfo() guard shouldEmit else { return .show } let messageDict = message.toDict() sendEvent(withName: EventName.handleInAppCalled.rawValue, body: messageDict) let timeoutResult = inAppHandlerSemaphore.wait(timeout: .now() + 2.0) if timeoutResult == .success { ITBInfo("inAppShowResponse: \(inAppShowResponse == .show)") return inAppShowResponse } else { ITBInfo("timed out") return .show } } } extension ReactIterableAPI: IterableAuthDelegate { func onAuthTokenRequested(completion: @escaping AuthTokenRetrievalHandler) { ITBInfo() DispatchQueue.global(qos: .userInitiated).async { self.sendEvent(withName: EventName.handleAuthCalled.rawValue, body: nil) let authTokenRetrievalResult = self.authHandlerSemaphore.wait(timeout: .now() + 30.0) if authTokenRetrievalResult == .success { ITBInfo("authTokenRetrieval successful") DispatchQueue.main.async { completion(self.passedAuthToken) } } else { ITBInfo("authTokenRetrieval timed out") DispatchQueue.main.async { completion(nil) } } } } }
35.044143
131
0.593624
5613515ccccec0f4de6001f945341dab365aac13
1,689
// // DataModel.swift // LabTestApp // // Created by Anna Zamora on 22/02/2018. // Copyright © 2018 Anna Zamora. All rights reserved. // import Foundation import SwiftyJSON class DataModel: NSObject { var categoriesDictionary = [String : ArticleCategory]() var selectedCategoryId: String = "" func articlesFromJSON(jsonObject: JSON) -> [Article] { guard let array = jsonObject.array else { log.warning("invalid JSON format") return [] } var tmpArticles: [Article] = [] for item in array { if let article = Article.fromJSON(jsonObject: item) { tmpArticles.append(article) } } return tmpArticles } func categoriesFromJSON(jsonObject: JSON) -> [ArticleCategory] { guard let array = jsonObject.array else { log.warning("invalid JSON format") return [] } var tmpCategories: [ArticleCategory] = [] for item in array { if let category = ArticleCategory.fromJSON(jsonObject: item) { tmpCategories.append(category) } } return tmpCategories } func setCategories(categoriesArray: [ArticleCategory]) { for item in categoriesArray { categoriesDictionary[item.id] = item } if let firstCategory = categoriesArray.first { selectedCategoryId = firstCategory.id } } func categories() -> [ArticleCategory] { let categoriesArray = categoriesDictionary.map({ $0.value }) return categoriesArray.sorted(by: {$0.title < $1.title}) } }
27.241935
74
0.584369
c1caa202d901b8a86981080fe97b0ab7d448dc92
21,294
/* Copyright 2015-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import CatalogByConvention import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialFlexibleHeader import MaterialComponents.MaterialLibraryInfo import MaterialComponents.MaterialShadowElevations import MaterialComponents.MaterialShadowLayer import MaterialComponents.MaterialThemes import MaterialComponents.MaterialTypography import MaterialComponents.MaterialIcons_ic_chevron_right import MaterialComponents.MaterialKeyboardWatcher import MaterialComponents.MaterialColorScheme import MaterialComponents.MaterialContainerScheme class MDCDragonsController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIGestureRecognizerDelegate { let containerScheme: MDCContainerScheming = { let scheme = MDCContainerScheme() scheme.colorScheme = MDCSemanticColorScheme(defaults: .material201907) scheme.typographyScheme = MDCTypographyScheme(defaults: .material201902) scheme.shapeScheme = MDCShapeScheme() return scheme }() fileprivate struct Constants { static let headerScrollThreshold: CGFloat = 50 static let headerViewMaxHeight: CGFloat = 113 static let headerViewMinHeight: CGFloat = 53 } fileprivate var cellsBySection: [[DragonCell]] fileprivate var nodes: [CBCNode] fileprivate var searched: [DragonCell]! fileprivate var results: [DragonCell]! fileprivate var tableView: UITableView! fileprivate var isSearchActive = false fileprivate var headerViewController = MDCFlexibleHeaderViewController() private let keyboardWatcher = MDCKeyboardWatcher() var headerView: HeaderView! enum Section { case main } @available(iOS 14.0, *) private(set) lazy var dataSource: UICollectionViewDiffableDataSource<Section, CBCNode>! = nil var collectionView: UICollectionView! = nil init(node: CBCNode) { let filteredPresentable = node.children.filter { return $0.isPresentable() } let filteredDragons = Set(node.children).subtracting(filteredPresentable) cellsBySection = [ filteredDragons.map { DragonCell(node: $0) }, filteredPresentable.map { DragonCell(node: $0) }, ] cellsBySection = cellsBySection.map { $0.sorted { $0.node.title < $1.node.title } } nodes = node.children super.init(nibName: nil, bundle: nil) results = getLeafNodes(node: node) searched = results setUpKeyboardWatcher() } deinit { NotificationCenter.default.removeObserver(self) } func getLeafNodes(node: CBCNode) -> [DragonCell] { if node.children.count == 0 { return [DragonCell(node: node)] } var cells = [DragonCell]() for child in node.children { cells += getLeafNodes(node: child) } return cells } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Material Dragons" addChild(headerViewController) headerViewController.headerView.minMaxHeightIncludesSafeArea = false headerViewController.headerView.maximumHeight = Constants.headerViewMaxHeight headerViewController.headerView.minimumHeight = Constants.headerViewMinHeight view.backgroundColor = containerScheme.colorScheme.backgroundColor if #available(iOS 14.0, *) { #if compiler(>=5.3) configureCollectionView() configureDataSource() #endif } else { tableView = UITableView(frame: self.view.bounds, style: .grouped) tableView.register( MDCDragonsTableViewCell.self, forCellReuseIdentifier: "MDCDragonsTableViewCell") tableView.backgroundColor = containerScheme.colorScheme.backgroundColor tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ tableView.leftAnchor.constraint(equalTo: guide.leftAnchor), tableView.rightAnchor.constraint(equalTo: guide.rightAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), ]) tableView.contentInsetAdjustmentBehavior = .always } setupHeaderView() let tapgesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tapgesture.delegate = self view.addGestureRecognizer(tapgesture) } func preiOS11Constraints() { tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } func setupHeaderView() { headerView = HeaderView(frame: headerViewController.headerView.bounds) headerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] headerView.title.text = title! headerView.searchBar.delegate = self headerViewController.headerView.addSubview(headerView) headerViewController.headerView.forwardTouchEvents(for: headerView) headerViewController.headerView.backgroundColor = containerScheme.colorScheme.primaryColor if #available(iOS 14.0, *) { headerViewController.headerView.trackingScrollView = collectionView } else { headerViewController.headerView.trackingScrollView = tableView } view.addSubview(headerViewController.view) headerViewController.didMove(toParent: self) } func adjustLogoForScrollView(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.y let inset = scrollView.contentInset.top let relativeOffset = inset + offset headerView.imageView.alpha = 1 - (relativeOffset / Constants.headerScrollThreshold) headerView.title.alpha = 1 - (relativeOffset / Constants.headerScrollThreshold) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override var childForStatusBarStyle: UIViewController? { return headerViewController } override var childForStatusBarHidden: UIViewController? { return headerViewController } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return isSearchActive ? 1 : 2 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return isSearchActive ? "Results" : (section == 0 ? "Dragons" : "Catalog") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearchActive ? searched.count : cellsBySection[section].count } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell( withIdentifier: "MDCDragonsTableViewCell", for: indexPath) as? MDCDragonsTableViewCell else { return UITableViewCell() } let nodeData = isSearchActive ? searched[indexPath.item] : cellsBySection[indexPath.section][indexPath.row] let componentName = nodeData.node.title cell.textLabel?.text = componentName cell.textLabel?.textColor = containerScheme.colorScheme.onBackgroundColor cell.tintColor = containerScheme.colorScheme.onBackgroundColor let node = nodeData.node if !node.isExample() && !isSearchActive { if nodeData.expanded { cell.accessoryView = cell.expandedAccessoryView cell.textLabel?.textColor = containerScheme.colorScheme.primaryColor } else { cell.accessoryView = cell.collapsedAccessoryView cell.textLabel?.textColor = containerScheme.colorScheme.onBackgroundColor } } else { cell.accessoryView = nil if indexPath.section != 0 { cell.textLabel?.textColor = containerScheme.colorScheme.onBackgroundColor if let text = cell.textLabel?.text { cell.textLabel?.text = " " + text } } else if isSearchActive { cell.textLabel?.textColor = containerScheme.colorScheme.onBackgroundColor } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) as? MDCDragonsTableViewCell else { return } let nodeData = isSearchActive ? searched[indexPath.item] : cellsBySection[indexPath.section][indexPath.row] if nodeData.node.isExample() || isSearchActive { setupTransition(nodeData: nodeData) } else if !isSearchActive { self.tableView.beginUpdates() if nodeData.expanded { collapseCells(at: indexPath) cell.accessoryView = cell.collapsedAccessoryView cell.textLabel?.textColor = containerScheme.colorScheme.onBackgroundColor } else { expandCells(at: indexPath) cell.accessoryView = cell.expandedAccessoryView cell.textLabel?.textColor = containerScheme.colorScheme.primaryColor } self.tableView.endUpdates() nodeData.expanded = !nodeData.expanded } } func setupTransition(nodeData: DragonCell) { var vc = nodeData.node.createExampleViewController() let containerSchemeSel = NSSelectorFromString("setContainerScheme:") if vc.responds(to: containerSchemeSel) { vc.perform(containerSchemeSel, with: containerScheme) } if !vc.responds(to: NSSelectorFromString("catalogShouldHideNavigation")) { let container = MDCAppBarContainerViewController(contentViewController: vc) container.appBar.headerViewController.headerView.backgroundColor = headerViewController.headerView.backgroundColor container.appBar.navigationBar.tintColor = .white container.appBar.navigationBar.titleTextAttributes = [ .foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 16), ] container.isTopLayoutGuideAdjustmentEnabled = true vc.title = nodeData.node.title let headerView = container.appBar.headerViewController.headerView if let collectionVC = vc as? UICollectionViewController { headerView.trackingScrollView = collectionVC.collectionView } else if let scrollView = vc.view as? UIScrollView { headerView.trackingScrollView = scrollView } vc = container } self.navigationController?.pushViewController(vc, animated: true) } } // UIScrollViewDelegate extension MDCDragonsController { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == headerViewController.headerView.trackingScrollView { self.headerViewController.headerView.trackingScrollDidScroll() self.adjustLogoForScrollView(scrollView) } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == headerViewController.headerView.trackingScrollView { self.headerViewController.headerView.trackingScrollDidEndDecelerating() } } func scrollViewWillEndDragging( _ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint> ) { let headerView = headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollWillEndDragging( withVelocity: velocity, targetContentOffset: targetContentOffset) } } } // UISearchBarDelegate extension MDCDragonsController { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { isSearchActive = false searched = results } else { isSearchActive = true searched = results.filter { return $0.node.title.range(of: searchText, options: .caseInsensitive) != nil } } // load our initial data refreshTable() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searched = results refreshTable() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.endEditing(true) } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { isSearchActive = true refreshTable() } @objc func dismissKeyboard() { self.view.endEditing(true) isSearchActive = false } func refreshTable() { if #available(iOS 14.0, *) { #if compiler(>=5.3) applySnapshot() #endif } else { tableView.reloadData() } } @objc(gestureRecognizer:shouldReceiveTouch:) func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if gestureRecognizer is UITapGestureRecognizer { if #available(iOS 14.0, *) { let location = touch.location(in: collectionView) return (collectionView.indexPathForItem(at: location) == nil) } else { let location = touch.location(in: tableView) return (tableView.indexPathForRow(at: location) == nil) } } return true } } extension MDCDragonsController { func collapseCells(at indexPath: IndexPath) { let upperCount = cellsBySection[indexPath.section][indexPath.row].node.children.count let indexPaths = (indexPath.row + 1..<indexPath.row + 1 + upperCount).map { IndexPath(row: $0, section: indexPath.section) } tableView.deleteRows(at: indexPaths, with: .automatic) cellsBySection[indexPath.section].removeSubrange( (indexPath.row + 1..<indexPath.row + 1 + upperCount)) } func expandCells(at indexPath: IndexPath) { let nodeChildren = cellsBySection[indexPath.section][indexPath.row].node.children let upperCount = nodeChildren.count let indexPaths = (indexPath.row + 1..<indexPath.row + 1 + upperCount).map { IndexPath(row: $0, section: indexPath.section) } tableView.insertRows(at: indexPaths, with: .automatic) cellsBySection[indexPath.section].insert( contentsOf: nodeChildren.map { DragonCell(node: $0) }, at: indexPath.row + 1) } } extension MDCDragonsController { func setUpKeyboardWatcher() { NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(notification:)), name: .MDCKeyboardWatcherKeyboardWillShow, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(notification:)), name: .MDCKeyboardWatcherKeyboardWillHide, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillChangeFrame(notification:)), name: .MDCKeyboardWatcherKeyboardWillChangeFrame, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } updateScrollViewWithKeyboardNotificationUserInfo(userInfo: userInfo) } @objc func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } updateScrollViewWithKeyboardNotificationUserInfo(userInfo: userInfo) } @objc func keyboardWillChangeFrame(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } updateScrollViewWithKeyboardNotificationUserInfo(userInfo: userInfo) } func updateScrollViewWithKeyboardNotificationUserInfo(userInfo: [AnyHashable: Any]) { if #available(iOS 14.0, *) { } else { guard let endFrame = userInfo[AnyHashable("UIKeyboardFrameEndUserInfoKey")] as? CGRect else { return } let endKeyboardFrameOriginInWindow = view.convert(endFrame.origin, from: nil) let tableViewMaxY = tableView.frame.maxY let baseInset = tableViewMaxY - endKeyboardFrameOriginInWindow.y let scrollIndicatorInset = baseInset var contentInset = baseInset if endKeyboardFrameOriginInWindow.y < tableViewMaxY { contentInset -= view.safeAreaInsets.bottom } tableView.contentInset.bottom = contentInset tableView.scrollIndicatorInsets.bottom = scrollIndicatorInset } } #if compiler(>=5.3) @available(iOS 14.0, *) func configureCollectionView() { let collectionView = UICollectionView( frame: view.bounds, collectionViewLayout: generateLayout()) view.addSubview(collectionView) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = containerScheme.colorScheme.backgroundColor self.collectionView = collectionView collectionView.delegate = self } @available(iOS 14.0, *) func configureDataSource() { let containerCellRegistration = UICollectionView.CellRegistration< UICollectionViewListCell, CBCNode > { (cell, indexPath, menuItem) in // Populate the cell with our item description. var contentConfiguration = cell.defaultContentConfiguration() contentConfiguration.text = menuItem.title contentConfiguration.textProperties.color = self.containerScheme.colorScheme.onBackgroundColor cell.contentConfiguration = contentConfiguration let disclosureOptions = UICellAccessory.OutlineDisclosureOptions(style: .header) cell.accessories = [.outlineDisclosure(options: disclosureOptions)] cell.backgroundConfiguration = UIBackgroundConfiguration.clear() } let cellRegistration = UICollectionView.CellRegistration< UICollectionViewListCell, CBCNode > { cell, indexPath, menuItem in // Populate the cell with our item description. var contentConfiguration = cell.defaultContentConfiguration() contentConfiguration.text = menuItem.title contentConfiguration.textProperties.color = self.containerScheme.colorScheme.onBackgroundColor cell.contentConfiguration = contentConfiguration cell.backgroundConfiguration = UIBackgroundConfiguration.clear() } dataSource = UICollectionViewDiffableDataSource<Section, CBCNode>(collectionView: collectionView) { ( collectionView: UICollectionView, indexPath: IndexPath, item: CBCNode ) -> UICollectionViewCell? in // Return the cell. if item.children.isEmpty { return collectionView.dequeueConfiguredReusableCell( using: cellRegistration, for: indexPath, item: item) } else { return collectionView.dequeueConfiguredReusableCell( using: containerCellRegistration, for: indexPath, item: item) } } // load our initial data applySnapshot(animatingDifferences: false) } @available(iOS 14.0, *) func generateLayout() -> UICollectionViewLayout { let listConfiguration = UICollectionLayoutListConfiguration(appearance: .plain) let layout = UICollectionViewCompositionalLayout.list(using: listConfiguration) return layout } @available(iOS 14.0, *) func applySnapshot(animatingDifferences: Bool = true) { let sectionSnapshot = createSectionSnapshot(section: isSearchActive ? searched.map { $0.node } : nodes) self.dataSource.apply(sectionSnapshot, to: .main, animatingDifferences: animatingDifferences) } @available(iOS 14.0, *) func createSectionSnapshot(section: [CBCNode]) -> NSDiffableDataSourceSectionSnapshot<CBCNode> { var snapshot = NSDiffableDataSourceSectionSnapshot<CBCNode>() func addItems(_ menuItems: [CBCNode], to parent: CBCNode?) { snapshot.append(menuItems, to: parent) for menuItem in menuItems where !menuItem.children.isEmpty { addItems(menuItem.children, to: menuItem) } } addItems(section, to: nil) return snapshot } #endif } extension MDCDragonsController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if #available(iOS 14.0, *) { guard let menuItem = self.dataSource.itemIdentifier(for: indexPath) else { return } collectionView.deselectItem(at: indexPath, animated: true) if menuItem.isExample() || isSearchActive { setupTransition(nodeData: DragonCell(node: menuItem)) } } } }
35.668342
100
0.723349
0104b4de911cd3dee774cd0cc27ee800a4f2c6b4
1,677
import CloudKit import SwiftObserver import SwiftyToolz public extension CKContainer { func ensureAccountAccess() -> ResultPromise<Void> { promise { fetchAccountStatus() } .mapSuccess { status in let potentialErrorMessage: String? = { switch status { case .couldNotDetermine: return "Could not determine iCloud account status." case .available: return nil case .restricted: return "iCloud account is restricted." case .noAccount: return "Cannot access the iCloud account." case .temporarilyUnavailable: return "iCloud account is temporarily unavailable." @unknown default: return "Unknown account status." } }() if let errorMessage = potentialErrorMessage { let error = ReadableError(errorMessage) log(error) throw error } } } func fetchAccountStatus() -> ResultPromise<CKAccountStatus> { .init { promise in accountStatus { status, error in if let error = error { log(error) promise.fulfill(error) } else { promise.fulfill(status) } } } } } let iCloudQueue = DispatchQueue(label: "iCloud", qos: .userInitiated)
26.203125
97
0.468098
088ad344da9eadf0096941d2e0cf1abb1d661857
150
// // Swift.swift // samplage // // Created by Paul Kilmurray on 3/3/19. // Copyright © 2019 Facebook. All rights reserved. // import Foundation
15
51
0.666667
f9fa99b4e9ff26ab067929fe217802bde90f5b92
940
// // Created by Rene Dohan on 1/24/20. // import Foundation public extension Dictionary { var isSet: Bool { !isEmpty } var isNotEmpty: Bool { !isEmpty } @discardableResult public mutating func add(_ other: Dictionary) -> Dictionary { for (k, v) in other { self[k] = v } return self } @discardableResult public mutating func add(key: Key, value: Value) -> Value { self[key] = value return value } @discardableResult public mutating func remove(key: Key) -> Value? { removeValue(forKey: key) } public func toJsonString(formatted: Bool = false) -> String? { var options: JSONSerialization.WritingOptions = formatted ? [.prettyPrinted] : [] if let theJSONData = try? JSONSerialization.data(withJSONObject: self, options: options) { return String(data: theJSONData, encoding: .ascii) } return nil } }
25.405405
98
0.62234
9b9d9a6411ff5e752d5ace3e1b47514f24a83ef3
23,529
// // NSAssetKitWatchOS.swift // Nightscouter // // Created by Peter Ina on 11/9/15. // Copyright (c) 2015 Nothingonline.net. All rights reserved. // // Generated by PaintCode (www.paintcodeapp.com) // import UIKit open class NSAssetKitWatchOS : NSObject { //// Cache fileprivate struct Cache { static let appLogoTintColor: UIColor = UIColor(red: 0.000, green: 0.451, blue: 0.812, alpha: 1.000) static let darkNavColor: UIColor = NSAssetKitWatchOS.appLogoTintColor.colorWithShadow(0.6) static let predefinedWarningColor: UIColor = UIColor(red: 1.000, green: 0.902, blue: 0.125, alpha: 1.000) static let predefinedPostiveColor: UIColor = UIColor(red: 0.016, green: 0.871, blue: 0.443, alpha: 1.000) static let predefinedAlertColor: UIColor = UIColor(red: 1.000, green: 0.067, blue: 0.310, alpha: 1.000) static let predefinedNeutralColor: UIColor = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000) static let predefinedLogoColor: UIColor = UIColor(red: 0.363, green: 0.363, blue: 0.363, alpha: 1.000) } //// Colors @objc open class var appLogoTintColor: UIColor { return Cache.appLogoTintColor } @objc open class var darkNavColor: UIColor { return Cache.darkNavColor } @objc open class var predefinedWarningColor: UIColor { return Cache.predefinedWarningColor } @objc open class var predefinedPostiveColor: UIColor { return Cache.predefinedPostiveColor } @objc open class var predefinedAlertColor: UIColor { return Cache.predefinedAlertColor } @objc open class var predefinedNeutralColor: UIColor { return Cache.predefinedNeutralColor } @objc open class var predefinedLogoColor: UIColor { return Cache.predefinedLogoColor } //// Drawing Methods @objc open class func drawWatchFace(_ watchFrame: CGRect = CGRect(x: 0, y: 0, width: 134, height: 134), arrowTintColor: UIColor = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000), rawColor: UIColor = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000), isDoubleUp: Bool = false, isArrowVisible: Bool = false, isRawEnabled: Bool = true, textSizeForSgv: CGFloat = 39, textSizeForDelta: CGFloat = 10, textSizeForRaw: CGFloat = 12, deltaString: String = "-- --/--", sgvString: String = "---", rawString: String = "--- : -----", angle: CGFloat = 0) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Color Declarations let arrowTintShadowColor = arrowTintColor.colorWithShadow(0.2) //// Variable Declarations let arrowNotVisible = !isArrowVisible let isUncomputable = arrowNotVisible //// Subframes let group: CGRect = CGRect(x: watchFrame.minX + floor((watchFrame.width - 98) * 0.50000 + 0.5), y: watchFrame.minY + floor((watchFrame.height - 98) * 0.63889 + 0.5), width: 98, height: 98) let frame4 = CGRect(x: group.minX, y: group.minY, width: 98, height: 98) let centerRing: CGRect = CGRect(x: watchFrame.minX + floor((watchFrame.width - 117) * 0.52941 + 0.5), y: watchFrame.minY + floor((watchFrame.height - 117) * 0.47059 + 0.5), width: 117, height: 117) let frame3 = CGRect(x: centerRing.minX, y: centerRing.minY, width: 117, height: 117) let innerRing: CGRect = CGRect(x: watchFrame.minX + floor((watchFrame.width - 119) * 0.46667 + 0.5), y: watchFrame.minY + floor((watchFrame.height - 119) * 0.46667 + 0.5), width: 119, height: 119) let frame = CGRect(x: innerRing.minX, y: innerRing.minY, width: 119, height: 119) let frame2 = CGRect(x: watchFrame.minX, y: watchFrame.minY, width: 134, height: 134) let group2: CGRect = CGRect(x: frame2.minX + floor((frame2.width - 121.01) * 0.49961 + 0.01) + 0.49, y: frame2.minY + floor((frame2.height - 97.25) * 0.00004 - 0.25) + 0.75, width: 121.01, height: 97.25) //// Group //// sgvLabel Drawing let sgvLabelRect = CGRect(x: frame4.minX + floor(frame4.width * 0.04082 + 0.5), y: frame4.minY + floor(frame4.height * 0.03061 + 0.5), width: floor(frame4.width * 0.95918 + 0.5) - floor(frame4.width * 0.04082 + 0.5), height: floor(frame4.height * 0.58163 + 0.5) - floor(frame4.height * 0.03061 + 0.5)) let sgvLabelStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle sgvLabelStyle.alignment = .center let sgvLabelFontAttributes = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Thin", size: textSizeForSgv)!, NSAttributedString.Key.foregroundColor: arrowTintShadowColor, NSAttributedString.Key.paragraphStyle: sgvLabelStyle] NSString(string: sgvString).draw(in: sgvLabelRect, withAttributes: sgvLabelFontAttributes) //// deltaLabel Drawing let deltaLabelRect = CGRect(x: frame4.minX + floor(frame4.width * 0.04082 + 0.5), y: frame4.minY + floor(frame4.height * 0.48980 + 0.5), width: floor(frame4.width * 0.95918 + 0.5) - floor(frame4.width * 0.04082 + 0.5), height: floor(frame4.height * 0.66327 + 0.5) - floor(frame4.height * 0.48980 + 0.5)) let deltaLabelStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle deltaLabelStyle.alignment = .center let deltaLabelFontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: textSizeForDelta), NSAttributedString.Key.foregroundColor: arrowTintShadowColor, NSAttributedString.Key.paragraphStyle: deltaLabelStyle] let deltaLabelTextHeight: CGFloat = NSString(string: deltaString).boundingRect(with: CGSize(width: deltaLabelRect.width, height: CGFloat.infinity), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: deltaLabelFontAttributes, context: nil).size.height context.saveGState() context.clip(to: deltaLabelRect); NSString(string: deltaString).draw(in: CGRect(x: deltaLabelRect.minX, y: deltaLabelRect.minY + (deltaLabelRect.height - deltaLabelTextHeight) / 2, width: deltaLabelRect.width, height: deltaLabelTextHeight), withAttributes: deltaLabelFontAttributes) context.restoreGState() if (isRawEnabled) { //// rawLabel Drawing let rawLabelRect = CGRect(x: frame4.minX + floor(frame4.width * 0.04082 + 0.5), y: frame4.minY + floor(frame4.height * 0.65306 + 0.5), width: floor(frame4.width * 0.95918 + 0.5) - floor(frame4.width * 0.04082 + 0.5), height: floor(frame4.height * 0.86735 + 0.5) - floor(frame4.height * 0.65306 + 0.5)) let rawLabelStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle rawLabelStyle.alignment = .center let rawLabelFontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: textSizeForRaw), NSAttributedString.Key.foregroundColor: rawColor, NSAttributedString.Key.paragraphStyle: rawLabelStyle] let rawLabelTextHeight: CGFloat = NSString(string: rawString).boundingRect(with: CGSize(width: rawLabelRect.width, height: CGFloat.infinity), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: rawLabelFontAttributes, context: nil).size.height context.saveGState() context.clip(to: rawLabelRect); NSString(string: rawString).draw(in: CGRect(x: rawLabelRect.minX, y: rawLabelRect.minY + (rawLabelRect.height - rawLabelTextHeight) / 2, width: rawLabelRect.width, height: rawLabelTextHeight), withAttributes: rawLabelFontAttributes) context.restoreGState() } //// centerRing if (isUncomputable) { //// Oval 3 Drawing context.saveGState() context.translateBy(x: frame3.minX + 0.49573 * frame3.width, y: frame3.minY + 0.50427 * frame3.height) let oval3Path = UIBezierPath(ovalIn: CGRect(x: -52.5, y: -52.5, width: 105, height: 105)) arrowTintShadowColor.setStroke() oval3Path.lineWidth = 3 oval3Path.stroke() context.restoreGState() } if (isDoubleUp) { //// outterRing //// Group 2 context.saveGState() context.beginTransparencyLayer(auxiliaryInfo: nil) //// Clip Bezier 2 let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: 0.5, y: -67)) bezier2Path.addCurve(to: CGPoint(x: 7.06, y: -60.09), controlPoint1: CGPoint(x: 0.5, y: -67), controlPoint2: CGPoint(x: 4.27, y: -63.03)) bezier2Path.addCurve(to: CGPoint(x: 52.39, y: -30.25), controlPoint1: CGPoint(x: 25.37, y: -57.92), controlPoint2: CGPoint(x: 42.47, y: -47.44)) bezier2Path.addCurve(to: CGPoint(x: 52.39, y: 30.25), controlPoint1: CGPoint(x: 63.2, y: -11.53), controlPoint2: CGPoint(x: 63.2, y: 11.53)) bezier2Path.addLine(to: CGPoint(x: 48.93, y: 28.25)) bezier2Path.addCurve(to: CGPoint(x: 48.93, y: -28.25), controlPoint1: CGPoint(x: 59.02, y: 10.77), controlPoint2: CGPoint(x: 59.02, y: -10.77)) bezier2Path.addCurve(to: CGPoint(x: 6.03, y: -56.18), controlPoint1: CGPoint(x: 39.56, y: -44.49), controlPoint2: CGPoint(x: 23.34, y: -54.31)) bezier2Path.addCurve(to: CGPoint(x: 0.5, y: -62), controlPoint1: CGPoint(x: 3.42, y: -58.92), controlPoint2: CGPoint(x: 0.5, y: -62)) bezier2Path.addCurve(to: CGPoint(x: -4.92, y: -56.3), controlPoint1: CGPoint(x: 0.5, y: -62), controlPoint2: CGPoint(x: -2.34, y: -59.01)) bezier2Path.addCurve(to: CGPoint(x: -28.25, y: -48.93), controlPoint1: CGPoint(x: -12.9, y: -55.61), controlPoint2: CGPoint(x: -20.85, y: -53.2)) bezier2Path.addCurve(to: CGPoint(x: -55.84, y: -8.63), controlPoint1: CGPoint(x: -43.67, y: -40.03), controlPoint2: CGPoint(x: -53.3, y: -24.96)) bezier2Path.addCurve(to: CGPoint(x: -53.75, y: 17.44), controlPoint1: CGPoint(x: -57.17, y: -0.05), controlPoint2: CGPoint(x: -56.54, y: 8.88)) bezier2Path.addCurve(to: CGPoint(x: -48.93, y: 28.25), controlPoint1: CGPoint(x: -52.55, y: 21.13), controlPoint2: CGPoint(x: -50.95, y: 24.75)) bezier2Path.addLine(to: CGPoint(x: -52.39, y: 30.25)) bezier2Path.addCurve(to: CGPoint(x: -56.81, y: -20.8), controlPoint1: CGPoint(x: -61.72, y: 14.1), controlPoint2: CGPoint(x: -62.75, y: -4.56)) bezier2Path.addCurve(to: CGPoint(x: -30.25, y: -52.39), controlPoint1: CGPoint(x: -52.11, y: -33.66), controlPoint2: CGPoint(x: -43.04, y: -45.01)) bezier2Path.addCurve(to: CGPoint(x: -5.94, y: -60.22), controlPoint1: CGPoint(x: -22.54, y: -56.85), controlPoint2: CGPoint(x: -14.26, y: -59.41)) bezier2Path.addCurve(to: CGPoint(x: 0.5, y: -67), controlPoint1: CGPoint(x: -3.21, y: -63.1), controlPoint2: CGPoint(x: 0.39, y: -66.88)) bezier2Path.addLine(to: CGPoint(x: 0.5, y: -67)) bezier2Path.close() var bezier2Transformation = CGAffineTransform.identity bezier2Transformation = bezier2Transformation.translatedBy(x: group2.minX + 60.51, y: group2.minY + 67) bezier2Path.apply(bezier2Transformation) bezier2Path.addClip() //// Rectangle Drawing context.saveGState() context.translateBy(x: group2.minX + 60.51, y: group2.minY + 67) context.rotate(by: -angle * CGFloat(Double.pi) / 180) let rectanglePath = UIBezierPath() rectanglePath.move(to: CGPoint(x: 10, y: -57)) rectanglePath.addLine(to: CGPoint(x: 0.5, y: -67)) rectanglePath.addLine(to: CGPoint(x: -9, y: -57)) rectanglePath.addLine(to: CGPoint(x: 10, y: -57)) rectanglePath.close() arrowTintShadowColor.setFill() rectanglePath.fill() context.restoreGState() //// Oval 2 Drawing context.saveGState() context.translateBy(x: group2.minX + 60.51, y: group2.minY + 67) context.rotate(by: -angle * CGFloat(Double.pi) / 180) let oval2Rect = CGRect(x: -58.5, y: -58.5, width: 117, height: 117) let oval2Path = UIBezierPath() oval2Path.addArc(withCenter: CGPoint(x: oval2Rect.midX, y: oval2Rect.midY), radius: oval2Rect.width / 2, startAngle: -210 * CGFloat(Double.pi)/180, endAngle: 30 * CGFloat(Double.pi)/180, clockwise: true) arrowTintShadowColor.setStroke() oval2Path.lineWidth = 4 oval2Path.stroke() context.restoreGState() context.endTransparencyLayer() context.restoreGState() } //// innerRing //// Oval Drawing context.saveGState() context.translateBy(x: frame.minX + 0.50420 * frame.width, y: frame.minY + 0.50420 * frame.height) context.rotate(by: -angle * CGFloat(Double.pi) / 180) let ovalRect = CGRect(x: -52.5, y: -52.5, width: 105, height: 105) let ovalPath = UIBezierPath() ovalPath.addArc(withCenter: CGPoint(x: ovalRect.midX, y: ovalRect.midY), radius: ovalRect.width / 2, startAngle: -220 * CGFloat(Double.pi)/180, endAngle: 40 * CGFloat(Double.pi)/180, clockwise: true) arrowTintShadowColor.setStroke() ovalPath.lineWidth = 3 ovalPath.stroke() context.restoreGState() if (isArrowVisible) { //// Rectangle 2 Drawing context.saveGState() context.translateBy(x: frame.minX + 0.50420 * frame.width, y: frame.minY + 0.50420 * frame.height) context.rotate(by: -angle * CGFloat(Double.pi) / 180) let rectangle2Path = UIBezierPath() rectangle2Path.move(to: CGPoint(x: 8, y: -53)) rectangle2Path.addLine(to: CGPoint(x: 0.5, y: -59)) rectangle2Path.addLine(to: CGPoint(x: -7, y: -53)) rectangle2Path.addLine(to: CGPoint(x: 8, y: -53)) rectangle2Path.close() arrowTintShadowColor.setFill() rectangle2Path.fill() context.restoreGState() } } @objc open class func drawSourceIcon(_ logoTintColor: UIColor = UIColor(red: 0.300, green: 0.300, blue: 0.300, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Color Declarations let logoHighlightColor = logoTintColor.colorWithHighlight(1) let logoShadowColor = NSAssetKitWatchOS.appLogoTintColor.colorWithShadow(0.218) //// Gradient Declarations let logoGradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [NSAssetKitWatchOS.appLogoTintColor.cgColor, logoShadowColor.cgColor] as CFArray, locations: [0, 1])! //// Group //// Rectangle Drawing let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100)) context.saveGState() rectanglePath.addClip() context.drawLinearGradient(logoGradient, start: CGPoint(x: 50, y: -0), end: CGPoint(x: 50, y: 100), options: CGGradientDrawingOptions()) context.restoreGState() //// outerShape 2 Drawing let outerShape2Path = UIBezierPath() outerShape2Path.move(to: CGPoint(x: 79.86, y: 38.09)) outerShape2Path.addCurve(to: CGPoint(x: 74.53, y: 58.24), controlPoint1: CGPoint(x: 80.6, y: 42.54), controlPoint2: CGPoint(x: 78.37, y: 50.18)) outerShape2Path.addCurve(to: CGPoint(x: 54.82, y: 85.32), controlPoint1: CGPoint(x: 69.65, y: 68.49), controlPoint2: CGPoint(x: 62.16, y: 79.41)) outerShape2Path.addCurve(to: CGPoint(x: 50.78, y: 88.33), controlPoint1: CGPoint(x: 51.54, y: 87.96), controlPoint2: CGPoint(x: 51.75, y: 87.84)) outerShape2Path.addCurve(to: CGPoint(x: 49.26, y: 88.33), controlPoint1: CGPoint(x: 50.52, y: 88.33), controlPoint2: CGPoint(x: 49.52, y: 88.33)) outerShape2Path.addCurve(to: CGPoint(x: 45.21, y: 85.32), controlPoint1: CGPoint(x: 49.26, y: 88.33), controlPoint2: CGPoint(x: 46.83, y: 86.81)) outerShape2Path.addCurve(to: CGPoint(x: 24.37, y: 58.1), controlPoint1: CGPoint(x: 38.74, y: 79.38), controlPoint2: CGPoint(x: 28.69, y: 68.39)) outerShape2Path.addCurve(to: CGPoint(x: 20.18, y: 38.09), controlPoint1: CGPoint(x: 21, y: 50.09), controlPoint2: CGPoint(x: 19.44, y: 42.51)) outerShape2Path.addCurve(to: CGPoint(x: 49.13, y: 10), controlPoint1: CGPoint(x: 20.18, y: 22.58), controlPoint2: CGPoint(x: 33.14, y: 10)) outerShape2Path.addCurve(to: CGPoint(x: 50.9, y: 10), controlPoint1: CGPoint(x: 49.44, y: 10), controlPoint2: CGPoint(x: 50.6, y: 10)) outerShape2Path.addCurve(to: CGPoint(x: 79.86, y: 38.09), controlPoint1: CGPoint(x: 66.9, y: 10), controlPoint2: CGPoint(x: 79.86, y: 22.58)) outerShape2Path.close() outerShape2Path.lineCapStyle = .round; outerShape2Path.lineJoinStyle = .round; logoHighlightColor.setStroke() outerShape2Path.lineWidth = 1.5 outerShape2Path.stroke() //// Oval Drawing let ovalPath = UIBezierPath(ovalIn: CGRect(x: 28, y: 19, width: 44, height: 39)) logoHighlightColor.setStroke() ovalPath.lineWidth = 1.5 ovalPath.stroke() //// crest //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 65, y: 60)) bezierPath.addCurve(to: CGPoint(x: 53.02, y: 76.03), controlPoint1: CGPoint(x: 65, y: 60), controlPoint2: CGPoint(x: 61.48, y: 69.12)) bezierPath.addCurve(to: CGPoint(x: 50.71, y: 77.84), controlPoint1: CGPoint(x: 51.31, y: 77.42), controlPoint2: CGPoint(x: 51.07, y: 77.64)) bezierPath.addCurve(to: CGPoint(x: 50.57, y: 78), controlPoint1: CGPoint(x: 50.62, y: 77.95), controlPoint2: CGPoint(x: 50.57, y: 78)) bezierPath.addLine(to: CGPoint(x: 49.43, y: 78)) bezierPath.addCurve(to: CGPoint(x: 49.29, y: 77.84), controlPoint1: CGPoint(x: 49.43, y: 78), controlPoint2: CGPoint(x: 49.38, y: 77.95)) bezierPath.addCurve(to: CGPoint(x: 46.98, y: 76.03), controlPoint1: CGPoint(x: 48.93, y: 77.64), controlPoint2: CGPoint(x: 48.69, y: 77.42)) bezierPath.addCurve(to: CGPoint(x: 43.65, y: 72.97), controlPoint1: CGPoint(x: 45.77, y: 75.04), controlPoint2: CGPoint(x: 44.67, y: 74.01)) bezierPath.addCurve(to: CGPoint(x: 48.98, y: 65.02), controlPoint1: CGPoint(x: 44.98, y: 70.98), controlPoint2: CGPoint(x: 47.66, y: 66.99)) bezierPath.addCurve(to: CGPoint(x: 50, y: 65.05), controlPoint1: CGPoint(x: 49.32, y: 65.04), controlPoint2: CGPoint(x: 49.66, y: 65.05)) bezierPath.addCurve(to: CGPoint(x: 65, y: 60), controlPoint1: CGPoint(x: 57.01, y: 65.05), controlPoint2: CGPoint(x: 65, y: 60)) bezierPath.close() bezierPath.move(to: CGPoint(x: 35, y: 60)) bezierPath.addCurve(to: CGPoint(x: 44.56, y: 64.22), controlPoint1: CGPoint(x: 35, y: 60), controlPoint2: CGPoint(x: 39.41, y: 62.79)) bezierPath.addCurve(to: CGPoint(x: 40.58, y: 69.42), controlPoint1: CGPoint(x: 43.86, y: 65.14), controlPoint2: CGPoint(x: 41.98, y: 67.6)) bezierPath.addCurve(to: CGPoint(x: 35, y: 60), controlPoint1: CGPoint(x: 36.7, y: 64.41), controlPoint2: CGPoint(x: 35, y: 60)) bezierPath.addLine(to: CGPoint(x: 35, y: 60)) bezierPath.close() bezierPath.lineCapStyle = .round; bezierPath.lineJoinStyle = .round; logoHighlightColor.setFill() bezierPath.fill() //// Oval 5 Drawing let oval5Path = UIBezierPath(ovalIn: CGRect(x: 37, y: 34, width: 6, height: 6)) logoHighlightColor.setFill() oval5Path.fill() //// Bezier 3 Drawing let bezier3Path = UIBezierPath() bezier3Path.move(to: CGPoint(x: 50, y: 28.33)) bezier3Path.addLine(to: CGPoint(x: 50, y: 46.67)) bezier3Path.lineCapStyle = .round; logoHighlightColor.setStroke() bezier3Path.lineWidth = 1.5 bezier3Path.stroke() //// Oval 2 Drawing let oval2Path = UIBezierPath(ovalIn: CGRect(x: 57, y: 34, width: 6, height: 6)) logoHighlightColor.setFill() oval2Path.fill() } //// Generated Images @objc open class func imageOfWatchFace(_ watchFrame: CGRect = CGRect(x: 0, y: 0, width: 134, height: 134), arrowTintColor: UIColor = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000), rawColor: UIColor = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000), isDoubleUp: Bool = false, isArrowVisible: Bool = false, isRawEnabled: Bool = true, textSizeForSgv: CGFloat = 39, textSizeForDelta: CGFloat = 10, textSizeForRaw: CGFloat = 12, deltaString: String = "-- --/--", sgvString: String = "---", rawString: String = "--- : -----", angle: CGFloat = 0) -> UIImage { UIGraphicsBeginImageContextWithOptions(watchFrame.size, false, 0) NSAssetKitWatchOS.drawWatchFace(CGRect(x: 0, y: 0, width: watchFrame.size.width, height: watchFrame.size.height), arrowTintColor: arrowTintColor, rawColor: rawColor, isDoubleUp: isDoubleUp, isArrowVisible: isArrowVisible, isRawEnabled: isRawEnabled, textSizeForSgv: textSizeForSgv, textSizeForDelta: textSizeForDelta, textSizeForRaw: textSizeForRaw, deltaString: deltaString, sgvString: sgvString, rawString: rawString, angle: angle) let imageOfWatchFace = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return imageOfWatchFace } } extension UIColor { @objc func colorWithHue(_ newHue: CGFloat) -> UIColor { var saturation: CGFloat = 1.0, brightness: CGFloat = 1.0, alpha: CGFloat = 1.0 self.getHue(nil, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: newHue, saturation: saturation, brightness: brightness, alpha: alpha) } @objc func colorWithSaturation(_ newSaturation: CGFloat) -> UIColor { var hue: CGFloat = 1.0, brightness: CGFloat = 1.0, alpha: CGFloat = 1.0 self.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: newSaturation, brightness: brightness, alpha: alpha) } @objc func colorWithBrightness(_ newBrightness: CGFloat) -> UIColor { var hue: CGFloat = 1.0, saturation: CGFloat = 1.0, alpha: CGFloat = 1.0 self.getHue(&hue, saturation: &saturation, brightness: nil, alpha: &alpha) return UIColor(hue: hue, saturation: saturation, brightness: newBrightness, alpha: alpha) } @objc func colorWithAlpha(_ newAlpha: CGFloat) -> UIColor { var hue: CGFloat = 1.0, saturation: CGFloat = 1.0, brightness: CGFloat = 1.0 self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: newAlpha) } @objc func colorWithHighlight(_ highlight: CGFloat) -> UIColor { var red: CGFloat = 1.0, green: CGFloat = 1.0, blue: CGFloat = 1.0, alpha: CGFloat = 1.0 self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red * (1-highlight) + highlight, green: green * (1-highlight) + highlight, blue: blue * (1-highlight) + highlight, alpha: alpha * (1-highlight) + highlight) } @objc func colorWithShadow(_ shadow: CGFloat) -> UIColor { var red: CGFloat = 1.0, green: CGFloat = 1.0, blue: CGFloat = 1.0, alpha: CGFloat = 1.0 self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red * (1-shadow), green: green * (1-shadow), blue: blue * (1-shadow), alpha: alpha * (1-shadow) + shadow) } }
60.79845
584
0.652259
e4ba90c4bc985f1a7e6ffe04ff81899da1d02fc6
1,638
// // HomeViewController.swift // SwappingCollectionView // // Created by Rumana Nazmul on 24/5/17. // Copyright © 2017 Paweł Łopusiński. All rights reserved. // import UIKit //var areImageLoaded = false //var myGameLevel = 2 //var imageLibrary = repository(gameLevel: myGameLevel) class HomeViewController: UIViewController { var menuShowing = false @IBOutlet weak var LeadConsTopMenu: NSLayoutConstraint! @IBOutlet weak var trailConsTopMenu: NSLayoutConstraint! @IBOutlet weak var topMenuView: GradView! @IBAction func menuLineButton(_ sender: UIButton) { if menuShowing == false{ self.LeadConsTopMenu.constant = 180 self.trailConsTopMenu.constant = 0 } else{ self.LeadConsTopMenu.constant = 0 self.trailConsTopMenu.constant = 0 } UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } menuShowing = !menuShowing } @IBAction func albumButton(_ sender: UIButton) { performSegue(withIdentifier: "ShowAlbum", sender: nil) } @IBAction func scoreButton(_ sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() // if(areImageLoaded == false){ // imageLibrary.loadAllImages() // areImageLoaded = true // } topMenuView.layer.shadowOpacity = 1 topMenuView.layer.shadowRadius = 3 } }
21.552632
62
0.568987
abbdd97ff6bbb5fe57a1ed81f74bcb2aa2be41e9
1,132
// // ContentSizeCategory+Accessibility.swift // // // Created by Bastián Véliz Vega on 14-09-20. // import SwiftUI public extension ContentSizeCategory { /** Check if an Accessibility category is used - Note: - Returns `false` is ContentSizeCategory value is` .extraSmall`, `.small`, `.medium`, `.large`, `.extraLarge`, `.extraExtraLarge`, `.extraExtraExtraLarge` - Return `true` in another case */ var isAccessibility: Bool { switch self { case .extraSmall, .small, .medium, .large, .extraLarge, .extraExtraLarge, .extraExtraExtraLarge: return false default: return true } } /** Check if an extra large Accessibility category is used - Note: - Returns `true` is ContentSizeCategory value is, `.extraLarge`, `.extraExtraLarge`, `.extraExtraExtraLarge` - Return `false` in another case */ var isExtraLarge: Bool { switch self { case .extraLarge, .extraExtraLarge, .extraExtraExtraLarge: return true default: return false } } }
26.325581
162
0.609541
675b598fa06334ce50989c096293bf94b148afaa
40
// RUN: %{python} %utils/line-directive
20
39
0.675
909070d2eaa8e36c07b4946c350dd7a60aa678df
1,919
import Foundation import Leonid internal extension FileManager { internal func filteredMusicFileURLs(inDirectory directory: String) -> [URL] { guard let enumerator = enumerator(at: URL(fileURLWithPath: directory), includingPropertiesForKeys: nil, options: [], errorHandler: nil) else { return [] } var musicFiles = [URL]() let enumeration: () -> Bool = { guard let fileURL = enumerator.nextObject() as? URL else { return false } if fileURL.isMusicFile { musicFiles.append(fileURL) } return true } while enumeration() {} return musicFiles } } internal extension URL { private enum MusicFileExtension: String { case mp3 = "mp3" case m4a = "m4a" case m4p = "m4p" } internal var isMusicFile: Bool { return MusicFileExtension(rawValue: pathExtension) != nil } } internal extension String { internal static let arrow = "=====>".addingBash(color: .blue, style: .dim) internal var tinted: String { return addingBash(color: .blue, style: .none) } internal var turnedOn: String { return addingBash(color: .green, style: .none) } internal var turnedOff: String { return addingBash(color: .red, style: .dim) } internal var highlighted: String { return addingBash(color: .white, style: .bold) } internal var underlined: String { return addingBash(color: .white, style: .underline) } } internal extension Collection { internal func shuffled() -> [Generator.Element] { var array = Array(self) array.shuffle() return array } } internal extension MutableCollection where Index == Int, IndexDistance == Int { internal mutating func shuffle() { guard count > 1 else { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }
22.313953
146
0.648254
167fd1e54e002139e28fb96eeff531231c05da18
2,389
// // EditorTextView.swift // Pyto // // Created by Emma Labbé on 24-08-20. // Copyright © 2020 Emma Labbé. All rights reserved. // import UIKit /// An `UITextView` to be used on the editor. class EditorTextView: LineNumberTextView, UITextViewDelegate { /// Undo. @objc func undo() { let theDelegate = delegate delegate = nil undoManager?.undo() delegate = theDelegate } /// Redo. @objc func redo() { let theDelegate = delegate delegate = nil undoManager?.redo() delegate = theDelegate } override var keyCommands: [UIKeyCommand]? { let undoCommand = UIKeyCommand.command(input: "z", modifierFlags: .command, action: #selector(undo), discoverabilityTitle: Localizable.MenuItems.undo) let redoCommand = UIKeyCommand.command(input: "z", modifierFlags: [.command, .shift], action: #selector(redo), discoverabilityTitle: Localizable.MenuItems.redo) var commands = [UIKeyCommand]() if undoManager?.canUndo == true { commands.append(undoCommand) } if undoManager?.canRedo == true { commands.append(redoCommand) } return commands } override var canBecomeFirstResponder: Bool { return true } override func paste(_ sender: Any?) { let theDelegate = delegate delegate = self if let range = selectedTextRange, let pasteboard = UIPasteboard.general.string { replace(range, withText: pasteboard) } delegate = theDelegate } override func cut(_ sender: Any?) { let theDelegate = delegate delegate = self if let range = selectedTextRange { let text = self.text(in: range) UIPasteboard.general.string = text replace(range, withText: "") } delegate = theDelegate } // Fixes a weird bug while cutting func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "" && range.length > 1 { textView.replace(range.toTextRange(textInput: textView) ?? UITextRange(), withText: text) return false } else { return true } } }
28.105882
168
0.584345
62b4c2145c71e02b5984a39e20dcc3f0bd6ae1f0
4,311
// // SelectLanguageVC.swift // Commun // // Created by Chung Tran on 11/1/19. // Copyright © 2019 Commun Limited. All rights reserved. // import Foundation import RxDataSources import RxCocoa import Localize_Swift class SelectInterfaceLanguageVC: BaseViewController { // MARK: - Properties let supportedLanguages = Language.supported.filter {$0.isSupportedInterfaceLanguage == true} // MARK: - Subviews let closeButton = UIButton.close() var tableView = UITableView(forAutoLayout: ()) lazy var languages = BehaviorRelay<[Language]>(value: supportedLanguages) // MARK: - Methods override func setUp() { super.setUp() view.backgroundColor = .appLightGrayColor title = "language".localized().uppercaseFirst setRightNavBarButton(with: closeButton) closeButton.addTarget(self, action: #selector(back), for: .touchUpInside) view.addSubview(tableView) tableView.autoPinEdgesToSuperviewSafeArea(with: UIEdgeInsets(top: 20, left: 10, bottom: 0, right: 10)) tableView.register(LanguageCell.self, forCellReuseIdentifier: "LanguageCell") tableView.separatorStyle = .none tableView.tableFooterView = UIView() tableView.backgroundColor = .clear // get current language chooseCurrentLanguage() } private func chooseCurrentLanguage() { let langs: [Language] = languages.value.map { lang in var lang = lang lang.isCurrentInterfaceLanguage = lang.code == Localize.currentLanguage() return lang } languages.accept(langs) } override func bind() { super.bind() let dataSource = MyRxTableViewSectionedAnimatedDataSource<AnimatableSectionModel<String, Language>>( configureCell: { _, _, indexPath, item in let cell = self.tableView.dequeueReusableCell(withIdentifier: "LanguageCell", for: indexPath) as! LanguageCell cell.setUp(with: item) cell.roundedCorner = [] if indexPath.row == 0 { cell.roundedCorner.insert([.topLeft, .topRight]) } if indexPath.row == self.languages.value.count - 1 { cell.separator.isHidden = true cell.roundedCorner.insert([.bottomLeft, .bottomRight]) } return cell } ) languages.map {[AnimatableSectionModel<String, Language>](arrayLiteral: AnimatableSectionModel<String, Language>(model: "", items: $0))} .bind(to: tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) tableView.rx.modelSelected(Language.self) .subscribe(onNext: { (language) in if language.isCurrentInterfaceLanguage == true {return} self.showActionSheet( title: "would you like to change the application's language to".localized().uppercaseFirst + " " + (language.name + " language").localized().uppercaseFirst + "?", actions: [ UIAlertAction( title: "change to".localized().uppercaseFirst + " " + (language.name + " language").localized().uppercaseFirst, style: .default, handler: { _ in Localize.setCurrentLanguage(language.code) self.chooseCurrentLanguage() let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = SplashVC() DispatchQueue.main.asyncAfter(deadline: .now() + 1) { appDelegate.tabBarVC = TabBarVC() appDelegate.changeRootVC(appDelegate.tabBarVC) } } ) ]) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { } }) .disposed(by: disposeBag) } }
41.451923
182
0.558339
8f10f331c32f5d4bf00fdad2445e5055c848d72f
10,455
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: tendermint/types/validator.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct Tendermint_Types_ValidatorSet { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var validators: [Tendermint_Types_Validator] = [] var proposer: Tendermint_Types_Validator { get {return _proposer ?? Tendermint_Types_Validator()} set {_proposer = newValue} } /// Returns true if `proposer` has been explicitly set. var hasProposer: Bool {return self._proposer != nil} /// Clears the value of `proposer`. Subsequent reads from it will return its default value. mutating func clearProposer() {self._proposer = nil} var totalVotingPower: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _proposer: Tendermint_Types_Validator? = nil } struct Tendermint_Types_Validator { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var address: Data = Data() var pubKey: Tendermint_Crypto_PublicKey { get {return _pubKey ?? Tendermint_Crypto_PublicKey()} set {_pubKey = newValue} } /// Returns true if `pubKey` has been explicitly set. var hasPubKey: Bool {return self._pubKey != nil} /// Clears the value of `pubKey`. Subsequent reads from it will return its default value. mutating func clearPubKey() {self._pubKey = nil} var votingPower: Int64 = 0 var proposerPriority: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _pubKey: Tendermint_Crypto_PublicKey? = nil } struct Tendermint_Types_SimpleValidator { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var pubKey: Tendermint_Crypto_PublicKey { get {return _pubKey ?? Tendermint_Crypto_PublicKey()} set {_pubKey = newValue} } /// Returns true if `pubKey` has been explicitly set. var hasPubKey: Bool {return self._pubKey != nil} /// Clears the value of `pubKey`. Subsequent reads from it will return its default value. mutating func clearPubKey() {self._pubKey = nil} var votingPower: Int64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _pubKey: Tendermint_Crypto_PublicKey? = nil } #if swift(>=5.5) && canImport(_Concurrency) extension Tendermint_Types_ValidatorSet: @unchecked Sendable {} extension Tendermint_Types_Validator: @unchecked Sendable {} extension Tendermint_Types_SimpleValidator: @unchecked Sendable {} #endif // swift(>=5.5) && canImport(_Concurrency) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "tendermint.types" extension Tendermint_Types_ValidatorSet: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ValidatorSet" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "validators"), 2: .same(proto: "proposer"), 3: .standard(proto: "total_voting_power"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.validators) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._proposer) }() case 3: try { try decoder.decodeSingularInt64Field(value: &self.totalVotingPower) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.validators.isEmpty { try visitor.visitRepeatedMessageField(value: self.validators, fieldNumber: 1) } try { if let v = self._proposer { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() if self.totalVotingPower != 0 { try visitor.visitSingularInt64Field(value: self.totalVotingPower, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Tendermint_Types_ValidatorSet, rhs: Tendermint_Types_ValidatorSet) -> Bool { if lhs.validators != rhs.validators {return false} if lhs._proposer != rhs._proposer {return false} if lhs.totalVotingPower != rhs.totalVotingPower {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Tendermint_Types_Validator: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Validator" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), 2: .standard(proto: "pub_key"), 3: .standard(proto: "voting_power"), 4: .standard(proto: "proposer_priority"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBytesField(value: &self.address) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._pubKey) }() case 3: try { try decoder.decodeSingularInt64Field(value: &self.votingPower) }() case 4: try { try decoder.decodeSingularInt64Field(value: &self.proposerPriority) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.address.isEmpty { try visitor.visitSingularBytesField(value: self.address, fieldNumber: 1) } try { if let v = self._pubKey { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() if self.votingPower != 0 { try visitor.visitSingularInt64Field(value: self.votingPower, fieldNumber: 3) } if self.proposerPriority != 0 { try visitor.visitSingularInt64Field(value: self.proposerPriority, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Tendermint_Types_Validator, rhs: Tendermint_Types_Validator) -> Bool { if lhs.address != rhs.address {return false} if lhs._pubKey != rhs._pubKey {return false} if lhs.votingPower != rhs.votingPower {return false} if lhs.proposerPriority != rhs.proposerPriority {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Tendermint_Types_SimpleValidator: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SimpleValidator" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "pub_key"), 2: .standard(proto: "voting_power"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._pubKey) }() case 2: try { try decoder.decodeSingularInt64Field(value: &self.votingPower) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._pubKey { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } }() if self.votingPower != 0 { try visitor.visitSingularInt64Field(value: self.votingPower, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Tendermint_Types_SimpleValidator, rhs: Tendermint_Types_SimpleValidator) -> Bool { if lhs._pubKey != rhs._pubKey {return false} if lhs.votingPower != rhs.votingPower {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
41.653386
144
0.731803
e4735527aec4cd335f173be9070638bf21429226
28,599
// // CropperViewController.swift // // Created by Chen Qizhi on 2019/10/15. // import UIKit enum CropBoxEdge: Int { case none case left case topLeft case top case topRight case right case bottomRight case bottom case bottomLeft } public protocol CropperViewControllerDelegate: class { func cropperDidConfirm(_ cropper: CropperViewController, state: CropperState?) func cropperDidCancel(_ cropper: CropperViewController) } public extension CropperViewControllerDelegate { func cropperDidCancel(_ cropper: CropperViewController) { cropper.dismiss(animated: true, completion: nil) } } open class CropperViewController: UIViewController, Rotatable, StateRestorable, Flipable { public let originalImage: UIImage var initialState: CropperState? var isCircular: Bool public init(originalImage: UIImage, initialState: CropperState? = nil, isCircular: Bool = false) { self.originalImage = originalImage self.initialState = initialState self.isCircular = isCircular super.init(nibName: nil, bundle: nil) modalPresentationStyle = .fullScreen } public required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } public weak var delegate: CropperViewControllerDelegate? // if self not init with a state, return false open var isCurrentlyInInitialState: Bool { isCurrentlyInState(initialState) } public var aspectRatioLocked: Bool = false { didSet { overlay.free = !aspectRatioLocked } } public var currentAspectRatioValue: CGFloat = 1.0 public var isCropBoxPanEnabled: Bool = true public var cropContentInset: UIEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) let cropBoxHotArea: CGFloat = 50 let cropBoxMinSize: CGFloat = 20 let barHeight: CGFloat = 44 var cropRegionInsets: UIEdgeInsets = .zero var maxCropRegion: CGRect = .zero var defaultCropBoxCenter: CGPoint = .zero var defaultCropBoxSize: CGSize = .zero var straightenAngle: CGFloat = 0.0 var rotationAngle: CGFloat = 0.0 var flipAngle: CGFloat = 0.0 var panBeginningPoint: CGPoint = .zero var panBeginningCropBoxEdge: CropBoxEdge = .none var panBeginningCropBoxFrame: CGRect = .zero var manualZoomed: Bool = false var needReload: Bool = false var defaultCropperState: CropperState? var stasisTimer: Timer? var stasisThings: (() -> Void)? open var isCurrentlyInDefalutState: Bool { isCurrentlyInState(defaultCropperState) } var totalAngle: CGFloat { return autoHorizontalOrVerticalAngle(straightenAngle + rotationAngle + flipAngle) } lazy var scrollViewContainer: ScrollViewContainer = ScrollViewContainer(frame: self.view.bounds) lazy var scrollView: UIScrollView = { let sv = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.defaultCropBoxSize.width, height: self.defaultCropBoxSize.height)) sv.delegate = self sv.center = self.backgroundView.convert(defaultCropBoxCenter, to: scrollViewContainer) sv.bounces = true sv.bouncesZoom = true sv.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) sv.alwaysBounceVertical = true sv.alwaysBounceHorizontal = true sv.minimumZoomScale = 1 sv.maximumZoomScale = 20 sv.showsVerticalScrollIndicator = false sv.showsHorizontalScrollIndicator = false sv.clipsToBounds = false sv.contentSize = self.defaultCropBoxSize //// debug // sv.layer.borderColor = UIColor.green.cgColor // sv.layer.borderWidth = 1 // sv.showsVerticalScrollIndicator = true // sv.showsHorizontalScrollIndicator = true return sv }() lazy var imageView: UIImageView = { let iv = UIImageView(image: self.originalImage) iv.backgroundColor = .clear return iv }() lazy var cropBoxPanGesture: UIPanGestureRecognizer = { let pan = UIPanGestureRecognizer(target: self, action: #selector(cropBoxPan(_:))) pan.delegate = self return pan }() // MARK: Custom UI lazy var backgroundView: UIView = { let view = UIView(frame: self.view.bounds) view.backgroundColor = UIColor(white: 0.06, alpha: 1) return view }() open lazy var bottomView: UIView = { let view = UIView(frame: CGRect(x: 0, y: self.view.height - 100, width: self.view.width, height: 100)) view.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] return view }() open lazy var topBar: UIView = { let topBar = TopBar(frame: CGRect(x: 0, y: 0, width: self.view.width, height: self.view.safeAreaInsets.top + barHeight)) topBar.flipButton.addTarget(self, action: #selector(flipButtonPressed(_:)), for: .touchUpInside) topBar.rotateButton.addTarget(self, action: #selector(rotateButtonPressed(_:)), for: .touchUpInside) topBar.aspectRationButton.addTarget(self, action: #selector(aspectRationButtonPressed(_:)), for: .touchUpInside) return topBar }() open lazy var toolbar: UIView = { let toolbar = Toolbar(frame: CGRect(x: 0, y: 0, width: self.view.width, height: view.safeAreaInsets.bottom + barHeight)) toolbar.doneButton.addTarget(self, action: #selector(confirmButtonPressed(_:)), for: .touchUpInside) toolbar.cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside) toolbar.resetButton.addTarget(self, action: #selector(resetButtonPressed(_:)), for: .touchUpInside) return toolbar }() let verticalAspectRatios: [AspectRatio] = [ .original, .freeForm, .square, .ratio(width: 9, height: 16), .ratio(width: 8, height: 10), .ratio(width: 5, height: 7), .ratio(width: 3, height: 4), .ratio(width: 3, height: 5), .ratio(width: 2, height: 3) ] open lazy var overlay: Overlay = Overlay(frame: self.view.bounds) public lazy var angleRuler: AngleRuler = { let ar = AngleRuler(frame: CGRect(x: 0, y: 0, width: view.width, height: 80)) ar.addTarget(self, action: #selector(angleRulerValueChanged(_:)), for: .valueChanged) ar.addTarget(self, action: #selector(angleRulerTouchEnded(_:)), for: [.editingDidEnd]) return ar }() public lazy var aspectRatioPicker: AspectRatioPicker = { let picker = AspectRatioPicker(frame: CGRect(x: 0, y: 0, width: view.width, height: 80)) picker.isHidden = true picker.delegate = self return picker }() @objc func angleRulerValueChanged(_: AnyObject) { toolbar.isUserInteractionEnabled = false topBar.isUserInteractionEnabled = false scrollViewContainer.isUserInteractionEnabled = false setStraightenAngle(CGFloat(angleRuler.value * CGFloat.pi / 180.0)) } @objc func angleRulerTouchEnded(_: AnyObject) { UIView.animate(withDuration: 0.25, animations: { self.overlay.gridLinesAlpha = 0 self.overlay.blur = true }, completion: { _ in self.toolbar.isUserInteractionEnabled = true self.topBar.isUserInteractionEnabled = true self.scrollViewContainer.isUserInteractionEnabled = true self.overlay.gridLinesCount = 2 }) } // MARK: - Override deinit { self.cancelStasis() } open override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.isHidden = true view.clipsToBounds = true // TODO: transition if originalImage.size.width < 1 || originalImage.size.height < 1 { // TODO: show alert and dismiss return } view.backgroundColor = .clear scrollView.addSubview(imageView) if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } else { automaticallyAdjustsScrollViewInsets = false } scrollViewContainer.scrollView = scrollView scrollViewContainer.addSubview(scrollView) scrollViewContainer.addGestureRecognizer(cropBoxPanGesture) scrollView.panGestureRecognizer.require(toFail: cropBoxPanGesture) backgroundView.addSubview(scrollViewContainer) backgroundView.addSubview(overlay) bottomView.addSubview(aspectRatioPicker) bottomView.addSubview(angleRuler) bottomView.addSubview(toolbar) view.addSubview(backgroundView) view.addSubview(bottomView) view.addSubview(topBar) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Layout when self.view finish layout and never layout before, or self.view need reload if let viewFrame = defaultCropperState?.viewFrame, viewFrame.equalTo(view.frame) { if needReload { // TODO: reload but keep crop box needReload = false resetToDefaultLayout() } } else { // TODO: suppport multi oriention resetToDefaultLayout() if let initialState = initialState { restoreState(initialState) updateButtons() } } } open override var prefersStatusBarHidden: Bool { return true } open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } open override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { return .top } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if !view.size.isEqual(to: size, accuracy: 0.0001) { needReload = true } super.viewWillTransition(to: size, with: coordinator) } // MARK: - User Interaction @objc func cropBoxPan(_ pan: UIPanGestureRecognizer) { guard isCropBoxPanEnabled else { return } let point = pan.location(in: view) if pan.state == .began { cancelStasis() panBeginningPoint = point panBeginningCropBoxFrame = overlay.cropBoxFrame panBeginningCropBoxEdge = nearestCropBoxEdgeForPoint(point: panBeginningPoint) overlay.blur = false overlay.gridLinesAlpha = 1 topBar.isUserInteractionEnabled = false bottomView.isUserInteractionEnabled = false } if pan.state == .ended || pan.state == .cancelled { stasisAndThenRun { self.matchScrollViewAndCropView(animated: true, targetCropBoxFrame: self.overlay.cropBoxFrame, extraZoomScale: 1, blurLayerAnimated: true, animations: { self.overlay.gridLinesAlpha = 0 self.overlay.blur = true }, completion: { self.topBar.isUserInteractionEnabled = true self.bottomView.isUserInteractionEnabled = true self.updateButtons() }) } } else { updateCropBoxFrameWithPanGesturePoint(point) } } @objc func cancelButtonPressed(_: UIButton) { delegate?.cropperDidCancel(self) } @objc func confirmButtonPressed(_: UIButton) { delegate?.cropperDidConfirm(self, state: saveState()) } @objc func resetButtonPressed(_: UIButton) { overlay.blur = false overlay.gridLinesAlpha = 0 overlay.cropBoxAlpha = 0 topBar.isUserInteractionEnabled = false bottomView.isUserInteractionEnabled = false UIView.animate(withDuration: 0.25, animations: { self.resetToDefaultLayout() }, completion: { _ in UIView.animate(withDuration: 0.25, animations: { self.overlay.cropBoxAlpha = 1 self.overlay.blur = true }, completion: { _ in self.topBar.isUserInteractionEnabled = true self.bottomView.isUserInteractionEnabled = true }) }) } @objc func flipButtonPressed(_: UIButton) { flip() } @objc func rotateButtonPressed(_: UIButton) { rotate90degrees() } @objc func aspectRationButtonPressed(_ sender: UIButton) { sender.isSelected = !sender.isSelected angleRuler.isHidden = sender.isSelected aspectRatioPicker.isHidden = !sender.isSelected } // MARK: - Private Methods open var cropBoxFrame: CGRect { get { return overlay.cropBoxFrame } set { overlay.cropBoxFrame = safeCropBoxFrame(newValue) } } open func resetToDefaultLayout() { let margin: CGFloat = 20 topBar.frame = CGRect(x: 0, y: 0, width: view.width, height: view.safeAreaInsets.top + barHeight) toolbar.size = CGSize(width: view.width, height: view.safeAreaInsets.bottom + barHeight) bottomView.size = CGSize(width: view.width, height: toolbar.height + angleRuler.height + margin) bottomView.bottom = view.height toolbar.bottom = bottomView.height angleRuler.bottom = toolbar.top - margin aspectRatioPicker.frame = angleRuler.frame let topHeight = topBar.isHidden ? view.safeAreaInsets.top : topBar.height let toolbarHeight = toolbar.isHidden ? view.safeAreaInsets.bottom : toolbar.height let bottomHeight = (angleRuler.isHidden && aspectRatioPicker.isHidden) ? toolbarHeight : bottomView.height cropRegionInsets = UIEdgeInsets(top: cropContentInset.top + topHeight, left: cropContentInset.left + view.safeAreaInsets.left, bottom: cropContentInset.bottom + bottomHeight, right: cropContentInset.right + view.safeAreaInsets.right) maxCropRegion = CGRect(x: cropRegionInsets.left, y: cropRegionInsets.top, width: view.width - cropRegionInsets.left - cropRegionInsets.right, height: view.height - cropRegionInsets.top - cropRegionInsets.bottom) defaultCropBoxCenter = CGPoint(x: view.width / 2.0, y: cropRegionInsets.top + maxCropRegion.size.height / 2.0) defaultCropBoxSize = { var size: CGSize let scaleW = self.originalImage.size.width / self.maxCropRegion.size.width let scaleH = self.originalImage.size.height / self.maxCropRegion.size.height let scale = max(scaleW, scaleH) size = CGSize(width: self.originalImage.size.width / scale, height: self.originalImage.size.height / scale) return size }() backgroundView.frame = view.bounds scrollViewContainer.frame = CGRect(x: 0, y: topHeight, width: view.width, height: view.height - topHeight - bottomHeight) scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = 20 scrollView.zoomScale = 1 scrollView.transform = .identity scrollView.bounds = CGRect(x: 0, y: 0, width: defaultCropBoxSize.width, height: defaultCropBoxSize.height) scrollView.contentSize = defaultCropBoxSize scrollView.contentOffset = .zero scrollView.center = backgroundView.convert(defaultCropBoxCenter, to: scrollViewContainer) imageView.transform = .identity imageView.frame = scrollView.bounds overlay.frame = backgroundView.bounds overlay.cropBoxFrame = CGRect(center: defaultCropBoxCenter, size: defaultCropBoxSize) straightenAngle = 0 rotationAngle = 0 flipAngle = 0 aspectRatioLocked = false currentAspectRatioValue = 1 if isCircular { isCropBoxPanEnabled = false overlay.isCircular = true topBar.isHidden = true aspectRatioPicker.isHidden = true angleRuler.isHidden = true cropBoxFrame = CGRect(center: defaultCropBoxCenter, size: CGSize(width: maxCropRegion.size.width, height: maxCropRegion.size.width)) matchScrollViewAndCropView() } else { if originalImage.size.width / originalImage.size.height < cropBoxMinSize / maxCropRegion.size.height { // very long cropBoxFrame = CGRect(x: (view.width - cropBoxMinSize) / 2, y: cropRegionInsets.top, width: cropBoxMinSize, height: maxCropRegion.size.height) matchScrollViewAndCropView() } else if originalImage.size.height / originalImage.size.width < cropBoxMinSize / maxCropRegion.size.width { // very wide cropBoxFrame = CGRect(x: cropRegionInsets.left, y: cropRegionInsets.top + (maxCropRegion.size.height - cropBoxMinSize) / 2, width: maxCropRegion.size.width, height: cropBoxMinSize) matchScrollViewAndCropView() } } defaultCropperState = saveState() angleRuler.value = 0 if overlay.cropBoxFrame.size.width > overlay.cropBoxFrame.size.height { aspectRatioPicker.aspectRatios = verticalAspectRatios.map { $0.rotated } } else { aspectRatioPicker.aspectRatios = verticalAspectRatios } aspectRatioPicker.rotated = false aspectRatioPicker.selectedAspectRatio = .freeForm updateButtons() } func updateButtons() { if let toolbar = self.toolbar as? Toolbar { toolbar.resetButton.isHidden = isCurrentlyInDefalutState if initialState != nil { toolbar.doneButton.isEnabled = !isCurrentlyInInitialState } else { toolbar.doneButton.isEnabled = true//!isCurrentlyInDefalutState } } } func scrollViewZoomScaleToBounds() -> CGFloat { let scaleW = scrollView.bounds.size.width / imageView.bounds.size.width let scaleH = scrollView.bounds.size.height / imageView.bounds.size.height return max(scaleW, scaleH) } func willSetScrollViewZoomScale(_ zoomScale: CGFloat) { if zoomScale > scrollView.maximumZoomScale { scrollView.maximumZoomScale = zoomScale } if zoomScale < scrollView.minimumZoomScale { scrollView.minimumZoomScale = zoomScale } } func photoTranslation() -> CGPoint { let rect = imageView.convert(imageView.bounds, to: view) let point = CGPoint(x: rect.origin.x + rect.size.width / 2, y: rect.origin.y + rect.size.height / 2) let zeroPoint = CGPoint(x: view.frame.width / 2, y: defaultCropBoxCenter.y) return CGPoint(x: point.x - zeroPoint.x, y: point.y - zeroPoint.y) } public static let overlayCropBoxFramePlaceholder: CGRect = .zero public func matchScrollViewAndCropView(animated: Bool = false, targetCropBoxFrame: CGRect = overlayCropBoxFramePlaceholder, extraZoomScale: CGFloat = 1.0, blurLayerAnimated: Bool = false, animations: (() -> Void)? = nil, completion: (() -> Void)? = nil) { var targetCropBoxFrame = targetCropBoxFrame if targetCropBoxFrame.equalTo(CropperViewController.overlayCropBoxFramePlaceholder) { targetCropBoxFrame = overlay.cropBoxFrame } let scaleX = maxCropRegion.size.width / targetCropBoxFrame.size.width let scaleY = maxCropRegion.size.height / targetCropBoxFrame.size.height let scale = min(scaleX, scaleY) // calculate the new bounds of crop view let newCropBounds = CGRect(x: 0, y: 0, width: scale * targetCropBoxFrame.size.width, height: scale * targetCropBoxFrame.size.height) // calculate the new bounds of scroll view let rotatedRect = newCropBounds.applying(CGAffineTransform(rotationAngle: totalAngle)) let width = rotatedRect.size.width let height = rotatedRect.size.height let cropBoxFrameBeforeZoom = targetCropBoxFrame let zoomRect = view.convert(cropBoxFrameBeforeZoom, to: imageView) // zoomRect is base on imageView when scrollView.zoomScale = 1 let center = CGPoint(x: zoomRect.origin.x + zoomRect.size.width / 2, y: zoomRect.origin.y + zoomRect.size.height / 2) let normalizedCenter = CGPoint(x: center.x / (imageView.width / scrollView.zoomScale), y: center.y / (imageView.height / scrollView.zoomScale)) UIView.animate(withDuration: animated ? 0.25 : 0, animations: { self.overlay.setCropBoxFrame(CGRect(center: self.defaultCropBoxCenter, size: newCropBounds.size), blurLayerAnimated: blurLayerAnimated) animations?() self.scrollView.bounds = CGRect(x: 0, y: 0, width: width, height: height) var zoomScale = scale * self.scrollView.zoomScale * extraZoomScale let scrollViewZoomScaleToBounds = self.scrollViewZoomScaleToBounds() if zoomScale < scrollViewZoomScaleToBounds { // Some are not image in the cropbox area zoomScale = scrollViewZoomScaleToBounds } if zoomScale > self.scrollView.maximumZoomScale { // Only rotate can make maximumZoomScale to get bigger zoomScale = self.scrollView.maximumZoomScale } self.willSetScrollViewZoomScale(zoomScale) self.scrollView.zoomScale = zoomScale let contentOffset = CGPoint(x: normalizedCenter.x * self.imageView.width - self.scrollView.bounds.size.width * 0.5, y: normalizedCenter.y * self.imageView.height - self.scrollView.bounds.size.height * 0.5) self.scrollView.contentOffset = self.safeContentOffsetForScrollView(contentOffset) }, completion: { _ in completion?() }) manualZoomed = true } func safeContentOffsetForScrollView(_ contentOffset: CGPoint) -> CGPoint { var contentOffset = contentOffset contentOffset.x = max(contentOffset.x, 0) contentOffset.y = max(contentOffset.y, 0) if scrollView.contentSize.height - contentOffset.y <= scrollView.bounds.size.height { contentOffset.y = scrollView.contentSize.height - scrollView.bounds.size.height } if scrollView.contentSize.width - contentOffset.x <= scrollView.bounds.size.width { contentOffset.x = scrollView.contentSize.width - scrollView.bounds.size.width } return contentOffset } func safeCropBoxFrame(_ cropBoxFrame: CGRect) -> CGRect { var cropBoxFrame = cropBoxFrame // Upon init, sometimes the box size is still 0, which can result in CALayer issues if cropBoxFrame.size.width < .ulpOfOne || cropBoxFrame.size.height < .ulpOfOne { return CGRect(center: defaultCropBoxCenter, size: defaultCropBoxSize) } // clamp the cropping region to the inset boundaries of the screen let contentFrame = maxCropRegion let xOrigin = contentFrame.origin.x let xDelta = cropBoxFrame.origin.x - xOrigin cropBoxFrame.origin.x = max(cropBoxFrame.origin.x, xOrigin) if xDelta < -.ulpOfOne { // If we clamp the x value, ensure we compensate for the subsequent delta generated in the width (Or else, the box will keep growing) cropBoxFrame.size.width += xDelta } let yOrigin = contentFrame.origin.y let yDelta = cropBoxFrame.origin.y - yOrigin cropBoxFrame.origin.y = max(cropBoxFrame.origin.y, yOrigin) if yDelta < -.ulpOfOne { cropBoxFrame.size.height += yDelta } // given the clamped X/Y values, make sure we can't extend the crop box beyond the edge of the screen in the current state let maxWidth = (contentFrame.size.width + contentFrame.origin.x) - cropBoxFrame.origin.x cropBoxFrame.size.width = min(cropBoxFrame.size.width, maxWidth) let maxHeight = (contentFrame.size.height + contentFrame.origin.y) - cropBoxFrame.origin.y cropBoxFrame.size.height = min(cropBoxFrame.size.height, maxHeight) // Make sure we can't make the crop box too small cropBoxFrame.size.width = max(cropBoxFrame.size.width, cropBoxMinSize) cropBoxFrame.size.height = max(cropBoxFrame.size.height, cropBoxMinSize) return cropBoxFrame } } // MARK: UIScrollViewDelegate extension CropperViewController: UIScrollViewDelegate { public func viewForZooming(in _: UIScrollView) -> UIView? { return imageView } public func scrollViewWillBeginZooming(_: UIScrollView, with _: UIView?) { cancelStasis() overlay.blur = false overlay.gridLinesAlpha = 1 topBar.isUserInteractionEnabled = false bottomView.isUserInteractionEnabled = false } public func scrollViewDidEndZooming(_: UIScrollView, with _: UIView?, atScale _: CGFloat) { matchScrollViewAndCropView(animated: true, completion: { self.stasisAndThenRun { UIView.animate(withDuration: 0.25, animations: { self.overlay.gridLinesAlpha = 0 self.overlay.blur = true }, completion: { _ in self.topBar.isUserInteractionEnabled = true self.bottomView.isUserInteractionEnabled = true self.updateButtons() }) self.manualZoomed = true } }) } public func scrollViewWillBeginDragging(_: UIScrollView) { cancelStasis() overlay.blur = false overlay.gridLinesAlpha = 1 topBar.isUserInteractionEnabled = false bottomView.isUserInteractionEnabled = false } public func scrollViewDidEndDragging(_: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { matchScrollViewAndCropView(animated: true, completion: { self.stasisAndThenRun { UIView.animate(withDuration: 0.25, animations: { self.overlay.gridLinesAlpha = 0 self.overlay.blur = true }, completion: { _ in self.topBar.isUserInteractionEnabled = true self.bottomView.isUserInteractionEnabled = true self.updateButtons() }) } }) } } public func scrollViewDidEndDecelerating(_: UIScrollView) { matchScrollViewAndCropView(animated: true, completion: { self.stasisAndThenRun { UIView.animate(withDuration: 0.25, animations: { self.overlay.gridLinesAlpha = 0 self.overlay.blur = true }, completion: { _ in self.topBar.isUserInteractionEnabled = true self.bottomView.isUserInteractionEnabled = true self.updateButtons() }) } }) } } // MARK: UIGestureRecognizerDelegate extension CropperViewController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == cropBoxPanGesture { guard isCropBoxPanEnabled else { return false } let tapPoint = gestureRecognizer.location(in: view) let frame = overlay.cropBoxFrame let d = cropBoxHotArea / 2.0 let innerFrame = frame.insetBy(dx: d, dy: d) let outerFrame = frame.insetBy(dx: -d, dy: -d) if innerFrame.contains(tapPoint) || !outerFrame.contains(tapPoint) { return false } } return true } } // MARK: AspectRatioPickerDelegate extension CropperViewController: AspectRatioPickerDelegate { func aspectRatioPickerDidSelectedAspectRatio(_ aspectRatio: AspectRatio) { setAspectRatio(aspectRatio) } } // MARK: Add capability from protocols extension CropperViewController: Stasisable, AngleAssist, CropBoxEdgeDraggable, AspectRatioSettable {}
38.491252
196
0.642295
01f446ecc2059703cea735b628c1ebed2176af07
767
// // WeatherServiceMock.swift // Weather App IITests // // Created by Sylvan Ash on 16/09/2020. // Copyright © 2020 Sylvan Ash. All rights reserved. // @testable import Weather_App_II class WebServiceMock: WebService { private(set) var didCallFetchForecast = false private(set) var location: String? var didSucceed = false override func fetchForecast(location: String?, completion: @escaping (Result<[Forecast], Error>) -> Void) { didCallFetchForecast = true self.location = location if didSucceed { let forecasts = DataHelper.getMockForecasts() completion(.success(forecasts)) } else { let error = MockError.failed completion(.failure(error)) } } }
26.448276
111
0.646675
eb9b8ab460c54699811b245c4e43fb4fc9d96996
2,285
import SwiftUI struct SettingsView: View { @State var darkMode = false @State var selection = 1 @State var firstDay = WeekDay.Sunday @State var inAppSound = true @State var need = Need.Required var body: some View { Form { Section(header: SectionHeader(title: "Settings")){ Toggle(isOn: $darkMode){ Text("Dark Mode") } Picker( selection: $selection, label: Text("Privacy Look") ) { ForEach(1...2, id: \.self){ value in Text(String(value == 1)) } } Picker( selection: $firstDay, label: Text("First Day of the Week") ) { ForEach(WeekDay.allCases, id: \.self){ Text($0.id).tag($0) } } } Section { Toggle(isOn: $inAppSound){ Text("In App Sound") } Picker( selection: $need, label: Text("App Badge") ) { ForEach(Need.allCases, id: \.self) { Text($0.id).tag($0) } } NavigationLink("Notifications", destination: EmptyView()) } Section(header: SectionHeader(title: "Application")) { NavigationLink("Upgrade to Premium", destination: EmptyView()) NavigationLink("Subscription info", destination: EmptyView()) NavigationLink("About App", destination: EmptyView()) } } .navigationBarTitleDisplayMode(.inline) .navigationBarItems(trailing: Button(action: {}){ Image(systemName:"plus.circle.fill") .foregroundColor(.gray) }) } } fileprivate struct SectionHeader: View { var title: String var body: some View { Text(title) .font(.largeTitle) .fontWeight(.light) .textCase(.none) .padding(.leading) } } enum WeekDay: String, Identifiable, CaseIterable { var id: String { rawValue } case Saturday case Sunday case Monday case Tuesday case Wednesday case Thursday case Friday } enum Need: String,Identifiable, CaseIterable { var id: String { rawValue } case Required case Optional case None } struct SettingsView_Previews: PreviewProvider { static var previews: some View { NavigationView { SettingsView() } } }
20.963303
70
0.577243
abb6329bba88b57f2777e655e550cd69f7fb6fe0
219
// // WeatherRoot.swift // Hava Durumu // // Created by Can Balkaya on 8/19/20. // Copyright © 2020 TurkishKit. All rights reserved. // import Foundation struct Weather: Codable { // MARK: - Properties }
14.6
53
0.648402
8751ee62ec84e011197fa884d7a33a8cb18cf3de
6,012
// // SumTextInputFormatterCaretPositionCalculator.swift // AnyFormatKit // // Created by branderstudio on 20.06.2019. // Copyright © 2019 BRANDERSTUDIO. All rights reserved. // import Foundation class SumTextInputFormatterCaretPositionCalculator { let prefix: String? let suffix: String? let decimalSeparator: String init(decimalSeparator: String, suffix: String?, prefix: String?) { self.prefix = prefix self.suffix = suffix self.decimalSeparator = decimalSeparator } func calculateCaretOffset( range: NSRange, replacementText: String, unformattedRange: NSRange, currentFormattedText: String, newFormattedText: String, currentUnformattedText: String, newUnformattedText: String) -> Int { let isInsert = range.length == 0 && !replacementText.isEmpty let isDelete = range.length != 0 && replacementText.isEmpty if isInsert { return calculateCaretPositionForInsert(range: range, replacementText: replacementText, unformattedRange: unformattedRange, currentFormattedText: currentFormattedText, newFormattedText: newFormattedText, currentUnformattedText: currentUnformattedText, newUnformattedText: newUnformattedText) } else if isDelete { return calculateCaretPositionForDelete(range: range, newFormattedText: newFormattedText, unformattedRange: unformattedRange) } else { // isReplace return calculateCaretPositionForReplace(range: range, currentFormattedText: currentFormattedText, newFormattedText: newFormattedText) } } // for insert private func calculateCaretPositionForInsert( range: NSRange, replacementText: String, unformattedRange: NSRange, currentFormattedText: String, newFormattedText: String, currentUnformattedText: String, newUnformattedText: String) -> Int { let differenceCount = newFormattedText.count - currentFormattedText.count if differenceCount == 0 { if currentFormattedText == newFormattedText { return range.location } else { if range.location + replacementText.count > (newFormattedText.count - (suffix ?? "").count) { return newFormattedText.count - (suffix ?? "").count } else { if currentUnformattedText.hasPrefix("0") { return range.location } else { return range.location + replacementText.count } } } } else { let prefixLength = prefix?.count ?? 0 var result = 0 if let suffix = suffix, !suffix.isEmpty, newFormattedText.hasSuffix(suffix), range.location == currentFormattedText.count { result = findIndexOfNumberSymbol(numberOfSymolsFromEnd: currentFormattedText.count - range.location, newFormattedText: newFormattedText) + 1 - suffix.count } else if currentFormattedText.isEmpty { return newFormattedText.count } else if range.location == currentFormattedText.count { result = findIndexOfNumberSymbol(numberOfSymolsFromEnd: currentFormattedText.count - range.location, newFormattedText: newFormattedText) + 1 } else { result = findIndexOfNumberSymbol(numberOfSymolsFromEnd: currentFormattedText.count - range.location, newFormattedText: newFormattedText) } if range.location < prefixLength { result += prefixLength - range.location } return result } } private func findIndexOfNumberSymbol(numberOfSymolsFromEnd: Int, newFormattedText: String) -> Int { var numberSymbolsCount = 0 for (index, _) in newFormattedText.enumerated().reversed() { numberSymbolsCount += 1 if numberSymbolsCount >= numberOfSymolsFromEnd { return index } } return 0 } // for delete private func calculateCaretPositionForDelete(range: NSRange, newFormattedText: String, unformattedRange: NSRange) -> Int { if let prefix = prefix, !prefix.isEmpty, newFormattedText.hasPrefix(prefix), range.location <= prefix.count { return range.location } else if unformattedRange.location == 0 { return findIndexOfNumberSymbol(numberOfSymbolsBefore: unformattedRange.location, newFormattedText: newFormattedText) } else { return findIndexOfNumberSymbol(numberOfSymbolsBefore: unformattedRange.location, newFormattedText: newFormattedText) + 1 } } private func findIndexOfNumberSymbol(numberOfSymbolsBefore: Int, newFormattedText: String) -> Int { var numberSymbolsCount = 0 for (index, character) in newFormattedText.enumerated() { if isDigit(character: character) || character == decimalSeparator.first || (!(suffix ?? "").isEmpty && (suffix ?? "").contains(character)) { numberSymbolsCount += 1 } if numberSymbolsCount >= numberOfSymbolsBefore { return index } } return 0 } // for replace private func calculateCaretPositionForReplace(range: NSRange, currentFormattedText: String, newFormattedText: String) -> Int { var result = 0 let rangeLocation = range.location + range.length if rangeLocation == currentFormattedText.count { result = findReplaceIndexOfNumberSymbol(numberOfSymolsFromEnd: currentFormattedText.count - rangeLocation, newFormattedText: newFormattedText) + 1 } else { result = findReplaceIndexOfNumberSymbol(numberOfSymolsFromEnd: currentFormattedText.count - rangeLocation, newFormattedText: newFormattedText) } return result } private func findReplaceIndexOfNumberSymbol(numberOfSymolsFromEnd: Int, newFormattedText: String) -> Int { var numberSymbolsCount = 0 for (index, _) in newFormattedText.enumerated().reversed() { numberSymbolsCount += 1 if numberSymbolsCount >= numberOfSymolsFromEnd { return index } } return 0 } private func isDigit(character: Character) -> Bool { guard let scalar = String(character).unicodeScalars.first else { return false } return CharacterSet.decimalDigits.contains(scalar) } }
39.552632
296
0.714737
14200218625d9bbcbc5fb59e37c13f8c3e2bc3f2
703
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse ide func f<Int](b, Any, AnyObject.c<b(A, c() -> { }))) { init<d) -> T, Any) -> (array: a<T where h, b where I) -> : A, g<j : $0] = { } let h : b: Int) { c] = .b("""") } class A { protocol A { } private let v: b : C(a() typealias b : I) -> String) typealias d<d { class A { } } func i() let b = f.d = { }(i<d<T)
26.037037
78
0.630156
229a987e480058ecd000d216d8b775824f8bc21a
2,198
// // YYxErrorHandler.swift // asdada // // Created by young lu on 2019/2/6. // Copyright © 2019 young lu. All rights reserved. // import Foundation enum ErroTyperMsg:String { case OptionalError = "qqqq option is fail" case GuardError = "qqqq guard is fail" case ConvertError = "qqqq convert is error" case NoInsatantObjectError = "yyx there is no element" case doCatchError = "yyx do-catch fail" case OtherError = "qqqq OtherError" case hasNoFile = "qqqq hasNoFile" } struct YYxErrorHandler { private static var fileName:String{ return #file.components(separatedBy: "/").last ?? ErroTyperMsg.OptionalError.rawValue } static func giveMeTroubleLocation<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) -> String{ return "\n\(fileName), \(function), \(line), \(Date())\n\(message)\n" } static func printFailMsg<T>(_ message: T, file: String = #file, function: String = #function, line: Int = #line) { Swift.print("\n\(fileName), \(function), \(line), \(Date())\n\(message)\n") } static func printGuardFail(function:String = #function,line:Int = #line){ Swift.print("\n\(fileName), \(function), \(line),\n\(ErroTyperMsg.GuardError.rawValue)\n") } static func printOptionFail(function:String = #function,line:Int = #line){ Swift.print("\n\(fileName), \(function), \(line),\n\(ErroTyperMsg.OptionalError.rawValue)\n") } static func printConvertErrorFail(function:String = #function,line:Int = #line){ Swift.print("\n\(fileName), \(function), \(line),\n\(ErroTyperMsg.ConvertError.rawValue)\n") } static func printDoCatchErrorFail(function:String = #function,line:Int = #line){ Swift.print("\n\(fileName), \(function), \(line),\n\(ErroTyperMsg.doCatchError.rawValue)\n") } static func addAseert(erroTyperMsg:ErroTyperMsg) { assert(true, YYxErrorHandler.giveMeTroubleLocation(erroTyperMsg.rawValue)) } static func printTestLog(withMark:String = "$$",witchStep:Int,message:String){ Swift.print(withMark + witchStep.convertToString() + withMark + ":::" + message) } }
42.269231
136
0.66151
89f2d970f97013167f546731c1bfac812f91bd74
323
// // Created by Yaroslav Zhurakovskiy // Copyright © 2019-2020 Yaroslav Zhurakovskiy. All rights reserved. // public struct ProblemID { public let questionID: Int public let slug: String public init(questionID: Int, slug: String) { self.questionID = questionID self.slug = slug } }
21.533333
69
0.662539
18a29b87d1bd5bd0d1e54d3ba6499ef1c12d8ae8
1,303
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "FYPhoto", defaultLocalization: "en", platforms: [ .iOS(.v11) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "FYPhoto", targets: ["FYPhoto"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/SDWebImage/SDWebImage.git", from: "5.1.0"), .package(url: "https://github.com/T2Je/FYVideoCompressor.git", from: "0.0.1") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "FYPhoto", dependencies: [ "SDWebImage", "FYVideoCompressor" ], path: "Sources"), .testTarget( name: "FYPhotoTests", dependencies: ["FYPhoto"], path: "Tests") ], swiftLanguageVersions: [.v5] )
32.575
117
0.617805
29a00f333b03c85f976dba735663a1f6fa80bfa4
2,639
// // UsersNetwork.swift // OneExample // // Created by Robin Enhorn on 2020-03-02. // Copyright © 2020 Enhorn. All rights reserved. // import Foundation import OneNetwork class UsersNetwork: OneNetwork { struct Page: Codable { enum CodingKeys: String, CodingKey { case pageNumber = "page" case perPage = "per_page" case totalPages = "total_pages" case total case users = "data" } let pageNumber: Int let perPage: Int let totalPages: Int let total: Int let users: [User] } private var currentFetches: Set<Int> = [] private var pages: [Page] = [] { didSet { updateUsersList() } } @Published private(set) var users: [User] = [] { willSet { objectWillChange.send() } } private let token: LoginToken init(token: LoginToken, authentication: Authentication, cache: OneCache? = nil) { self.token = token super.init(authentication: authentication, cache: cache) } func fetchIfNeeded(page: Int) { guard !currentFetches.contains(page), !pages.contains(where: { $0.pageNumber == page }) else { return } currentFetches.insert(page) get(request: URLRequest(url: usersURL(page: page))) { [weak self] (result: Page?) in self?.currentFetches.remove(page) guard let page = result else { return } self?.pages.append(page) }.ifFailed { [weak self] _ in self?.currentFetches.remove(page) } } func preloadAdjacentPages(to user: User) { guard let page = page(holding: user) else { return } if let previous = page.previousPage { fetchIfNeeded(page: previous) } if let next = page.nextPage { fetchIfNeeded(page: next) } } } private extension UsersNetwork { func usersURL(page: Int) -> URL { switch authentication { case .none, .custom: return .users(token: token, page: page) case .bearer: return .users(page: page) } } func page(holding user: User) -> Page? { return pages.first { $0.users.contains(user) } } func updateUsersList() { users = pages.sorted(by: { $0.pageNumber < $1.pageNumber }).reduce([]) { current, page in return current + page.users } } } private extension UsersNetwork.Page { var previousPage: Int? { pageNumber > 1 ? pageNumber-1 : nil } var nextPage: Int? { pageNumber < totalPages ? pageNumber+1 : nil } }
24.211009
111
0.577113
ffbafbc0e504c278917cdd02f45f901fa68eac46
60,107
// // AutomergeTest.swift // Automerge // // Created by Lukas Schmidt on 25.05.20. // import Foundation import XCTest import Automerge // /test/test.js class AutomergeTest: XCTestCase { // should initially be an empty map func testInit1() { struct Scheme: Codable, Equatable {} let document = Document(Scheme()) XCTAssertEqual(document.content, Scheme()) } // should allow instantiating from an existing object func testInit2() { struct Scheme: Codable, Equatable { struct Birds: Codable, Equatable { let wrens: Int; let magpies: Int } let birds: Birds } let initialState = Scheme(birds: .init(wrens: 3, magpies: 4)) let document = Document(initialState) XCTAssertEqual(document.content, initialState) } // should allow passing an actorId when instantiating from an existing object func testInit4() { struct Scheme: Codable, Equatable {} let actor = Actor() let document = Document(Scheme(), actor: actor) XCTAssertEqual(document.actor, actor) } // // should not enable undo after init // func testInit5() { // struct Scheme: Codable, Equatable {} // let document = Document(Scheme()) // XCTAssertFalse(document.canUndo) // } // should not mutate objects func testSerialUse1() { struct Scheme: Codable, Equatable { var foo: String?} let s1 = Document(Scheme(foo: nil)) var s2 = s1 s2.change { $0.foo?.set("bar") } XCTAssertEqual(s1.content.foo, nil) XCTAssertEqual(s2.content.foo, "bar") } // should not register any conflicts on repeated assignment func testSerialUse2() { struct Scheme: Codable, Equatable { var foo: String?} var s1 = Document(Scheme(foo: nil)) s1.change { $0.foo?.set("bar") } XCTAssertNil(s1.rootProxy().conflicts(dynamicMember: \.foo)) s1.change { $0.foo?.set("bar") } XCTAssertNil(s1.rootProxy().conflicts(dynamicMember: \.foo)) s1.change { $0.foo?.set("bar") } XCTAssertNil(s1.rootProxy().conflicts(dynamicMember: \.foo)) } // should group several changes func testSerialUseChanges1() { struct Scheme: Codable, Equatable { let first: String?; let second: String? } let s1 = Document(Scheme(first: nil, second: nil)) var s2 = s1 s2.change { doc in doc.first.set("one") XCTAssertEqual(doc.first.get(), "one") doc.second.set("two") XCTAssertEqual(doc.get(), Scheme(first: "one", second: "two")) } XCTAssertEqual(s1.content, Scheme(first: nil, second: nil)) XCTAssertEqual(s2.content, Scheme(first: "one", second: "two")) } // should allow repeated reading and writing of values func testSerialUseChanges2() { struct Scheme: Codable, Equatable { var value: String? } let s1 = Document(Scheme(value: nil)) var s2 = s1 s2.change { doc in doc.value.set("a") XCTAssertEqual(doc.value.get(), "a") doc.value.set("b") doc.value.set("c") XCTAssertEqual(doc.value.get(), "c") } XCTAssertEqual(s1.content, Scheme(value: nil)) XCTAssertEqual(s2.content, Scheme(value: "c")) } // should not record conflicts when writing the same field several times within one change func testSerialUseChanges3() { struct Scheme: Codable, Equatable { var value: String? } let s1 = Document(Scheme(value: nil)) var s2 = s1 s2.change { doc in doc.value.set("a") doc.value.set("b") doc.value.set("c") } XCTAssertEqual(s2.content, Scheme(value: "c")) XCTAssertNil(s1.rootProxy().conflicts(dynamicMember: \.value)) } // should return the unchanged state object if nothing changed func testSerialUseChanges4() { struct Scheme: Codable, Equatable { var value: String? } var s1 = Document(Scheme(value: nil)) s1.change { _ in } XCTAssertEqual(s1.content, Scheme(value: nil)) } // should support Date objects in maps func testSerialUseChanges5() { struct Scheme: Codable, Equatable { var now: Date } let now = Date(timeIntervalSince1970: 0) let now2 = Date(timeIntervalSince1970: 2) var s1 = Document(Scheme(now: now)) s1.change { $0.now.set(now2) } let s2 = Document<Scheme>(changes: s1.allChanges()) XCTAssertEqual(s2.content.now, now2) } // should support URL objects in maps func testSerialUseChanges6() { struct Scheme: Codable, Equatable { var url: URL? } let url = URL(string: "automerge.com") let url2 = URL(string: "automerge.com/test") var s1 = Document(Scheme(url: url)) s1.change { $0.url.set(url2) } let s2 = Document<Scheme>(changes: s1.allChanges()) XCTAssertEqual(s2.content.url, url2) } // should support Date objects in lists func testSerialUseChanges7() { struct Scheme: Codable, Equatable { var list: [Date] } let now = Date(timeIntervalSince1970: 0) let now2 = Date(timeIntervalSince1970: 2) var s1 = Document(Scheme(list: [now])) s1.change { $0.list.set([now2]) } let s2 = Document<Scheme>(changes: s1.allChanges()) XCTAssertEqual(s2.content.list, [now2]) } // should support URL objects in lists func testSerialUseChanges8() { struct Scheme: Codable, Equatable { var list: [URL?]? } let url = URL(string: "automerge.com") let url2 = URL(string: "automerge.com/test") var s1 = Document(Scheme(list: [url])) s1.change { $0.list.set([url2]) } let s2 = Document<Scheme>(changes: s1.allChanges()) XCTAssertEqual(s2.content.list, [url2]) } // should handle single-property assignment func testSerialUseRootObject1() { struct Scheme: Codable, Equatable { var foo: String?; var zip: String? } var s1 = Document(Scheme(foo: nil, zip: nil)) s1.change { $0.foo.set("bar") } s1.change { $0.zip.set("zap") } XCTAssertEqual(s1.content.foo, "bar") XCTAssertEqual(s1.content.zip, "zap") XCTAssertEqual(s1.content, Scheme(foo: "bar", zip: "zap")) } // should allow floating-point values func testSerialUseRootObject2() { struct Scheme: Codable, Equatable { var number: Double?; } var s1 = Document(Scheme(number: nil)) s1.change { $0.number.set(1589032171.1) } XCTAssertEqual(s1.content.number, 1589032171.1) } // should handle multi-property assignment func testSerialUseRootObject3() { struct Scheme: Codable, Equatable { var foo: String?; var zip: String? } var s1 = Document(Scheme(foo: nil, zip: nil)) s1.change(message: "multi-assign") { $0.foo.set("bar") $0.zip.set("zap") } XCTAssertEqual(s1.content.foo, "bar") XCTAssertEqual(s1.content.zip, "zap") XCTAssertEqual(s1.content, Scheme(foo: "bar", zip: "zap")) } // should handle root property deletion func testSerialUseRootObject4() { struct Scheme: Codable, Equatable { var foo: String?; var zip: String? } var s1 = Document(Scheme(foo: nil, zip: nil)) s1.change(message: "set foo", { $0.foo.set("bar") $0.zip.set(nil) }) s1.change(message: "del foo", { $0.foo.set(nil) }) XCTAssertEqual(s1.content.foo, nil) XCTAssertEqual(s1.content.zip, nil) XCTAssertEqual(s1.content, Scheme(foo: nil, zip: nil)) } // should assign an objectId to nested maps func testSerialUseNestedMaps1() { struct Scheme: Codable, Equatable { struct Nested: Codable, Equatable {} var nested: Nested? } var s1 = Document(Scheme(nested: nil)) s1.change { $0.nested.set(.init()) } XCTAssertNotEqual(s1.rootProxy().nested?.objectId, "00000000-0000-0000-0000-000000000000") XCTAssertEqual(s1.content, Scheme(nested: .init())) } // should handle assignment of a nested property func testSerialUseNestedMaps2() { struct Scheme: Codable, Equatable { struct Nested: Codable, Equatable { var foo: String?; var one: Int? } var nested: Nested? } var s1 = Document(Scheme(nested: nil)) s1.change { $0.nested.set(.init(foo: nil, one: nil)) $0.nested?.foo.set("bar") } s1.change { $0.nested?.one?.set(1) } XCTAssertEqual(s1.content, Scheme(nested: .init(foo: "bar", one: 1))) XCTAssertEqual(s1.content.nested, .init(foo: "bar", one: 1)) XCTAssertEqual(s1.content.nested?.foo, "bar") XCTAssertEqual(s1.content.nested?.one, 1) } // should handle assignment of an object func testSerialUseNestedMaps3() { struct Scheme: Codable, Equatable { struct Style: Codable, Equatable { let bold: Bool; let fontSize: Int } var style: Style? } var s1 = Document(Scheme(style: nil)) s1.change { $0.style?.set(.init(bold: false, fontSize: 12)) } XCTAssertEqual(s1.content, Scheme(style: .init(bold: false, fontSize: 12))) XCTAssertEqual(s1.content.style, .init(bold: false, fontSize: 12)) XCTAssertEqual(s1.content.style?.bold, false) XCTAssertEqual(s1.content.style?.fontSize, 12) } // should handle assignment of multiple nested properties func testSerialUseNestedMaps4() { struct Scheme: Codable, Equatable { struct Style: Codable, Equatable { let bold: Bool; let fontSize: Int; let typeface: String? } var style: Style? } var s1 = Document(Scheme(style: nil)) s1.change { $0.style?.set(.init(bold: false, fontSize: 12, typeface: nil)) $0.style?.set(.init(bold: true, fontSize: 14, typeface: "Optima")) } XCTAssertEqual(s1.content, Scheme(style: .init(bold: true, fontSize: 14, typeface: "Optima"))) XCTAssertEqual(s1.content.style, .init(bold: true, fontSize: 14, typeface: "Optima")) XCTAssertEqual(s1.content.style?.bold, true) XCTAssertEqual(s1.content.style?.fontSize, 14) XCTAssertEqual(s1.content.style?.typeface, "Optima") } // should handle arbitrary-depth nesting func testSerialUseNestedMaps5() { struct A: Codable, Equatable { var b: B } struct B: Codable, Equatable { var c: C } struct C: Codable, Equatable { var d: D } struct D: Codable, Equatable { var e: E } struct E: Codable, Equatable { var f: F } struct F: Codable, Equatable { var g: String; var i: String? } struct Scheme: Codable, Equatable { var a: A } var s1 = Document(Scheme(a: A(b: B(c: C(d: D(e: E(f: F(g: "h", i: nil)))))))) s1.change { $0.a.b.c.d.e.f.i?.set("j") } XCTAssertEqual(s1.content, Scheme(a: A(b: B(c: C(d: D(e: E(f: F(g: "h", i: "j")))))))) XCTAssertEqual(s1.content.a.b.c.d.e.f.g, "h") XCTAssertEqual(s1.content.a.b.c.d.e.f.i, "j") } // should allow an old object to be replaced with a new one func testSerialUseNestedMaps6() { struct Scheme: Codable, Equatable { struct Pet: Codable, Equatable { let species: String; let legs: Int?; let breed: String?; let colors: [String: Bool]?; let variety: String? } var myPet: Pet? } var s1 = Document(Scheme(myPet: nil)) s1.change { $0.myPet?.set(.init(species: "dog", legs: 4, breed: "dachshund", colors: nil, variety: nil)) } var s2 = s1 s2.change { $0.myPet?.set(.init(species: "koi", legs: nil, breed: nil, colors: ["red": true, "white": true, "black": false], variety: "紅白")) } XCTAssertEqual(s1.content, Scheme(myPet: .init(species: "dog", legs: 4, breed: "dachshund", colors: nil, variety: nil))) XCTAssertEqual(s1.content.myPet?.breed, "dachshund") XCTAssertEqual(s2.content, Scheme(myPet: .init(species: "koi", legs: nil, breed: nil, colors: ["red": true, "white": true, "black": false], variety: "紅白"))) XCTAssertEqual(s2.content.myPet?.breed, nil) XCTAssertEqual(s2.content.myPet?.variety, "紅白") } // should handle deletion of properties within a map func testSerialUseNestedMaps7() { struct Scheme: Codable, Equatable { struct Style: Codable, Equatable { var bold: Bool?; let fontSize: Int; let typeface: String? } var style: Style? } var s1 = Document(Scheme(style: nil)) s1.change { $0.style?.set(.init(bold: false, fontSize: 12, typeface: "Optima")) } s1.change { $0.style?.bold.set(nil) } XCTAssertEqual(s1.content.style, .init(bold: nil, fontSize: 12, typeface: "Optima")) XCTAssertEqual(s1.content.style?.bold, nil) } // should handle deletion of references to a map func testSerialUseNestedMaps8() { struct Scheme: Codable, Equatable { struct Style: Codable, Equatable { var bold: Bool?; let fontSize: Int; let typeface: String? } var style: Style? let title: String } var s1 = Document(Scheme(style: nil, title: "Hello")) s1.change { $0.style?.set(.init(bold: false, fontSize: 12, typeface: "Optima")) } s1.change { $0.style.set(nil) } XCTAssertEqual(s1.content.style, nil) XCTAssertEqual(s1.content, Scheme(style: nil, title: "Hello")) } // should allow elements to be inserted func testSerialUseLists1() { struct Scheme: Codable, Equatable { var noodles: [String] } var s1 = Document(Scheme(noodles: [])) s1.change { $0.noodles.insert(contentsOf: ["udon", "soba"], at: 0) } s1.change { $0.noodles.insert("ramen", at: 1) } XCTAssertEqual(s1.content.noodles, ["udon", "ramen", "soba"]) XCTAssertEqual(s1.content.noodles[0], "udon") XCTAssertEqual(s1.content.noodles[1], "ramen") XCTAssertEqual(s1.content.noodles[2], "soba") XCTAssertEqual(s1.content.noodles.count, 3) } // should handle assignment of a list literal func testSerialUseLists2() { struct Scheme: Codable, Equatable { var noodles: [String] } var s1 = Document(Scheme(noodles: [])) s1.change { $0.noodles.set(["udon", "ramen", "soba"]) } XCTAssertEqual(s1.content, Scheme(noodles: ["udon", "ramen", "soba"])) XCTAssertEqual(s1.content.noodles, ["udon", "ramen", "soba"]) XCTAssertEqual(s1.content.noodles[0], "udon") XCTAssertEqual(s1.content.noodles[1], "ramen") XCTAssertEqual(s1.content.noodles[2], "soba") XCTAssertEqual(s1.content.noodles.count, 3) } // should handle deletion of list elements func testSerialUseLists3() { struct Scheme: Codable, Equatable { var noodles: [String] } var s1 = Document(Scheme(noodles:["udon", "ramen", "soba"])) s1.change { $0.noodles.remove(at: 1) } XCTAssertEqual(s1.content, Scheme(noodles: ["udon", "soba"])) XCTAssertEqual(s1.content.noodles, ["udon", "soba"]) XCTAssertEqual(s1.content.noodles[0], "udon") XCTAssertEqual(s1.content.noodles[1], "soba") XCTAssertEqual(s1.content.noodles.count, 2) } // should handle assignment of individual list indexes func testSerialUseLists4() { struct Scheme: Codable, Equatable { var japaneseFood: [String] } var s1 = Document(Scheme(japaneseFood: ["udon", "ramen", "soba"])) s1.change { $0.japaneseFood[1].set("sushi") } XCTAssertEqual(s1.content, Scheme(japaneseFood: ["udon", "sushi", "soba"])) XCTAssertEqual(s1.content.japaneseFood, ["udon", "sushi", "soba"]) XCTAssertEqual(s1.content.japaneseFood[0], "udon") XCTAssertEqual(s1.content.japaneseFood[1], "sushi") XCTAssertEqual(s1.content.japaneseFood[2], "soba") XCTAssertEqual(s1.content.japaneseFood.count, 3) } // should handle assignment of individual list indexes func testSerialUseLists5() { struct Scheme: Codable, Equatable { var japaneseFood: [String] } var s1 = Document(Scheme(japaneseFood: ["udon", "ramen", "soba"])) s1.change { $0.japaneseFood[0].set("うどん") $0.japaneseFood[2].set("そば") } XCTAssertEqual(s1.content, Scheme(japaneseFood: ["うどん", "ramen", "そば"])) XCTAssertEqual(s1.content.japaneseFood, ["うどん", "ramen", "そば"]) XCTAssertEqual(s1.content.japaneseFood[0], "うどん") XCTAssertEqual(s1.content.japaneseFood[1], "ramen") XCTAssertEqual(s1.content.japaneseFood[2], "そば") XCTAssertEqual(s1.content.japaneseFood.count, 3) } // should handle nested objects func testSerialUseLists6() { struct Noodle: Codable, Equatable { enum TypeNoodle: String, Codable { case ramen, udon } let type: TypeNoodle var dishes: [String] } struct Scheme: Codable, Equatable { var noodles: [Noodle] } var s1 = Document(Scheme(noodles: [.init(type: .ramen, dishes: ["tonkotsu", "shoyu"])])) s1.change { $0.noodles.append(.init(type: .udon, dishes: ["tempura udon"])) } s1.change { $0.noodles[0].dishes.append("miso") } XCTAssertEqual(s1.content, Scheme(noodles: [.init(type: .ramen, dishes: ["tonkotsu", "shoyu", "miso"]), .init(type: .udon, dishes: ["tempura udon"])])) XCTAssertEqual(s1.content.noodles[0], .init(type: .ramen, dishes: ["tonkotsu", "shoyu", "miso"])) XCTAssertEqual(s1.content.noodles[1], .init(type: .udon, dishes: ["tempura udon"])) } // should handle assignment of individual list indexes func testSerialUseLists7() { struct Scheme: Codable, Equatable { var noodles: [String]? var japaneseFood: [String]? } var s1 = Document(Scheme(noodles: ["udon", "soba", "ramen"], japaneseFood: nil)) s1.change { $0.japaneseFood.set($0.noodles?.get()) $0.noodles?.set(["wonton", "pho"]) } XCTAssertEqual(s1.content, Scheme(noodles: ["wonton", "pho"], japaneseFood: ["udon", "soba", "ramen"])) XCTAssertEqual(s1.content.noodles, ["wonton", "pho"]) XCTAssertEqual(s1.content.noodles?[0], "wonton") XCTAssertEqual(s1.content.noodles?[1], "pho") XCTAssertEqual(s1.content.noodles?.count, 2) } // should allow list creation and assignment in the same change callback func testSerialUseLists8() { struct Scheme: Codable, Equatable { var letters: [String] } var s1 = Document(Scheme(letters: [])) s1.change { $0.letters.set(["a", "b", "c"]) $0.letters[1].set("d") } XCTAssertEqual(s1.content, Scheme(letters: ["a", "d", "c"])) XCTAssertEqual(s1.content.letters[1], "d") } // should allow adding and removing list elements in the same change callback func testSerialUseLists9() { struct Scheme: Codable, Equatable { var noodles: [String] } var s1 = Document(Scheme(noodles: [])) s1.change { $0.noodles.append("udon") $0.noodles.remove(at: 0) } XCTAssertEqual(s1.content, Scheme(noodles: [])) // do the add-remove cycle twice, test for #151 (https://github.com/automerge/automerge/issues/151) s1.change { $0.noodles.append("soba") $0.noodles.remove(at: 0) } XCTAssertEqual(s1.content, Scheme(noodles: [])) } // should allow adding and removing list elements in the same change callback func testSerialUseLists10() { struct Scheme: Codable, Equatable { var maze: [[[[[[[[String]]]]]]]] } var s1 = Document(Scheme(maze: [[[[[[[["noodles"]]]]]]]])) s1.change { $0.maze[0][0][0][0][0][0][0].append("found") } XCTAssertEqual(s1.content, Scheme(maze: [[[[[[[["noodles", "found"]]]]]]]])) XCTAssertEqual(s1.content.maze[0][0][0][0][0][0][0][1], "found") } func testSerialUseCounter1() { struct Scheme: Codable, Equatable { var counter: Counter? } var s1 = Document(Scheme(counter: nil)) s1.change { $0.counter?.set(1) } s1.change { $0.counter?.increment(2) } XCTAssertEqual(s1.content, Scheme(counter: 3)) } func testSerialUseCounter2() throws { throw XCTSkip("Fix this once #347 is resolved") // https://github.com/automerge/automerge/pull/347 struct Scheme: Codable, Equatable { var counter: Counter? } let s1 = Document(Scheme(counter: 0)) var s2 = s1 s2.change { $0.counter?.increment(2) $0.counter?.decrement() $0.counter?.increment(3) } XCTAssertEqual(s1.content, Scheme(counter: 0)) XCTAssertEqual(s2.content, Scheme(counter: 4)) } // should merge concurrent updates of different properties func testConcurrentUse1() { struct Scheme: Codable, Equatable { var foo: String?; var hello: String? } let s1 = Document(Scheme(foo: "bar", hello: nil)) let s2 = Document(Scheme(foo: nil, hello: "world")) var s3 = s1 s3.merge(s2) XCTAssertEqual(s3.content.foo, "bar") XCTAssertEqual(s3.content.hello, "world") XCTAssertEqual(s3.content, Scheme(foo: "bar", hello: "world")) XCTAssertNil(s3.rootProxy().conflicts(dynamicMember: \.foo)) XCTAssertNil(s3.rootProxy().conflicts(dynamicMember: \.hello)) } // should add concurrent increments of the same property func testConcurrentUse2() { struct Scheme: Codable, Equatable { var counter: Counter? } var s1 = Document(Scheme(counter: 0)) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.counter?.increment() } s2.change { $0.counter?.increment(2) } var s3 = s1 s3.merge(s2) XCTAssertEqual(s1.content.counter?.value, 1) XCTAssertEqual(s2.content.counter?.value, 2) XCTAssertEqual(s3.content.counter?.value, 3) XCTAssertNil(s3.rootProxy().conflicts(dynamicMember: \.counter)) } // should add increments only to the values they precede func testConcurrentUse3() { struct Scheme: Codable, Equatable { var counter: Counter? } var s1 = Document(Scheme(counter: 0)) s1.change { $0.counter?.increment() } var s2 = Document(Scheme(counter: 100)) s2.change { $0.counter?.increment(3) } var s3 = s1 s3.merge(s2) if s1.actor > s2.actor { XCTAssertEqual(s3.content.counter?.value, 1) } else { XCTAssertEqual(s3.content.counter?.value, 103) } XCTAssertEqual(s3.rootProxy().conflicts(dynamicMember: \.counter), [ "1@\(s1.actor)": 1, "1@\(s2.actor)": 103 ]) } // should detect concurrent updates of the same field func testConcurrentUse4() { struct Scheme: Codable, Equatable { var field: String? } var s1 = Document(Scheme(field: "one")) let s2 = Document(Scheme(field: "two")) s1.merge(s2) if s1.actor > s2.actor { XCTAssertEqual(s1.content.field, "one") } else { XCTAssertEqual(s1.content.field, "two") } XCTAssertEqual(s1.rootProxy().conflicts(dynamicMember: \.field), [ "1@\(s1.actor)": "one", "1@\(s2.actor)": "two" ]) } // should detect concurrent updates of the same field func testConcurrentUse5() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["finch"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.birds[0].set("greenfinch") } s2.change { $0.birds[0].set("goldfinch") } s1.merge(s2) if s1.actor > s2.actor { XCTAssertEqual(s1.content.birds, ["greenfinch"]) } else { XCTAssertEqual(s1.content.birds, ["goldfinch"]) } XCTAssertEqual(s1.rootProxy().birds.conflicts(index: 0), [ "3@\(s1.actor)": "greenfinch", "3@\(s2.actor)": "goldfinch" ]) } // should handle changes within a conflicting list element func testConcurrentUse6() { struct Scheme: Codable, Equatable { struct Obj: Codable, Equatable { var map1: Bool? var map2: Bool? var key: Int? } var list: [Obj] } var s1 = Document(Scheme(list: [.init(map1: false, map2: false, key: 0)])) XCTAssertEqual(s1.content, Scheme(list: [.init(map1: false, map2: false, key: 0)])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.list[0].set(.init(map1: true, map2: nil, key: nil)) } s1.change { $0.list[0].key.set(1) } s2.change { $0.list[0].set(.init(map1: nil, map2: true, key: nil)) } s2.change { $0.list[0].key.set(2) } var s3 = s1 s3.merge(s2) if s1.actor > s2.actor { XCTAssertEqual(s3.content.list, [.init(map1: true, map2: nil, key: 1)]) } else { XCTAssertEqual(s3.content.list, [.init(map1: nil, map2: true, key: 2)]) } XCTAssertEqual(s3.rootProxy().list.conflicts(index: 0), [ "6@\(s1.actor)": .init(map1: true, map2: nil, key: 1), "6@\(s2.actor)": .init(map1: nil, map2: true, key: 2) ]) } // should not merge concurrently assigned nested maps func testConcurrentUse7() { struct Scheme: Codable, Equatable { struct Config: Codable, Equatable { var background: String? var logo_url: String? } var config: Config } let s1 = Document(Scheme(config: .init(background: "blue"))) let s2 = Document(Scheme(config: .init(logo_url: "logo.png"))) var s3 = s1 s3.merge(s2) XCTAssertEqualOneOf(s3.content, Scheme(config: .init(background: "blue")), Scheme(config: .init(logo_url: "logo.png"))) XCTAssertEqual(s3.rootProxy().conflicts(dynamicMember: \.config), [ "1@\(s1.actor)": .init(background: "blue"), "1@\(s2.actor)": .init(logo_url: "logo.png") ]) } // should clear conflicts after assigning a new value func testConcurrentUse8() { struct Scheme: Codable, Equatable { var field: String } let s1 = Document(Scheme(field: "one")) var s2 = Document(Scheme(field: "two")) var s3 = s1 s3.merge(s2) s3.change { $0.field.set("three") } XCTAssertEqual(s3.content, Scheme(field: "three")) s2.merge(s3) XCTAssertEqual(s2.content, Scheme(field: "three")) XCTAssertNil(s2.rootProxy().conflicts(dynamicMember: \.field)) } // should handle concurrent insertions at different list positions func testConcurrentUse9() { struct Scheme: Codable, Equatable { var list: [String] } var s1 = Document(Scheme(list: ["one", "three"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.list.insert("two", at: 1) } s2.change({ $0.list.append("four") }) var s3 = s1 s3.merge(s2) XCTAssertEqual(s3.content, Scheme(list: ["one", "two", "three", "four"])) s2.merge(s3) XCTAssertNil(s2.rootProxy().conflicts(dynamicMember: \.list)) } // should handle concurrent insertions at different list positions func testConcurrentUse10() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["parakeet"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.birds.append("starling") } s2.change({ $0.birds.append("chaffinch") }) var s3 = s1 s3.merge(s2) XCTAssertEqualOneOf(s3.content, Scheme(birds: ["parakeet", "starling", "chaffinch"]), Scheme(birds: ["parakeet", "chaffinch", "starling"])) s2.merge(s3) XCTAssertEqual(s2.content, s3.content) } //should handle concurrent assignment and deletion of a map entry func testConcurrentUse11() { // Add-wins semantics struct Scheme: Codable, Equatable { var bestBird: String? } var s1 = Document(Scheme(bestBird: "robin")) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.bestBird.set(nil) } s2.change { $0.bestBird.set("magpie") } var s3 = s1 s3.merge(s2) XCTAssertEqual(s1.content, Scheme(bestBird: nil)) XCTAssertEqual(s2.content, Scheme(bestBird: "magpie")) XCTAssertEqual(s3.content, Scheme(bestBird: "magpie")) XCTAssertNil(s2.rootProxy().conflicts(dynamicMember: \.bestBird)) } //should handle concurrent assignment and deletion of a list element func testConcurrentUse12() { // Concurrent assignment ressurects a deleted list element. Perhaps a little // surprising, but consistent with add-wins semantics of maps (see test above) struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["blackbird", "thrush", "goldfinch"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.birds[1].set("starling") } s2.change { $0.birds.remove(at: 1) } var s3 = s1 s3.merge(s2) XCTAssertEqual(s1.content, Scheme(birds: ["blackbird", "starling", "goldfinch"])) XCTAssertEqual(s2.content, Scheme(birds: ["blackbird", "goldfinch"])) XCTAssertEqual(s3.content, Scheme(birds: ["blackbird", "starling", "goldfinch"])) } // should handle insertion after a deleted list element func testConcurrentUse13() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["blackbird", "thrush", "goldfinch"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.birds.replaceSubrange(1...2, with: [String]()) } s2.change { $0.birds.insert("starling", at: 2) } var s3 = s1 s3.merge(s2) XCTAssertEqual(s3.content, Scheme(birds: ["blackbird", "starling"])) s2.merge(s3) XCTAssertEqual(s2.content, Scheme(birds: ["blackbird", "starling"])) } // should handle concurrent deletion of the same element func testConcurrentUse14() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["albatross", "buzzard", "cormorant"])) // 1 var s2 = Document<Scheme>(changes: s1.allChanges()) // 0 s1.change { $0.birds.remove(at: 1) } // 2 s2.change { $0.birds.remove(at: 1) } // 1 var s3 = s1 s3.merge(s2) // s3 XCTAssertEqual(s3.content, Scheme(birds: ["albatross", "cormorant"])) } // should handle concurrent deletion of different elements func testConcurrentUse15() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["albatross", "buzzard", "cormorant"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.birds.remove(at: 0) } s2.change { $0.birds.remove(at: 1) } var s3 = s1 s3.merge(s2) XCTAssertEqual(s3.content, Scheme(birds: ["cormorant"])) } // should handle concurrent updates at different levels of the tree func testConcurrentUse16() { struct Scheme: Codable, Equatable { struct Animals: Codable, Equatable { struct Birds: Codable, Equatable { let pink: String let black: String var brown: String? } var birds: Birds? var mammals: [String] } var animals: Animals } var s1 = Document(Scheme(animals: .init(birds: .init(pink: "flamingo", black: "starling", brown: nil), mammals: ["badger"]))) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.animals.birds?.brown?.set("sparrow") } s2.change { $0.animals.birds.set(nil) } var s3 = s1 s3.merge(s2) XCTAssertEqual(s1.content, Scheme(animals: .init(birds: .init(pink: "flamingo", black: "starling", brown: "sparrow"), mammals: ["badger"]))) XCTAssertEqual(s2.content, Scheme(animals: .init(birds: nil, mammals: ["badger"]))) XCTAssertEqual(s3.content, Scheme(animals: .init(birds: nil, mammals: ["badger"]))) } // should not interleave sequence insertions at the same position func testConcurrentUse17() { struct Scheme: Codable, Equatable { var wisdom: [String] } var s1 = Document(Scheme(wisdom: [])) var s2 = Document<Scheme>(changes: s1.allChanges()) s1.change { $0.wisdom.append(contentsOf: ["to", "be", "is", "to", "do"]) } s2.change { $0.wisdom.append(contentsOf: ["to", "do", "is", "to", "be"]) } var s3 = s1 s3.merge(s2) XCTAssertEqualOneOf(s3.content.wisdom, ["to", "be", "is", "to", "do", "to", "do", "is", "to", "be"], ["to", "do", "is", "to", "be", "to", "be", "is", "to", "do"]) // In case you're wondering: http://quoteinvestigator.com/2013/09/16/do-be-do/ } // should handle insertion by greater actor ID func testConcurrentUseMultipleInsertsAtTheSameListPosition1() { struct Scheme: Codable, Equatable { var list: [String] } var s1 = Document(Scheme(list: []), actor: Actor(actorId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) var s2 = Document(Scheme(list: []), actor: Actor(actorId: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) s1.change { $0.list.set(["two"]) } s2.merge(s1) s2.change { $0.list.insert("one", at: 0) } XCTAssertEqual(s2.content.list, ["one", "two"]) } // should handle insertion by lesser actor ID func testConcurrentUseMultipleInsertsAtTheSameListPosition2() { struct Scheme: Codable, Equatable { var list: [String] } var s1 = Document(Scheme(list: []), actor: Actor(actorId: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) var s2 = Document(Scheme(list: []), actor: Actor(actorId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) s1.change { $0.list.set(["two"]) } s2.merge(s1) s2.change { $0.list.insert("one", at: 0) } XCTAssertEqual(s2.content.list, ["one", "two"]) } // should handle insertion by lesser actor ID func testConcurrentUseMultipleInsertsAtTheSameListPosition3() { struct Scheme: Codable, Equatable { var list: [String] } var s1 = Document(Scheme(list: [])) s1.change { $0.list.set(["two"]) } var s2 = Document<Scheme>(changes: s1.allChanges()) s2.change { $0.list.insert("one", at: 0) } XCTAssertEqual(s2.content.list, ["one", "two"]) } // should make insertion order consistent with causality func testConcurrentUseMultipleInsertsAtTheSameListPosition4() { struct Scheme: Codable, Equatable { var list: [String] } var s1 = Document(Scheme(list: ["four"])) var s2 = Document<Scheme>(changes: s1.allChanges()) s2.change { $0.list.insert("three", at: 0) } s1.merge(s2) s1.change { $0.list.insert("two", at: 0) } s2.merge(s1) s2.change { $0.list.insert("one", at: 0) } XCTAssertEqual(s2.content.list, ["one", "two", "three", "four"]) } // // should allow undo if there have been local changes // func testUndo1() { // struct Scheme: Codable, Equatable { // var hello: String? // } // // var s1 = Document(Scheme(hello: nil)) // XCTAssertFalse(s1.canUndo) // s1.change { $0.hello?.set("world") } // XCTAssertTrue(s1.canUndo) // let s2 = Document<Scheme>(changes: s1.allChanges()) // XCTAssertFalse(s2.canUndo) // } // // // should allow undo if there have been local changes // func testUndo2() { // struct Scheme: Codable, Equatable { // var hello: String? // } // // var s1 = Document(Scheme(hello: nil)) // s1.change { $0.hello?.set("world") } // XCTAssertEqual(s1.content, Scheme(hello: "world")) // s1.undo() // XCTAssertEqual(s1.content, Scheme(hello: nil)) // } // // // should undo a field update by reverting to the previous value // func testUndo3() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 3)) // s1.change { $0.value.set(4) } // XCTAssertEqual(s1.content, Scheme(value: 4)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 3)) // } // // // should allow undoing multiple changes // func testUndo4() { // struct Scheme: Codable, Equatable { // var value: Int? // } // // var s1 = Document(Scheme(value: nil)) // s1.change { $0.value.set(1) } // s1.change { $0.value.set(2) } // s1.change { $0.value.set(3) } // XCTAssertEqual(s1.content, Scheme(value: 3)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 2)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 1)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: nil)) // XCTAssertFalse(s1.canUndo) // } // // // should undo only local changes // func testUndo5() { // struct Scheme: Codable, Equatable { // var s1: String? // var s2: String? // } // // var s1 = Document(Scheme(s1: "s1.old", s2: nil)) // s1.change { $0.s1.set("s1.new") } // var s2 = Document<Scheme>(changes: s1.allChanges()) // s2.change { $0.s2?.set("s2") } // // s1.merge(s2) // XCTAssertEqual(s1.content, Scheme(s1: "s1.new", s2: "s2")) // s1.undo() // XCTAssertEqual(s1.content, Scheme(s1: "s1.old", s2: "s2")) // } // // // should apply undos by growing the history // func testUndo6() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 1)) // s1.change(message: "set 2") { $0.value.set(2) } // var s2 = Document<Scheme>(changes: s1.allChanges()) // s1.undo(message: "undo!") // let seqs = History(document: s1).map { $0.change.seq } // XCTAssertEqual(seqs, [1, 2, 3]) // let messages = History(document: s1).map { $0.change.message } // XCTAssertEqual(messages, ["Initialization", "set 2", "undo!"]) // s2.merge(s1) // XCTAssertEqual(s2.content, Scheme(value: 1)) // XCTAssertEqual(s1.content, Scheme(value: 1)) // } // // // should ignore other actors' updates to an undo-reverted field // func testUndo7() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 1)) // s1.change { $0.value.set(2) } // var s2 = Document<Scheme>(changes: s1.allChanges()) // s2.change { $0.value.set(3) } // s1.merge(s2) // XCTAssertEqual(s1.content, Scheme(value: 3)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 1)) // } // // // should undo object creation by removing the link // func testUndo8() { // struct Scheme: Codable, Equatable { // struct Settings: Codable, Equatable { // let background: String // let text: String // } // var settings: Settings? // } // // var s1 = Document(Scheme(settings: nil)) // s1.change { $0.settings.set(.init(background: "white", text: "black")) } // XCTAssertEqual(s1.content, Scheme(settings: .init(background: "white", text: "black"))) // s1.undo() // XCTAssertEqual(s1.content, Scheme(settings: nil)) // } // // // should undo primitive field deletion by setting the old value // func testUndo9() { // struct Scheme: Codable, Equatable { // var k1: String? // var k2: String? // } // // var s1 = Document(Scheme(k1: "v1", k2: "v2")) // s1.change { $0.k2.set(nil) } // XCTAssertEqual(s1.content, Scheme(k1: "v1", k2: nil)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(k1: "v1", k2: "v2")) // } // // // should undo link deletion by linking the old value // func testUndo10() { // struct Scheme: Codable, Equatable { // var fish: [String]? // var birds: [String]? // } // // var s1 = Document(Scheme(fish: ["trout", "sea bass"], birds: nil)) // s1.change { $0.birds.set(["heron", "magpie"]) } // // var s2 = s1 // s2.change { $0.fish.set(nil) } // XCTAssertEqual(s2.content, Scheme(fish: nil, birds: ["heron", "magpie"])) // s2.undo() // XCTAssertEqual(s2.content, Scheme(fish: ["trout", "sea bass"], birds: ["heron", "magpie"])) // } // // // should undo list insertion by removing the new element // func testUndo11() { // struct Scheme: Codable, Equatable { // var list: [String] // } // // var s1 = Document(Scheme(list: ["A", "B", "C"])) // s1.change { $0.list.append("D") } // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C", "D"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C"])) // } // // // should undo list element deletion by re-assigning the old value // func testUndo12() { // struct Scheme: Codable, Equatable { // var list: [String] // } // // var s1 = Document(Scheme(list: ["A", "B", "C"])) // s1.change { $0.list.remove(at: 1) } // XCTAssertEqual(s1.content, Scheme(list: ["A", "C"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C"])) // } // // // should undo counter increments // func testUndo13() { // struct Scheme: Codable, Equatable { // var counter: Counter // } // // var s1 = Document(Scheme(counter: 0)) // s1.change { $0.counter.increment() } // XCTAssertEqual(s1.content, Scheme(counter: 1)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(counter: 0)) // } // // // should allow redo if the last change was an undo // func testRedo1() { // struct Scheme: Codable, Equatable { // var birds: [String] // } // var s1 = Document(Scheme(birds: ["peregrine falcon"])) // s1.change { $0.birds.append("magpie") } // XCTAssertFalse(s1.canRedo) // s1.undo() // XCTAssertTrue(s1.canRedo) // s1.redo() // XCTAssertFalse(s1.canRedo) // } // // // should allow several undos to be matched by several redos // func testRedo2() { // struct Scheme: Codable, Equatable { // var birds: [String] // } // var s1 = Document(Scheme(birds: [])) // s1.change { $0.birds.append("peregrine falcon") } // s1.change { $0.birds.append("sparrowhawk") } // XCTAssertEqual(s1.content, Scheme(birds: ["peregrine falcon", "sparrowhawk"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(birds: ["peregrine falcon"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(birds: [])) // s1.redo() // XCTAssertEqual(s1.content, Scheme(birds: ["peregrine falcon"])) // s1.redo() // XCTAssertEqual(s1.content, Scheme(birds: ["peregrine falcon", "sparrowhawk"])) // } // // // should allow several undos to be matched by several redos // func testRedo3() { // struct Scheme: Codable, Equatable { // var sparrows: Int? // var skylarks: Int? // } // var s1 = Document<Scheme>(Scheme(sparrows: nil, skylarks: nil)) // s1.change { $0.sparrows?.set(1) } // s1.change { $0.skylarks?.set(1) } // s1.change { $0.sparrows?.set(2) } // s1.change { $0.skylarks.set(nil) } // let states: [Scheme] = [.init(sparrows: nil, skylarks: nil), .init(sparrows: 1, skylarks: nil), .init(sparrows: 1, skylarks: 1), .init(sparrows: 2, skylarks: 1), .init(sparrows: 2, skylarks: nil)] // for _ in (0..<3) { // for undo in (0...(states.count - 2)).reversed() { // s1.undo() // XCTAssertEqual(s1.content, states[undo]) // } // for redo in 1..<states.count { // s1.redo() // XCTAssertEqual(s1.content, states[redo]) // } // } // } // // // should undo/redo an initial field assignment // func testRedo4() { // struct Scheme: Codable, Equatable { // var hello: String? // } // var s1 = Document(Scheme(hello: nil)) // s1.change { $0.hello?.set("world") } // s1.undo() // XCTAssertEqual(s1.content, Scheme(hello: nil)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(hello: "world")) // } // // // should undo/redo a field update // func testRedo5() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 3)) // s1.change { $0.value.set(4) } // XCTAssertEqual(s1.content, Scheme(value: 4)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 3)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(value: 4)) // } // // // should undo/redo a field deletion // func testRedo6() { // struct Scheme: Codable, Equatable { // var value: Int? // } // // var s1 = Document(Scheme(value: 123)) // s1.change { $0.value.set(nil) } // XCTAssertEqual(s1.content, Scheme(value: nil)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 123)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(value: nil)) // } // // // should undo/redo object creation and linking // func testRedo7() { // struct Scheme: Codable, Equatable { // struct Settings: Codable, Equatable { // let background: String // let text: String // } // var settings: Settings? // } // // var s1 = Document(Scheme(settings: nil)) // s1.change { $0.settings.set(.init(background: "white", text: "black")) } // XCTAssertEqual(s1.content, Scheme(settings: .init(background: "white", text: "black"))) // s1.undo() // XCTAssertEqual(s1.content, Scheme(settings: nil)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(settings: .init(background: "white", text: "black"))) // } // // // should undo/redo link deletion // func testRedo8() { // struct Scheme: Codable, Equatable { // var fish: [String]? // var birds: [String]? // } // // var s1 = Document(Scheme(fish: ["trout", "sea bass"], birds: nil)) // s1.change { $0.birds.set(["heron", "magpie"]) } // s1.change { $0.fish.set(nil) } // XCTAssertEqual(s1.content, Scheme(fish: nil, birds: ["heron", "magpie"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(fish: ["trout", "sea bass"], birds: ["heron", "magpie"])) // s1.redo() // XCTAssertEqual(s1.content, Scheme(fish: nil, birds: ["heron", "magpie"])) // } // // // should undo/redo a list element insertion // func testRedo9() { // struct Scheme: Codable, Equatable { // var list: [String] // } // // var s1 = Document(Scheme(list: ["A", "B", "C"])) // s1.change { $0.list.append("D") } // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C", "D"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C"])) // s1.redo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C", "D"])) // } // // // should undo/redo a list element deletion // func testRedo10() { // struct Scheme: Codable, Equatable { // var list: [String] // } // // var s1 = Document(Scheme(list: ["A", "B", "C"])) // s1.change { $0.list.remove(at: 1) } // XCTAssertEqual(s1.content, Scheme(list: ["A", "C"])) // s1.undo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "B", "C"])) // s1.redo() // XCTAssertEqual(s1.content, Scheme(list: ["A", "C"])) // } // // // should undo/redo counter increments // func testRedo11() { // struct Scheme: Codable, Equatable { // var counter: Counter // } // // var s1 = Document(Scheme(counter: 0)) // s1.change { $0.counter.increment() } // XCTAssertEqual(s1.content, Scheme(counter: 1)) // s1.undo() // XCTAssertEqual(s1.content, Scheme(counter: 0)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(counter: 1)) // } // // // should redo assignments by other actors that precede the undo // func testRedo12() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 1)) // s1.change({ $0.value.set(2) }) // var s2 = Document<Scheme>(changes: s1.allChanges()) // s2.change({ $0.value.set(3) }) // s1.merge(s2) // s1.undo() // XCTAssertEqual(s1.content, Scheme(value: 1)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(value: 3)) // } // // // should overwrite assignments by other actors that follow the undo // func testRedo13() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 1)) // s1.change({ $0.value.set(2) }) // s1.undo() // var s2 = Document<Scheme>(changes: s1.allChanges()) // s2.change({ $0.value.set(3) }) // s1.merge(s2) // XCTAssertEqual(s1.content, Scheme(value: 3)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(value: 2)) // } // // // should merge with concurrent changes to other fields // func testRedo14() { // struct Scheme: Codable, Equatable { // var trout: Int? // var salmon: Int? // } // // var s1 = Document(Scheme(trout: 2, salmon: nil)) // s1.change({ $0.trout.set(3) }) // s1.undo() // var s2 = Document<Scheme>(changes: s1.allChanges()) // s2.change({ $0.salmon.set(1) }) // s1.merge(s2) // XCTAssertEqual(s1.content, Scheme(trout: 2, salmon: 1)) // s1.redo() // XCTAssertEqual(s1.content, Scheme(trout: 3, salmon: 1)) // } // // // should apply redos by growing the history // func testRedo15() { // struct Scheme: Codable, Equatable { // var value: Int // } // // var s1 = Document(Scheme(value: 1)) // s1.change(message: "set 2") { $0.value.set(2) } // s1.undo(message: "undo") // s1.redo(message: "redo!") // let history = History(document: s1) // let seqs = history.map { $0.change.seq } // XCTAssertEqual(seqs, [1, 2, 3, 4]) // let messages = history.map { $0.change.message } // XCTAssertEqual(messages, ["Initialization", "set 2", "undo", "redo!"]) // XCTAssertEqual(history.count, 4) // } // should save and restore an empty document func testSaveAndLoading1() { struct Scheme: Codable, Equatable { } let s = Document<Scheme>(data: Document(Scheme()).save()) XCTAssertEqual(s.content, Scheme()) } // should generate a new random actor ID func testSaveAndLoading2() { struct Scheme: Codable, Equatable { } let s1 = Document(Scheme()) let s2 = Document<Scheme>(data:s1.save()) XCTAssertNotEqual(s1.actor, s2.actor) } // should allow a custom actor ID to be set func testSaveAndLoading3() { struct Scheme: Codable, Equatable { } let s = Document<Scheme>(data: Document(Scheme()).save(), actor: Actor(actorId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) XCTAssertEqual(s.actor, Actor(actorId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) } // should allow a custom actor ID to be set func testSaveAndLoading4() { struct Scheme: Codable, Equatable { struct Todo: Codable, Equatable { let title: String let done: Bool } let todos: [Todo] } let s1 = Document(Scheme(todos: [.init(title: "water plants'", done: false)])) let s2 = Document<Scheme>(data: s1.save()) XCTAssertEqual(s2.content, Scheme(todos: [.init(title: "water plants'", done: false)])) } // should reconstitute conflicts func testSaveAndLoading5() { struct Scheme: Codable, Equatable { let x: Int } var s1 = Document(Scheme(x: 3), actor: Actor(actorId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) let s2 = Document(Scheme(x: 5), actor: Actor(actorId: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) s1.merge(s2) let s3 = Document<Scheme>(data: s1.save()) XCTAssertEqual(s1.content.x, 5) XCTAssertEqual(s3.content.x, 5) XCTAssertEqual(s1.rootProxy().conflicts(dynamicMember: \.x), ["1@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": 3, "1@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": 5]) XCTAssertEqual(s3.rootProxy().conflicts(dynamicMember: \.x), ["1@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": 3, "1@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": 5]) } // should allow a reloaded list to be mutated func testSaveAndLoading6() { struct Scheme: Codable, Equatable { var foo: [Int] } var doc = Document(Scheme(foo: [])) doc = Document(data: doc.save()) doc.change { $0.foo.append(1) } doc = Document(data: doc.save()) XCTAssertEqual(doc.content.foo, [1]) } // should make past document states accessible func testHistory1() { struct Scheme: Codable, Equatable { struct Config: Codable, Equatable { let background: String } let config: Config var birds: [String] } var s = Document(Scheme(config: .init(background: "blue"), birds: [])) s.change({ $0.birds.set(["mallard"]) }) s.change { $0.birds.insert("oystercatcher", at: 0) } let history = History(document: s).map { $0.snapshot } XCTAssertEqual(history, [ Scheme(config: .init(background: "blue"), birds: []), Scheme(config: .init(background: "blue"), birds: ["mallard"]), Scheme(config: .init(background: "blue"), birds: ["oystercatcher", "mallard"]) ]) } // should make change messages accessible func testHistory2() { struct Scheme: Codable, Equatable { var books: [String] } var s = Document(Scheme(books: [])) s.change(message: "Add Orwell") { $0.books.append("Nineteen Eighty-Four") } s.change(message: "Add Huxley") { $0.books.append("Brave New World") } let messages = History(document: s).map { $0.change.message } XCTAssertEqual(messages, [ "Initialization", "Add Orwell", "Add Huxley" ]) } // should make access fast func testHistory3() { struct Scheme: Codable, Equatable { var books: [String] } var s = Document(Scheme(books: [])) s.change(message: "Add Orwell") { $0.books.append("Nineteen Eighty-Four") } s.change(message: "Add Huxley") { $0.books.append("Brave New World") } let message = History(document: s).last?.change.message XCTAssertEqual(message, "Add Huxley") } // should contain actor func testHistory4() { struct Scheme: Codable, Equatable { var books: [String] } let actor = Actor() var s = Document(Scheme(books: []), actor: actor) s.change(message: "Add Orwell") { $0.books.append("Nineteen Eighty-Four") } s.change(message: "Add Huxley") { $0.books.append("Brave New World") } let historyActor = History(document: s).last?.change.actor XCTAssertEqual(historyActor, actor) } // should report missing dependencies func testgetMissingDeps1() { struct Scheme: Codable, Equatable { var birds: [String] } let s1 = Document(Scheme(birds: ["Chaffinch"])) var s2 = Document<Scheme>(data: s1.save()) s2.change({ $0.birds.append("Bullfinch") }) let changes = s2.allChanges() var s3 = Document<Scheme>(changes: [changes[1]]) XCTAssertEqual(s3.getMissingsDeps(), Change(change: changes[1]).deps) s3.apply(changes: [changes[0]]) XCTAssertEqual(s3.content, Scheme(birds: ["Chaffinch", "Bullfinch"])) XCTAssertEqual(s3.getMissingsDeps(), []) } // should report missing dependencies func testGetHeads1() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["Chaffinch"])) s1.change({ $0.birds.append("Test") }) let heads = s1.getHeads() XCTAssertEqual(heads.count, 1) } func testGetChangesBetween1() { struct Scheme: Codable, Equatable { var birds: [String] } let s1 = Document(Scheme(birds: ["Chaffinch"])) let s2 = Document<Scheme>(changes: s1.allChanges()) let changes = s1.getChanges(between: s2) XCTAssertEqual(changes.count, 0) } func testGetChangesBetween2() { struct Scheme: Codable, Equatable { var birds: [String] } var s1 = Document(Scheme(birds: ["Chaffinch"])) var s2 = s1 s1.change({ $0.birds.append("Bullfinch") }) let changes = s1.getChanges(between: s2) XCTAssertEqual(changes.count, 1) s2.apply(changes: changes) let changes2 = s1.getChanges(between: s2) XCTAssertEqual(changes2.count, 0) } }
37.217957
206
0.563795
d6d6df19fa92cf697b4ad920c661f37526496f65
2,236
// // MessagesViewController.swift // RecorderFramework-TVExample // // Created by Stefanita Oaca on 12/07/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import RecorderFramework class MessagesViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { var selectedObject: AnyObject! @IBOutlet weak var tableView: UITableView! var messages = [ServerMessage]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:TableView func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "titleCell", for: indexPath) cell.textLabel?.text = messages[indexPath.row].title cell.detailTextLabel?.text = messages[indexPath.row].body return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: false) selectedObject = messages[indexPath.row].description as AnyObject self.performSegue(withIdentifier: "showMessageDetailsFromMessages", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showMessageDetailsFromMessages"{ (segue.destination as! DisplayViewController).object = selectedObject (segue.destination as! DisplayViewController).objectTitle = "Message details" } } }
33.878788
100
0.691413
ff1fe9c61822775d9b90959709958e6c2fa0269d
18,996
import Foundation // Code below is ported from https://github.com/cocometadata/cocoapi /// Coco metadata API that loads annotation file and prepares /// data structures for data set access. public struct COCO { public typealias Metadata = [String: Any] public typealias Info = [String: Any] public typealias Annotation = [String: Any] public typealias AnnotationId = Int public typealias Image = [String: Any] public typealias ImageId = Int public typealias Category = [String: Any] public typealias CategoryId = Int public var imagesDirectory: URL? public var metadata: Metadata public var info: Info = [:] public var annotations: [AnnotationId: Annotation] = [:] public var categories: [CategoryId: Category] = [:] public var images: [ImageId: Image] = [:] public var imageToAnnotations: [ImageId: [Annotation]] = [:] public var categoryToImages: [CategoryId: [ImageId]] = [:] public init(fromFile fileURL: URL, imagesDirectory imgDir: URL?) throws { let contents = try String(contentsOfFile: fileURL.path) let data = contents.data(using: .utf8)! let parsed = try JSONSerialization.jsonObject(with: data) self.metadata = parsed as! Metadata self.imagesDirectory = imgDir self.createIndex() } mutating func createIndex() { if let info = metadata["info"] { self.info = info as! Info } if let annotations = metadata["annotations"] as? [Annotation] { for ann in annotations { let ann_id = ann["id"] as! AnnotationId let image_id = ann["image_id"] as! ImageId self.imageToAnnotations[image_id, default: []].append(ann) self.annotations[ann_id] = ann } } if let images = metadata["images"] as? [Image] { for img in images { let img_id = img["id"] as! ImageId self.images[img_id] = img } } if let categories = metadata["categories"] as? [Category] { for cat in categories { let cat_id = cat["id"] as! CategoryId self.categories[cat_id] = cat } } if metadata["annotations"] != nil && metadata["categories"] != nil { let anns = metadata["annotations"] as! [Annotation] for ann in anns { let cat_id = ann["category_id"] as! CategoryId let image_id = ann["image_id"] as! ImageId self.categoryToImages[cat_id, default: []].append(image_id) } } } /// Get annotation ids that satisfy given filter conditions. public func getAnnotationIds( imageIds: [ImageId] = [], categoryIds: Set<CategoryId> = [], areaRange: [Double] = [], isCrowd: Int? = nil ) -> [AnnotationId] { let filterByImageId = imageIds.count != 0 let filterByCategoryId = imageIds.count != 0 let filterByAreaRange = areaRange.count != 0 let filterByIsCrowd = isCrowd != nil var anns: [Annotation] = [] if filterByImageId { for imageId in imageIds { if let imageAnns = self.imageToAnnotations[imageId] { for imageAnn in imageAnns { anns.append(imageAnn) } } } } else { anns = self.metadata["annotations"] as! [Annotation] } var annIds: [AnnotationId] = [] for ann in anns { if filterByCategoryId { let categoryId = ann["category_id"] as! CategoryId if !categoryIds.contains(categoryId) { continue } } if filterByAreaRange { let area = ann["area"] as! Double if !(area > areaRange[0] && area < areaRange[1]) { continue } } if filterByIsCrowd { let annIsCrowd = ann["iscrowd"] as! Int if annIsCrowd != isCrowd! { continue } } let id = ann["id"] as! AnnotationId annIds.append(id) } return annIds } /// Get category ids that satisfy given filter conditions. public func getCategoryIds( categoryNames: Set<String> = [], supercategoryNames: Set<String> = [], categoryIds: Set<CategoryId> = [] ) -> [CategoryId] { let filterByName = categoryNames.count != 0 let filterBySupercategory = supercategoryNames.count != 0 let filterById = categoryIds.count != 0 var categoryIds: [CategoryId] = [] let cats = self.metadata["categories"] as! [Category] for cat in cats { let name = cat["name"] as! String let supercategory = cat["supercategory"] as! String let id = cat["id"] as! CategoryId if filterByName && !categoryNames.contains(name) { continue } if filterBySupercategory && !supercategoryNames.contains(supercategory) { continue } if filterById && !categoryIds.contains(id) { continue } categoryIds.append(id) } return categoryIds } /// Get image ids that satisfy given filter conditions. public func getImageIds( imageIds: [ImageId] = [], categoryIds: [CategoryId] = [] ) -> [ImageId] { if imageIds.count == 0 && categoryIds.count == 0 { return Array(self.images.keys) } else { var ids = Set(imageIds) for (i, catId) in categoryIds.enumerated() { if i == 0 && ids.count == 0 { ids = Set(self.categoryToImages[catId]!) } else { ids = ids.intersection(Set(self.categoryToImages[catId]!)) } } return Array(ids) } } /// Load annotations with specified ids. public func loadAnnotations(ids: [AnnotationId] = []) -> [Annotation] { var anns: [Annotation] = [] for id in ids { anns.append(self.annotations[id]!) } return anns } /// Load categories with specified ids. public func loadCategories(ids: [CategoryId] = []) -> [Category] { var cats: [Category] = [] for id in ids { cats.append(self.categories[id]!) } return cats } /// Load images with specified ids. public func loadImages(ids: [ImageId] = []) -> [Image] { var imgs: [Image] = [] for id in ids { imgs.append(self.images[id]!) } return imgs } /// Convert segmentation in an annotation to RLE. public func annotationToRLE(_ ann: Annotation) -> RLE { let imgId = ann["image_id"] as! ImageId let img = self.images[imgId]! let h = img["height"] as! Int let w = img["width"] as! Int let segm = ann["segmentation"] if let polygon = segm as? [Any] { let rles = Mask.fromObject(polygon, width: w, height: h) return Mask.merge(rles) } else if let segmDict = segm as? [String: Any] { if segmDict["counts"] is [Any] { return Mask.fromObject(segmDict, width: w, height: h)[0] } else if let countsStr = segmDict["counts"] as? String { return RLE(fromString: countsStr, width: w, height: h) } else { fatalError("unrecognized annotation: \(ann)") } } else { fatalError("unrecognized annotation: \(ann)") } } public func annotationToMask(_ ann: Annotation) -> Mask { let rle = annotationToRLE(ann) let mask = Mask(fromRLE: rle) return mask } } public struct Mask { var width: Int var height: Int var n: Int var mask: [Bool] init(width w: Int, height h: Int, n: Int, mask: [Bool]) { self.width = w self.height = h self.n = n self.mask = mask } init(fromRLE rle: RLE) { self.init(fromRLEs: [rle]) } init(fromRLEs rles: [RLE]) { let w = rles[0].width let h = rles[0].height let n = rles.count var mask = [Bool](repeating: false, count: w * h * n) var cursor: Int = 0 for i in 0..<n { var v: Bool = false for j in 0..<rles[i].m { for _ in 0..<rles[i].counts[j] { mask[cursor] = v cursor += 1 } v = !v } } self.init(width: w, height: h, n: n, mask: mask) } static func merge(_ rles: [RLE], intersect: Bool = false) -> RLE { return RLE(merging: rles, intersect: intersect) } static func fromBoundingBoxes(_ bboxes: [[Double]], width w: Int, height h: Int) -> [RLE] { var rles: [RLE] = [] for bbox in bboxes { let rle = RLE(fromBoundingBox: bbox, width: w, height: h) rles.append(rle) } return rles } static func fromPolygons(_ polys: [[Double]], width w: Int, height h: Int) -> [RLE] { var rles: [RLE] = [] for poly in polys { let rle = RLE(fromPolygon: poly, width: w, height: h) rles.append(rle) } return rles } static func fromUncompressedRLEs(_ arr: [[String: Any]], width w: Int, height h: Int) -> [RLE] { var rles: [RLE] = [] for elem in arr { let counts = elem["counts"] as! [Int] let m = counts.count var cnts = [UInt32](repeating: 0, count: m) for i in 0..<m { cnts[i] = UInt32(counts[i]) } let size = elem["size"] as! [Int] let h = size[0] let w = size[1] rles.append(RLE(width: w, height: h, m: cnts.count, counts: cnts)) } return rles } static func fromObject(_ obj: Any, width w: Int, height h: Int) -> [RLE] { // encode rle from a list of json deserialized objects if let arr = obj as? [[Double]] { assert(arr.count > 0) if arr[0].count == 4 { return fromBoundingBoxes(arr, width: w, height: h) } else { assert(arr[0].count > 4) return fromPolygons(arr, width: w, height: h) } } else if let arr = obj as? [[String: Any]] { assert(arr.count > 0) assert(arr[0]["size"] != nil) assert(arr[0]["counts"] != nil) return fromUncompressedRLEs(arr, width: w, height: h) // encode rle from a single json deserialized object } else if let arr = obj as? [Double] { if arr.count == 4 { return fromBoundingBoxes([arr], width: w, height: h) } else { assert(arr.count > 4) return fromPolygons([arr], width: w, height: h) } } else if let dict = obj as? [String: Any] { assert(dict["size"] != nil) assert(dict["counts"] != nil) return fromUncompressedRLEs([dict], width: w, height: h) } else { fatalError("input type is not supported") } } } public struct RLE { var width: Int = 0 var height: Int = 0 var m: Int = 0 var counts: [UInt32] = [] var mask: Mask { return Mask(fromRLE: self) } init(width w: Int, height h: Int, m: Int, counts: [UInt32]) { self.width = w self.height = h self.m = m self.counts = counts } init(fromString str: String, width w: Int, height h: Int) { let data = str.data(using: .utf8)! let bytes = [UInt8](data) self.init(fromBytes: bytes, width: w, height: h) } init(fromBytes bytes: [UInt8], width w: Int, height h: Int) { var m: Int = 0 var p: Int = 0 var cnts = [UInt32](repeating: 0, count: bytes.count) while p < bytes.count { var x: Int = 0 var k: Int = 0 var more: Int = 1 while more != 0 { let c = Int8(bitPattern: bytes[p]) - 48 x |= (Int(c) & 0x1f) << 5 * k more = Int(c) & 0x20 p += 1 k += 1 if more == 0 && (c & 0x10) != 0 { x |= -1 << 5 * k } } if m > 2 { x += Int(cnts[m - 2]) } cnts[m] = UInt32(truncatingIfNeeded: x) m += 1 } self.init(width: w, height: h, m: m, counts: cnts) } init(fromBoundingBox bb: [Double], width w: Int, height h: Int) { let xs = bb[0] let ys = bb[1] let xe = bb[2] let ye = bb[3] let xy: [Double] = [xs, ys, xs, ye, xe, ye, xe, ys] self.init(fromPolygon: xy, width: w, height: h) } init(fromPolygon xy: [Double], width w: Int, height h: Int) { // upsample and get discrete points densely along the entire boundary var k: Int = xy.count / 2 var j: Int = 0 var m: Int = 0 let scale: Double = 5 var x = [Int](repeating: 0, count: k + 1) var y = [Int](repeating: 0, count: k + 1) for j in 0..<k { x[j] = Int(scale * xy[j * 2 + 0] + 0.5) } x[k] = x[0] for j in 0..<k { y[j] = Int(scale * xy[j * 2 + 1] + 0.5) } y[k] = y[0] for j in 0..<k { m += max(abs(x[j] - x[j + 1]), abs(y[j] - y[j + 1])) + 1 } var u = [Int](repeating: 0, count: m) var v = [Int](repeating: 0, count: m) m = 0 for j in 0..<k { var xs: Int = x[j] var xe: Int = x[j + 1] var ys: Int = y[j] var ye: Int = y[j + 1] let dx: Int = abs(xe - xs) let dy: Int = abs(ys - ye) var t: Int let flip: Bool = (dx >= dy && xs > xe) || (dx < dy && ys > ye) if flip { t = xs xs = xe xe = t t = ys ys = ye ye = t } let s: Double = dx >= dy ? Double(ye - ys) / Double(dx) : Double(xe - xs) / Double(dy) if dx >= dy { for d in 0...dx { t = flip ? dx - d : d u[m] = t + xs let vm = Double(ys) + s * Double(t) + 0.5 v[m] = vm.isNaN ? 0 : Int(vm) m += 1 } } else { for d in 0...dy { t = flip ? dy - d : d v[m] = t + ys let um = Double(xs) + s * Double(t) + 0.5 u[m] = um.isNaN ? 0 : Int(um) m += 1 } } } // get points along y-boundary and downsample k = m m = 0 var xd: Double var yd: Double x = [Int](repeating: 0, count: k) y = [Int](repeating: 0, count: k) for j in 1..<k { if u[j] != u[j - 1] { xd = Double(u[j] < u[j - 1] ? u[j] : u[j] - 1) xd = (xd + 0.5) / scale - 0.5 if floor(xd) != xd || xd < 0 || xd > Double(w - 1) { continue } yd = Double(v[j] < v[j - 1] ? v[j] : v[j - 1]) yd = (yd + 0.5) / scale - 0.5 if yd < 0 { yd = 0 } else if yd > Double(h) { yd = Double(h) } yd = ceil(yd) x[m] = Int(xd) y[m] = Int(yd) m += 1 } } // compute rle encoding given y-boundary points k = m var a = [UInt32](repeating: 0, count: k + 1) for j in 0..<k { a[j] = UInt32(x[j] * Int(h) + y[j]) } a[k] = UInt32(h * w) k += 1 a.sort() var p: UInt32 = 0 for j in 0..<k { let t: UInt32 = a[j] a[j] -= p p = t } var b = [UInt32](repeating: 0, count: k) j = 0 m = 0 b[m] = a[j] m += 1 j += 1 while j < k { if a[j] > 0 { b[m] = a[j] m += 1 j += 1 } else { j += 1 } if j < k { b[m - 1] += a[j] j += 1 } } self.init(width: w, height: h, m: m, counts: b) } init(merging rles: [RLE], intersect: Bool) { var c: UInt32 var ca: UInt32 var cb: UInt32 var cc: UInt32 var ct: UInt32 var v: Bool var va: Bool var vb: Bool var vp: Bool var a: Int var b: Int var w: Int = rles[0].width var h: Int = rles[0].height var m: Int = rles[0].m var A: RLE var B: RLE let n = rles.count if n == 0 { self.init(width: 0, height: 0, m: 0, counts: []) return } if n == 1 { self.init(width: w, height: h, m: m, counts: rles[0].counts) return } var cnts = [UInt32](repeating: 0, count: h * w + 1) for a in 0..<m { cnts[a] = rles[0].counts[a] } for i in 1..<n { B = rles[i] if B.height != h || B.width != w { h = 0 w = 0 m = 0 break } A = RLE(width: w, height: h, m: m, counts: cnts) ca = A.counts[0] cb = B.counts[0] v = false va = false vb = false m = 0 a = 1 b = 1 cc = 0 ct = 1 while ct > 0 { c = min(ca, cb) cc += c ct = 0 ca -= c if ca == 0 && a < A.m { ca = A.counts[a] a += 1 va = !va } ct += ca cb -= c if cb == 0 && b < B.m { cb = B.counts[b] b += 1 vb = !vb } ct += cb vp = v if intersect { v = va && vb } else { v = va || vb } if v != vp || ct == 0 { cnts[m] = cc m += 1 cc = 0 } } } self.init(width: w, height: h, m: m, counts: cnts) } }
32.527397
100
0.450516
2050bd12f95b7d2056b88c7a781168232388262c
3,521
// // SearchViewController.swift // GitHubSearchApp // // Created by burt on 2018. 10. 22.. // Copyright © 2018년 Burt.K. All rights reserved. // import Cocoa import SnapKit import CocoaReactComponentKit import BKEventBus import BKRedux class SearchHistoryViewController: NSViewControllerComponent { private lazy var textfieldComponent: TextfieldComponent = { let component = TextfieldComponent(token: self.token, receiveState: false) return component }() private lazy var searchModeComponent: SegmentComponent = { let component = SegmentComponent(token: self.token, labels: ["User", "Repo"]) return component }() private lazy var tableViewComponent: NSTableViewComponent = { let component = NSTableViewComponent(token: self.token, receiveState: false) component.selectionHighlightStyle = .none component.wantsLayer = true component.layer?.cornerRadius = 5 return component }() private lazy var adapter: NSTableViewAdapter = { let adapter = NSTableViewAdapter(tableViewComponent: tableViewComponent, useDiff: true) return adapter }() required init(token: Token, receiveState: Bool = true) { super.init(token: token, receiveState: receiveState) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.layer?.backgroundColor = NSColor.controlColor.cgColor view.addSubview(textfieldComponent) view.addSubview(searchModeComponent) view.addSubview(tableViewComponent) textfieldComponent.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(16) make.right.equalToSuperview().offset(-16) make.width.greaterThanOrEqualTo(200) make.top.equalToSuperview().offset(30) } searchModeComponent.snp.makeConstraints { (make) in make.left.right.equalTo(textfieldComponent) make.top.equalTo(textfieldComponent.snp.bottom).offset(8) } tableViewComponent.snp.makeConstraints { (make) in make.left.right.equalTo(textfieldComponent) make.top.equalTo(searchModeComponent.snp.bottom).offset(8) make.bottom.equalToSuperview().offset(-8) } // propagate input text textfieldComponent.changedText = { [weak self] (keyword) in guard let keyword = keyword else { return } self?.dispatch(action: InputSearchKeywordAction(keyword: keyword)) } textfieldComponent.enterText = { [weak self] keyword in guard let keyword = keyword else { return } self?.dispatch(action: StoreKeywordAction(keyword: keyword)) } searchModeComponent.changedSelectedSegment = { [weak self] (index) in let searchScope: SearchState.SearchScope = index == 0 ? .user : .repo self?.dispatch(action: SelectSearchScopeAction(searchScope: searchScope)) } tableViewComponent.adapter = adapter tableViewComponent.register(component: HistoryItemComponent.self) } override func on(state: State) { guard let searchState = state as? SearchState, let section = searchState.hitorySectons else { return } adapter.set(section: section) } }
35.565657
110
0.652371
8763c91460a221b1da0efa79d5bb459eddb5b3d2
414
// // JsonCoder.swift // PersonalDictionary // // Created by Maxim Ivanov on 09.10.2021. // import Foundation protocol JsonCoder { func encodeAsync<T: Encodable>(_ object: T, _ completion: @escaping (Result<Data, Error>) -> Void) func decodeAsync<T: Decodable>(_ data: Data, _ completion: @escaping (Result<T, Error>) -> Void) }
23
89
0.567633
f81dbcccaa0323f6b3214a36b61381be0c91cde7
3,387
// // StoresController.swift // Checkout // // Created by Calebe Emerick on 30/11/16. // Copyright © 2016 CalebeEmerick. All rights reserved. // import UIKit // MARK: - Variables & Outlets - final class StoresController : UIViewController { @IBOutlet fileprivate weak var container: UIView! @IBOutlet fileprivate weak var collectionView: UICollectionView! @IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView! fileprivate let storeError = StoreError.makeXib() fileprivate let dataSource = StoreDataSource() fileprivate let delegate = StoreDelegate() fileprivate let layout = StoreLayout() fileprivate var presenter: StorePresenter? } // MARK: - Life Cycle - extension StoresController { override func viewDidLoad() { super.viewDidLoad() changeNavigationBarBackButton() presenter = StorePresenter(storeView: self) delegate.selectedStore = { [weak self] store in self?.openTransactionController(with: store) } layout.setupCollectionView(for: collectionView, dataSource: dataSource, delegate: delegate) setErrorViewConstraints() presenter?.getStores() } } // MARK: - Methods - extension StoresController { fileprivate func setErrorViewConstraints() { DispatchQueue.main.async { self.storeError.alpha = 0 self.storeError.triedAgain = { self.tryLoadStoresAgain() } self.view.addSubview(self.storeError) self.storeError.translatesAutoresizingMaskIntoConstraints = false self.storeError.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true self.storeError.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true self.storeError.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8).isActive = true self.storeError.heightAnchor.constraint(equalToConstant: self.storeError.bounds.height).isActive = true } } fileprivate func changeStoreError(alpha: CGFloat) { UIView.animate(withDuration: 0.4) { self.storeError.alpha = alpha } } } // MARK: - StoresView Protocol - extension StoresController : StoresView { func showLoading() { activityIndicator.startAnimating() } func hideLoading() { activityIndicator.stopAnimating() } func showContainer() { hideLoading() UIView.animate(withDuration: 0.4) { self.container.alpha = 1 } } func update(stores: [Store]) { DispatchQueue.main.async { self.dataSource.stores = stores self.collectionView.reloadData() } } func showError(message: String) { storeError.message = message changeStoreError(alpha: 1) } func hideError() { changeStoreError(alpha: 0) } func tryLoadStoresAgain() { hideError() showLoading() presenter?.getStores() } func openTransactionController(with store: Store) { TransactionRouter.openCreditCardTransactionController(from: self, with: store) } }
27.096
118
0.633009
9b6fdc8f95b051a503ed208de5fd4dae70b1b29a
3,736
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation @objc protocol KeyBackupRecoverCoordinatorBridgePresenterDelegate { func keyBackupRecoverCoordinatorBridgePresenterDidCancel(_ keyBackupRecoverCoordinatorBridgePresenter: KeyBackupRecoverCoordinatorBridgePresenter) func keyBackupRecoverCoordinatorBridgePresenterDidRecover(_ keyBackupRecoverCoordinatorBridgePresenter: KeyBackupRecoverCoordinatorBridgePresenter) } /// KeyBackupRecoverCoordinatorBridgePresenter enables to start KeyBackupRecoverCoordinator from a view controller. /// This bridge is used while waiting for global usage of coordinator pattern. @objcMembers final class KeyBackupRecoverCoordinatorBridgePresenter: NSObject { // MARK: - Properties // MARK: Private private let session: MXSession private let keyBackupVersion: MXKeyBackupVersion private var coordinator: KeyBackupRecoverCoordinator? // MARK: Public weak var delegate: KeyBackupRecoverCoordinatorBridgePresenterDelegate? // MARK: - Setup init(session: MXSession, keyBackupVersion: MXKeyBackupVersion) { self.session = session self.keyBackupVersion = keyBackupVersion super.init() } // MARK: - Public func present(from viewController: UIViewController, animated: Bool) { let keyBackupSetupCoordinator = KeyBackupRecoverCoordinator(session: self.session, keyBackupVersion: keyBackupVersion) keyBackupSetupCoordinator.delegate = self viewController.present(keyBackupSetupCoordinator.toPresentable(), animated: animated, completion: nil) keyBackupSetupCoordinator.start() self.coordinator = keyBackupSetupCoordinator } func push(from navigationController: UINavigationController, animated: Bool) { NSLog("[KeyBackupRecoverCoordinatorBridgePresenter] Push complete security from \(navigationController)") let navigationRouter = NavigationRouter(navigationController: navigationController) let keyBackupSetupCoordinator = KeyBackupRecoverCoordinator(session: self.session, keyBackupVersion: keyBackupVersion, navigationRouter: navigationRouter) keyBackupSetupCoordinator.delegate = self keyBackupSetupCoordinator.start() // Will trigger view controller push self.coordinator = keyBackupSetupCoordinator } func dismiss(animated: Bool) { guard let coordinator = self.coordinator else { return } coordinator.toPresentable().dismiss(animated: animated) { self.coordinator = nil } } } // MARK: - KeyBackupRecoverCoordinatorDelegate extension KeyBackupRecoverCoordinatorBridgePresenter: KeyBackupRecoverCoordinatorDelegate { func keyBackupRecoverCoordinatorDidRecover(_ keyBackupRecoverCoordinator: KeyBackupRecoverCoordinatorType) { self.delegate?.keyBackupRecoverCoordinatorBridgePresenterDidRecover(self) } func keyBackupRecoverCoordinatorDidCancel(_ keyBackupRecoverCoordinator: KeyBackupRecoverCoordinatorType) { self.delegate?.keyBackupRecoverCoordinatorBridgePresenterDidCancel(self) } }
40.172043
162
0.760707
e4801de6f9835fe9bdb30d4229c4f9405cb0f894
1,154
// // NODEProtocols.swift // NodeelKit // // Created by Heestand XYZ on 2018-07-26. // Open Source - MIT License // import CoreGraphics import Metal import Combine public protocol NODEDelegate: AnyObject { func nodeDidRender(_ node: NODE) } public protocol NODEIn { func didUpdateInputConnections() } public protocol NODEOut { var renderPromisePublisher: PassthroughSubject<RenderRequest, Never> { get } var renderPublisher: PassthroughSubject<RenderPack, Never> { get } } public protocol NODEInSingle: NODEIn { var input: (NODE & NODEOut)? { get set } } public protocol NODEInMerger: NODEIn { var inputA: (NODE & NODEOut)? { get set } var inputB: (NODE & NODEOut)? { get set } } public protocol NODEInMulti: NODEIn { var inputs: [NODE & NODEOut] { get set } } public protocol NODEInIO: NODEIn { var inputList: [NODE & NODEOut] { get set } var connectedIn: Bool { get } var cancellableIns: [AnyCancellable] { get set } } public protocol NODEOutIO: NODEOut { // var outputPathList: NODE.WeakOutPaths { get set } var outputPathList: [NODEOutPath] { get set } var connectedOut: Bool { get } }
25.086957
80
0.69844
294c5f3fe3f087efa41b7230bfb6d3339ff68a11
797
// // StageViewModel.swift // ReformApplication // // Created by Laszlo Korte on 26.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformStage import ReformTools final class StageViewModel { let stage : Stage let stageUI : StageUI let toolController : ToolController let selection : FormSelection let camera: Camera let selectionChanger : FormSelectionChanger init(stage: Stage, stageUI: StageUI, toolController : ToolController, selection: FormSelection, camera: Camera, selectionChanger: FormSelectionChanger) { self.stage = stage self.stageUI = stageUI self.toolController = toolController self.selection = selection self.camera = camera self.selectionChanger = selectionChanger } }
28.464286
157
0.711418
1a471bc0bc21a65e276dc21d1815bad1e6474244
34,611
// // TeslaSwift.swift // TeslaSwift // // Created by Joao Nunes on 04/03/16. // Copyright © 2016 Joao Nunes. All rights reserved. // import Foundation import os.log import CoreLocation.CLLocation public enum VehicleCommand { case valetMode(valetActivated: Bool, pin: String?) case resetValetPin case openChargeDoor case closeChargeDoor case chargeLimitStandard case chargeLimitMaxRange case chargeLimitPercentage(limit: Int) case startCharging case stopCharging case flashLights case triggerHomeLink(location: CLLocation) case honkHorn case unlockDoors case lockDoors case setTemperature(driverTemperature: Double, passengerTemperature: Double) case setMaxDefrost(on: Bool) case startAutoConditioning case stopAutoConditioning case setSunRoof(state: RoofState, percentage: Int?) case startVehicle(password: String) case openTrunk(options: OpenTrunkOptions) case togglePlayback case nextTrack case previousTrack case nextFavorite case previousFavorite case volumeUp case volumeDown case shareToVehicle(options: ShareToVehicleOptions) case cancelSoftwareUpdate case scheduleSoftwareUpdate case speedLimitSetLimit(speed: Measurement<UnitSpeed>) case speedLimitActivate(pin: String) case speedLimitDeactivate(pin: String) case speedLimitClearPin(pin: String) case setSeatHeater(seat: HeatedSeat, level: HeatLevel) case setSteeringWheelHeater(on: Bool) case sentryMode(activated: Bool) case windowControl(state: WindowState) func path() -> String { switch self { case .valetMode: return "command/set_valet_mode" case .resetValetPin: return "command/reset_valet_pin" case .openChargeDoor: return "command/charge_port_door_open" case .closeChargeDoor: return "command/charge_port_door_close" case .chargeLimitStandard: return "command/charge_standard" case .chargeLimitMaxRange: return "command/charge_max_range" case .chargeLimitPercentage: return "command/set_charge_limit" case .startCharging: return "command/charge_start" case .stopCharging: return "command/charge_stop" case .flashLights: return "command/flash_lights" case .triggerHomeLink: return "command/trigger_homelink" case .honkHorn: return "command/honk_horn" case .unlockDoors: return "command/door_unlock" case .lockDoors: return "command/door_lock" case .setTemperature: return "command/set_temps" case .setMaxDefrost: return "command/set_preconditioning_max" case .startAutoConditioning: return "command/auto_conditioning_start" case .stopAutoConditioning: return "command/auto_conditioning_stop" case .setSunRoof: return "command/sun_roof_control" case .startVehicle: return "command/remote_start_drive" case .openTrunk: return "command/actuate_trunk" case .togglePlayback: return "command/media_toggle_playback" case .nextTrack: return "command/media_next_track" case .previousTrack: return "command/media_prev_track" case .nextFavorite: return "command/media_next_fav" case .previousFavorite: return "command/media_prev_fav" case .volumeUp: return "command/media_volume_up" case .volumeDown: return "command/media_volume_down" case .shareToVehicle: return "command/share" case .scheduleSoftwareUpdate: return "command/schedule_software_update" case .cancelSoftwareUpdate: return "command/cancel_software_update" case .speedLimitSetLimit: return "command/speed_limit_set_limit" case .speedLimitActivate: return "command/speed_limit_activate" case .speedLimitDeactivate: return "command/speed_limit_deactivate" case .speedLimitClearPin: return "command/speed_limit_clear_pin" case .setSeatHeater: return "command/remote_seat_heater_request" case .setSteeringWheelHeater: return "command/remote_steering_wheel_heater_request" case .sentryMode: return "command/set_sentry_mode" case .windowControl: return "command/window_control" } } } public enum TeslaError: Error, Equatable { case networkError(error:NSError) case authenticationRequired case authenticationFailed case tokenRevoked case noTokenToRefresh case tokenRefreshFailed case invalidOptionsForCommand case failedToParseData case streamingMissingEmailOrVehicleToken case failedToReloadVehicle } let ErrorInfo = "ErrorInfo" private var nullBody = "" open class TeslaSwift { open var useMockServer = false open var debuggingEnabled = false { didSet { streaming.debuggingEnabled = debuggingEnabled } } open var token: AuthToken? open fileprivate(set) var email: String? fileprivate var password: String? lazy var streaming = TeslaStreaming() public init() { } } extension TeslaSwift { public var isAuthenticated: Bool { return token != nil && (token?.isValid ?? false) } /** Performs the authentition with the Tesla API You only need to call this once. The token will be stored and your credentials. If the token expires your credentials will be reused. - parameter email: The email address. - parameter password: The password. - returns: A completion handler with the AuthToken. */ public func authenticate(email: String, password: String, completion: @escaping (Result<AuthToken, Error>) -> ()) -> Void { self.email = email self.password = password let body = AuthTokenRequest(email: email, password: password, grantType: .password) request(.authentication, body: body) { (result: Result<AuthToken, Error>) in switch result { case .success(let token): self.token = token completion(Result.success(token)) case .failure(let error): if case let TeslaError.networkError(error: internalError) = error { if internalError.code == 401 { completion(Result.failure(TeslaError.authenticationFailed)) } else { completion(Result.failure(error)) } } else { completion(Result.failure(error)) } } } } /** Performs the token refresh with the Tesla API - returns: A completion handler with the AuthToken. */ public func refreshToken(completion: @escaping (Result<AuthToken, Error>) -> ()) -> Void { guard let token = self.token else { completion(Result.failure(TeslaError.noTokenToRefresh)) return } let body = AuthTokenRequest(grantType: .refreshToken, refreshToken: token.refreshToken) request(.authentication, body: body) { (result: Result<AuthToken, Error>) in switch result { case .success(let token): self.token = token completion(Result.success(token)) case .failure(let error): if case let TeslaError.networkError(error: internalError) = error { if internalError.code == 401 { completion(Result.failure(TeslaError.tokenRefreshFailed)) } else { completion(Result.failure(error)) } } else { completion(Result.failure(error)) } } } } /** Use this method to reuse a previous authentication token This method is useful if your app wants to ask the user for credentials once and reuse the token skiping authentication If the token is invalid a new authentication will be required - parameter token: The previous token - parameter email: Email is required for streaming */ public func reuse(token: AuthToken, email: String? = nil) { self.token = token self.email = email } /** Revokes the stored token. Endpoint always returns true. - returns: A completion handler with the token revoke state. */ public func revoke(completion: @escaping (Result<Bool, Error>) -> ()) -> Void { guard let accessToken = self.token?.accessToken else { token = nil return completion(Result.success(false)) } token = nil checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let body = ["token" : accessToken] self.request(.revoke, body: body) { (result: Result<BoolResponse, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Removes all the information related to the previous authentication */ public func logout() { email = nil password = nil token = nil } /** Fetchs the list of your vehicles including not yet delivered ones - returns: A completion handler with an array of Vehicles. */ public func getVehicles(completion: @escaping (Result<[Vehicle], Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): self.request(.vehicles, body: nullBody) { (result: Result<ArrayResponse<Vehicle>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the summary of a vehicle - returns: A completion handler with a Vehicle. */ public func getVehicle(_ vehicleID: String, completion: @escaping (Result<Vehicle, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): self.request(.vehicleSummary(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<Vehicle>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the summary of a vehicle - returns: A completion handler with a Vehicle. */ public func getVehicle(_ vehicle: Vehicle, completion: @escaping (Result<Vehicle, Error>) -> ()) -> Void { return getVehicle(vehicle.id!, completion: completion) } /** Fetchs the vehicle data - returns: A completion handler with all the data */ public func getAllData(_ vehicle: Vehicle, completion: @escaping (Result<VehicleExtended, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.allStates(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<VehicleExtended>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle mobile access state - returns: A completion handler with mobile access state. */ public func getVehicleMobileAccessState(_ vehicle: Vehicle, completion: @escaping (Result<Bool, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.mobileAccess(vehicleID: vehicleID), body: nullBody) { (result: Result<BoolResponse, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle charge state - returns: A completion handler with charge state. */ public func getVehicleChargeState(_ vehicle: Vehicle, completion: @escaping (Result<ChargeState, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.chargeState(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<ChargeState>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle Climate state - returns: A completion handler with Climate state. */ public func getVehicleClimateState(_ vehicle: Vehicle, completion: @escaping (Result<ClimateState, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.climateState(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<ClimateState>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicledrive state - returns: A completion handler with drive state. */ public func getVehicleDriveState(_ vehicle: Vehicle, completion: @escaping (Result<DriveState, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.driveState(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<DriveState>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle Gui Settings - returns: A completion handler with Gui Settings. */ public func getVehicleGuiSettings(_ vehicle: Vehicle, completion: @escaping (Result<GuiSettings, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.guiSettings(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<GuiSettings>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle state - returns: A completion handler with vehicle state. */ public func getVehicleState(_ vehicle: Vehicle, completion: @escaping (Result<VehicleState, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.vehicleState(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<VehicleState>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetchs the vehicle config - returns: A completion handler with vehicle config */ public func getVehicleConfig(_ vehicle: Vehicle, completion: @escaping (Result<VehicleConfig, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.vehicleConfig(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<VehicleConfig>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Fetches the nearby charging sites - parameter vehicle: the vehicle to get nearby charging sites from - returns: A completion handler with nearby charging sites */ public func getNearbyChargingSites(_ vehicle: Vehicle, completion: @escaping (Result<NearbyChargingSites, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.nearbyChargingSites(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<NearbyChargingSites>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Wakes up the vehicle - returns: A completion handler with the current Vehicle */ public func wakeUp(_ vehicle: Vehicle, completion: @escaping (Result<Vehicle, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): let vehicleID = vehicle.id! self.request(.wakeUp(vehicleID: vehicleID), body: nullBody) { (result: Result<Response<Vehicle>, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let data): completion(Result.success(data.response)) } } } } } /** Sends a command to the vehicle - parameter vehicle: the vehicle that will receive the command - parameter command: the command to send to the vehicle - returns: A completion handler with the CommandResponse object containing the results of the command. */ public func sendCommandToVehicle(_ vehicle: Vehicle, command: VehicleCommand, completion: @escaping (Result<CommandResponse, Error>) -> ()) -> Void { checkAuthentication { (result: Result<AuthToken, Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(_): switch command { case let .setMaxDefrost(on: state): let body = MaxDefrostCommandOptions(state: state) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .triggerHomeLink(coordinates): let body = HomeLinkCommandOptions(coordinates: coordinates) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .valetMode(valetActivated, pin): let body = ValetCommandOptions(valetActivated: valetActivated, pin: pin) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .openTrunk(options): let body = options self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .shareToVehicle(address): let body = address self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .chargeLimitPercentage(limit): let body = ChargeLimitPercentageCommandOptions(limit: limit) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .setTemperature(driverTemperature, passengerTemperature): let body = SetTemperatureCommandOptions(driverTemperature: driverTemperature, passengerTemperature: passengerTemperature) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .setSunRoof(state, percent): let body = SetSunRoofCommandOptions(state: state, percent: percent) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .startVehicle(password): let body = RemoteStartDriveCommandOptions(password: password) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .speedLimitSetLimit(speed): let body = SetSpeedLimitOptions(limit: speed) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .speedLimitActivate(pin): let body = SpeedLimitPinOptions(pin: pin) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .speedLimitDeactivate(pin): let body = SpeedLimitPinOptions(pin: pin) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .speedLimitClearPin(pin): let body = SpeedLimitPinOptions(pin: pin) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .setSeatHeater(seat, level): let body = RemoteSeatHeaterRequestOptions(seat: seat, level: level) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .setSteeringWheelHeater(on): let body = RemoteSteeringWheelHeaterRequestOptions(on: on) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .sentryMode(activated): let body = SentryModeCommandOptions(activated: activated) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) case let .windowControl(state): let body = WindowControlCommandOptions(command: state) self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) default: let body = nullBody self.request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body, completion: completion) } } } } } extension TeslaSwift { func checkToken() -> Bool { if let token = self.token { return token.isValid } else { return false } } func cleanToken() { self.token = nil } func checkAuthentication(completion: @escaping (Result<AuthToken, Error>) -> ()) { let value = checkToken() if value { completion(Result.success(self.token!)) } else { self.cleanToken() if let email = self.email, let password = self.password { authenticate(email: email, password: password, completion: completion) } else { completion(Result.failure(TeslaError.authenticationRequired)) } } } func request<ReturnType: Decodable, BodyType: Encodable>(_ endpoint: Endpoint, body: BodyType, completion: @escaping (Result<ReturnType, Error>) -> ()) -> Void { let request = prepareRequest(endpoint, body: body) let debugEnabled = debuggingEnabled let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in guard error == nil else { completion(Result.failure(error!)); return } guard let httpResponse = response as? HTTPURLResponse else { completion(Result.failure(TeslaError.failedToParseData)); return } var responseString = "\nRESPONSE: \(String(describing: httpResponse.url))" responseString += "\nSTATUS CODE: \(httpResponse.statusCode)" if let headers = httpResponse.allHeaderFields as? [String: String] { responseString += "\nHEADERS: [\n" headers.forEach {(key: String, value: String) in responseString += "\"\(key)\": \"\(value)\"\n" } responseString += "]" } logDebug(responseString, debuggingEnabled: debugEnabled) if case 200..<300 = httpResponse.statusCode { do { if let data = data { let objectString = String.init(data: data, encoding: String.Encoding.utf8) ?? "No Body" logDebug("RESPONSE BODY: \(objectString)\n", debuggingEnabled: debugEnabled) let mapped = try teslaJSONDecoder.decode(ReturnType.self, from: data) completion(Result.success(mapped)) } } catch { logDebug("ERROR: \(error)", debuggingEnabled: debugEnabled) completion(Result.failure(TeslaError.failedToParseData)) } } else { if let data = data { let objectString = String.init(data: data, encoding: String.Encoding.utf8) ?? "No Body" logDebug("RESPONSE BODY ERROR: \(objectString)\n", debuggingEnabled: debugEnabled) if let wwwauthenticate = httpResponse.allHeaderFields["Www-Authenticate"] as? String, wwwauthenticate.contains("invalid_token") { completion(Result.failure(TeslaError.tokenRevoked)) } else if httpResponse.allHeaderFields["Www-Authenticate"] != nil, httpResponse.statusCode == 401 { completion(Result.failure(TeslaError.authenticationFailed)) } else if let mapped = try? teslaJSONDecoder.decode(ErrorMessage.self, from: data) { completion(Result.failure(TeslaError.networkError(error: NSError(domain: "TeslaError", code: httpResponse.statusCode, userInfo:[ErrorInfo: mapped])))) } else { completion(Result.failure(TeslaError.networkError(error: NSError(domain: "TeslaError", code: httpResponse.statusCode, userInfo: nil)))) } } else { if let wwwauthenticate = httpResponse.allHeaderFields["Www-Authenticate"] as? String { if wwwauthenticate.contains("invalid_token") { completion(Result.failure(TeslaError.authenticationFailed)) } } else { completion(Result.failure(TeslaError.networkError(error: NSError(domain: "TeslaError", code: httpResponse.statusCode, userInfo: nil)))) } } } }) task.resume() } func prepareRequest<BodyType: Encodable>(_ endpoint: Endpoint, body: BodyType) -> URLRequest { var request = URLRequest(url: URL(string: endpoint.baseURL(useMockServer) + endpoint.path)!) request.httpMethod = endpoint.method request.setValue("TeslaSwift", forHTTPHeaderField: "User-Agent") if let token = self.token?.accessToken { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } if let body = body as? String, body == nullBody { } else { request.httpBody = try? teslaJSONEncoder.encode(body) request.setValue("application/json", forHTTPHeaderField: "content-type") } logDebug("\nREQUEST: \(request)", debuggingEnabled: debuggingEnabled) logDebug("METHOD: \(request.httpMethod!)", debuggingEnabled: debuggingEnabled) if let headers = request.allHTTPHeaderFields { var headersString = "REQUEST HEADERS: [\n" headers.forEach {(key: String, value: String) in headersString += "\"\(key)\": \"\(value)\"\n" } headersString += "]" logDebug(headersString, debuggingEnabled: debuggingEnabled) } if let body = body as? String, body != nullBody { } else if let jsonString = body.jsonString { logDebug("REQUEST BODY: \(jsonString)", debuggingEnabled: debuggingEnabled) } return request } } // MARK: Streaming API extension TeslaSwift { /** Streams vehicle data - parameter vehicle: the vehicle that will receive the command - parameter reloadsVehicle: if you have a cached vehicle, the token might be expired, this forces a vehicle token reload - parameter dataReceived: callback to receive the websocket data */ public func openStream(vehicle: Vehicle, reloadsVehicle: Bool = true, dataReceived: @escaping (TeslaStreamingEvent) -> Void) { if reloadsVehicle { reloadVehicle(vehicle: vehicle) { (result: Result<Vehicle, Error>) in switch result { case .failure(let error): dataReceived(TeslaStreamingEvent.error(error)) case .success(let freshVehicle): self.startStream(vehicle: freshVehicle, dataReceived: dataReceived) } } } else { startStream(vehicle: vehicle, dataReceived: dataReceived) } } func reloadVehicle(vehicle: Vehicle, completion: @escaping (Result<Vehicle, Error>) -> ()) -> Void { getVehicles { (result: Result<[Vehicle], Error>) in switch result { case .failure(let error): completion(Result.failure(error)) case .success(let vehicles): for freshVehicle in vehicles where freshVehicle.vehicleID == vehicle.vehicleID { completion(Result.success(freshVehicle)) return } completion(Result.failure(TeslaError.failedToReloadVehicle)) } } } func startStream(vehicle: Vehicle, dataReceived: @escaping (TeslaStreamingEvent) -> Void) { guard let email = email, let vehicleToken = vehicle.tokens?.first else { dataReceived(TeslaStreamingEvent.error(TeslaError.streamingMissingEmailOrVehicleToken)) return } let authentication = TeslaStreamAuthentication(email: email, vehicleToken: vehicleToken, vehicleId: "\(vehicle.vehicleID!)") streaming.openStream(authentication: authentication, dataReceived: dataReceived) } /** Stops the stream */ public func closeStream() { streaming.closeStream() } } func logDebug(_ format: String, debuggingEnabled: Bool) { if debuggingEnabled { print(format) } } public let teslaJSONEncoder: JSONEncoder = { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted encoder.dateEncodingStrategy = .secondsSince1970 return encoder }() public let teslaJSONDecoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 return decoder }()
34.995956
174
0.600185
1a843a5136311e55efb0c2ccf77b18586ccf7c16
11,002
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit /// Errors that can be passed back by the existing data migration manager. enum ExistingDataMigrationManagerError: Error { /// Error loading experiments from disk. Called with the IDs of the experiments. case experimentLoadError(experimentIDs: [String]) /// Error saving experiments. Called with the IDs of the experiments. case experimentSaveError(experimentIDs: [String]) /// Error fetching sensor data for trials. Called with the IDs of the trials. case sensorDataFetchError(trialIDs: [String]) /// Error storing assets for the experiment. Called with the IDs of the experiments. case assetsSaveError(experimentIDs: [String]) } /// Manages migrating data from the pre-accounts root user to per-user storage, including /// experiments, sensor data and preferences. class ExistingDataMigrationManager { // MARK: - Properties /// The user manager for the user migrating data. let accountUserManager: AccountUserManager /// The user manager for the pre-accounts root user. let rootUserManager: RootUserManager /// The number of existing experiments. var numberOfExistingExperiments: Int { return rootUserManager.metadataManager.experimentOverviews.count } /// Whether or not there are existing experiments. var hasExistingExperiments: Bool { return numberOfExistingExperiments > 0 } private let migrationQueue = GSJOperationQueue() // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - accountUserManager: The user manager for the user migrating data. /// - rootUserManager: The user manager for the pre-accounts root user. init(accountUserManager: AccountUserManager, rootUserManager: RootUserManager) { self.accountUserManager = accountUserManager self.rootUserManager = rootUserManager // For memory performance, experiments migrate one at a time. migrationQueue.maxConcurrentOperationCount = 1 } // MARK: Experiments /// Moves an experiment from pre-account storage to storage for this user. /// /// - Parameters: /// - experimentID: The ID of the experiment to migrate. /// - completion: Called when migration is complete, with errors if any. func migrateExperiment(withID experimentID: String, completion: @escaping ([Error]) -> Void) { guard let experimentAndOverview = self.rootUserManager.metadataManager.experimentAndOverview( forExperimentID: experimentID) else { let error = ExistingDataMigrationManagerError.experimentLoadError(experimentIDs: [experimentID]) completion([error]) return } var migrateOperations = [GSJOperation]() // Sensor data var errorTrialIDs = [String]() experimentAndOverview.experiment.trials.forEach { (trial) in let migrateTrial = GSJBlockOperation(block: { [unowned self] (finished) in let accountSensorDataManager = self.accountUserManager.sensorDataManager let rootSensorDataManager = self.rootUserManager.sensorDataManager accountSensorDataManager.countOfAllSensorData(forTrialID: trial.ID, completion: { (accountCount) in rootSensorDataManager.countOfAllSensorData(forTrialID: trial.ID, completion: { (rootCount) in var shouldMigrateSensorData = true if let accountCount = accountCount { if rootCount == accountCount { shouldMigrateSensorData = false } else if accountCount > 0 { accountSensorDataManager.removeData(forTrialID: trial.ID) } } if shouldMigrateSensorData { rootSensorDataManager.fetchAllSensorData(forTrialID: trial.ID, completion: { (sensorData, fetchContext) in if let sensorData = sensorData { accountSensorDataManager.addSensorDataPoints(sensorData) { // Now that adding is complete, reset the fetch context to clear up memory. fetchContext.reset() finished() } } else { errorTrialIDs.append(trial.ID) finished() } }) } else { finished() } }) }) }) migrateOperations.append(migrateTrial) } let migrate = GroupOperation(operations: migrateOperations) migrate.maxConcurrentOperationCount = 1 migrate.addObserver(BlockObserver { [unowned self] _, _ in // Experiment let addExperimentSuccess = self.accountUserManager.metadataManager.addExperiment( experimentAndOverview.experiment, overview: experimentAndOverview.overview) var saveAssetsSuccess = true if addExperimentSuccess { let rootAssetsURL = self.rootUserManager.metadataManager.assetsURL(for: experimentAndOverview.experiment) if FileManager.default.fileExists(atPath: rootAssetsURL.path) { let accountAssetsURL = self.accountUserManager.metadataManager.assetsURL( for: experimentAndOverview.experiment) do { try FileManager.default.moveItem(at: rootAssetsURL, to: accountAssetsURL) } catch { saveAssetsSuccess = false print("[ExistingDataMigrationManager] Error moving assets directory at " + "'\(rootAssetsURL)' to '\(accountAssetsURL)': \(error.localizedDescription)") } } self.removeExperimentFromRootUser(experimentAndOverview.experiment) } // Errors var errors = [ExistingDataMigrationManagerError]() if !addExperimentSuccess { errors.append(.experimentSaveError(experimentIDs: [experimentID])) } if !errorTrialIDs.isEmpty { errors.append(.sensorDataFetchError(trialIDs: errorTrialIDs)) } if !saveAssetsSuccess { errors.append(.assetsSaveError(experimentIDs: [experimentID])) } DispatchQueue.main.async { completion(errors) } }) migrate.addObserver(BackgroundTaskObserver()) migrationQueue.addOperation(migrate) } /// Moves all experiments from pre-account storage to storage for this user. /// /// - Parameter completion: Called when migration is complete, with errors if any. func migrateAllExperiments(completion: @escaping ([Error]) -> Void) { let dispatchGroup = DispatchGroup() var experimentLoadErrorIDs = [String]() var experimentSaveErrorIDs = [String]() var sensorDataFetchErrorIDs = [String]() var assetsSaveErrorIDs = [String]() var otherErrors = [Error]() let experimentIDs = rootUserManager.metadataManager.experimentOverviews.map { $0.experimentID } experimentIDs.forEach { dispatchGroup.enter() migrateExperiment(withID: $0) { $0.forEach { if let error = $0 as? ExistingDataMigrationManagerError { switch error { case .experimentLoadError(let experimentIDs): experimentLoadErrorIDs.append(contentsOf: experimentIDs) case .experimentSaveError(let experimentIDs): experimentSaveErrorIDs.append(contentsOf: experimentIDs) case .sensorDataFetchError(let trialIDs): sensorDataFetchErrorIDs.append(contentsOf: trialIDs) case .assetsSaveError(let experimentIDs): assetsSaveErrorIDs.append(contentsOf: experimentIDs) } } else { otherErrors.append($0) } } dispatchGroup.leave() } } dispatchGroup.notify(qos: .userInitiated, queue: .global()) { var errors = [Error]() if !experimentLoadErrorIDs.isEmpty { errors.append(ExistingDataMigrationManagerError.experimentLoadError( experimentIDs: experimentLoadErrorIDs)) } if !experimentSaveErrorIDs.isEmpty { errors.append(ExistingDataMigrationManagerError.experimentSaveError( experimentIDs: experimentSaveErrorIDs)) } if !sensorDataFetchErrorIDs.isEmpty { errors.append(ExistingDataMigrationManagerError.sensorDataFetchError( trialIDs: sensorDataFetchErrorIDs)) } if !assetsSaveErrorIDs.isEmpty { errors.append(ExistingDataMigrationManagerError.assetsSaveError( experimentIDs: assetsSaveErrorIDs)) } if !otherErrors.isEmpty { errors.append(contentsOf: otherErrors) } DispatchQueue.main.async { completion(errors) } } } /// Removes an experiment from pre-account storage, as well as its trial sensor data. /// /// - Parameters: /// - experiment: The experiment to remove. func removeExperimentFromRootUser(_ experiment: Experiment) { // Sensor data experiment.trials.forEach { self.rootUserManager.sensorDataManager.removeData(forTrialID: $0.ID) } // Experiment self.rootUserManager.metadataManager.removeExperiment(withID: experiment.ID) } /// Removes an experiment from pre-account storage. /// /// - Parameter experimentID: The ID of the experiment to remove. func removeExperimentFromRootUser(withID experimentID: String) { guard let experiment = rootUserManager.metadataManager.experiment(withID: experimentID) else { return } removeExperimentFromRootUser(experiment) return } /// Removes all experiments from pre-account storage. func removeAllExperimentsFromRootUser() { let experimentIDs = rootUserManager.metadataManager.experimentOverviews.map { $0.experimentID } experimentIDs.forEach { removeExperimentFromRootUser(withID: $0) } } // MARK: Preferences /// Moves preferences from pre-account user defaults to user defaults for this user. func migratePreferences() { accountUserManager.preferenceManager.migratePreferences( fromManager: rootUserManager.preferenceManager) } // MARK: Bluetooth Devices /// Removes all bluetooth devices for the root user, as bluetooth devices are not a supported /// migration data type and must be reconfigured in the future by signed in accounts. func removeAllBluetoothDevices() { rootUserManager.metadataManager.deleteAllBluetoothSensors() } }
38.468531
99
0.679785
79e62bc87b5c8578bcfcc686a7987a16ce5a7e18
4,260
// // LikedPostInteractor.swift // Photostream // // Created by Mounir Ybanez on 19/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // protocol LikedPostInteractorInput: BaseModuleInteractorInput { func fetchNew(userId: String, limit: UInt) func fetchNext(userId: String, limit: UInt) func likePost(id: String) func unlikePost(id: String) } protocol LikedPostInteractorOutput: BaseModuleInteractorOutput { func didRefresh(data: [LikedPostData]) func didLoadMore(data: [LikedPostData]) func didRefresh(error: PostServiceError) func didLoadMore(error: PostServiceError) func didLike(error: PostServiceError?, postId: String) func didUnlike(error: PostServiceError?, postId: String) } protocol LikedPostInteractorInterface: BaseModuleInteractor { var service: PostService! { set get } var offset: String? { set get } var isFetching: Bool { set get } init(service: PostService) func fetchPosts(userId: String, limit: UInt) } class LikedPostInteractor: LikedPostInteractorInterface { typealias Output = LikedPostInteractorOutput weak var output: Output? var service: PostService! var offset: String? var isFetching: Bool = false required init(service: PostService) { self.service = service } func fetchPosts(userId: String, limit: UInt) { guard output != nil, offset != nil, !isFetching else { return } isFetching = true service.fetchLikedPosts(userId: userId, offset: offset!, limit: limit) { [weak self] result in self?.didFetch(result: result) } } private func didFetch(result: PostServiceResult) { isFetching = false guard result.error == nil else { didFetch(error: result.error!) return } guard let list = result.posts, list.count > 0 else { didFetch(data: [LikedPostData]()) return } var posts = [LikedPostData]() for post in list.posts { guard let user = list.users[post.userId] else { continue } var item = LikedPostDataItem() item.id = post.id item.message = post.message item.timestamp = post.timestamp item.photoUrl = post.photo.url item.photoWidth = post.photo.width item.photoHeight = post.photo.height item.likes = post.likesCount item.comments = post.commentsCount item.isLiked = post.isLiked item.userId = user.id item.avatarUrl = user.avatarUrl item.displayName = user.displayName posts.append(item) } didFetch(data: posts) offset = result.nextOffset } private func didFetch(data: [LikedPostData]) { if offset != nil, offset!.isEmpty { output?.didRefresh(data: data) } else { output?.didLoadMore(data: data) } } private func didFetch(error: PostServiceError) { if offset != nil, offset!.isEmpty { output?.didRefresh(error: error) } else { output?.didLoadMore(error: error) } } } extension LikedPostInteractor: LikedPostInteractorInput { func fetchNew(userId: String, limit: UInt) { offset = "" fetchPosts(userId: userId, limit: limit) } func fetchNext(userId: String, limit: UInt) { fetchPosts(userId: userId, limit: limit) } func likePost(id: String) { guard output != nil else { return } service.like(id: id) { error in self.output?.didLike(error: error, postId: id) } } func unlikePost(id: String) { guard output != nil else { return } service.unlike(id: id) { error in self.output?.didUnlike(error: error, postId: id) } } }
25.97561
80
0.564085
01e3fe727cf4426d4b5b94b22362248e64f5082f
183
// // GenericCellDataProtocol.swift // MoveeComponents // // Created by Oguz Tandogan on 18.11.2020. // import Foundation public protocol GenericCellDataProtocol: class { }
14.076923
48
0.721311
1a6401069993b8ce92999d2208c03ed3083ab69f
1,019
// // String+Nexd.swift // Nexd // // Created by Tobias Schröpf on 01.04.20. // Copyright © 2020 Tobias Schröpf. All rights reserved. // import UIKit extension String { func asPlaceholder() -> NSAttributedString { let attributes: [NSAttributedString.Key: Any] = [ .foregroundColor: R.color.textfieldStroke()! ] return NSAttributedString(string: self, attributes: attributes) } func asLink(range: Range<String.Index>?, target: String) -> NSAttributedString { let attributes: [NSAttributedString.Key: Any] = [ .font: R.font.proximaNovaRegular(size: 16)! ] let attributedString = NSMutableAttributedString(string: self, attributes: attributes) guard let range = range else { return attributedString } attributedString.addAttribute(.link, value: target, range: NSRange(range, in: self)) return attributedString } var cstring: UnsafePointer<CChar> { (self as NSString).utf8String! } }
28.305556
94
0.656526
0e10a9963e6c19e6f5ed2496f6fac4bbbc329d85
913
import UIKit import SwiftUI extension SwiftUI.View { private var appWindow: UIWindow { if let window = UIApplication.shared.windows.first { return window } else { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = UIViewController() window.makeKeyAndVisible() return window } } func placeUIView() -> UIView { let controller = UIHostingController(rootView: self) let uiView = controller.view! // out of screen uiView.frame = CGRect(x: 0, y: CGFloat(Int.max), width: 1, height: 1) appWindow.rootViewController?.view.addSubview(uiView) let size = controller.sizeThatFits(in: UIScreen.main.bounds.size) uiView.bounds = CGRect(origin: .zero, size: size) uiView.sizeToFit() return uiView } }
27.666667
77
0.6046
21215d3164aa426f8e08acfe2cc91ec0c0811a81
12,777
// // NativeAdView.swift // flutter_native_admob // // Created by Dao Duy Duong on 3/8/20. // import UIKit import GoogleMobileAds enum NativeAdmobType: String { case banner, full } class NativeAdView: GADNativeAdView { let adLabelLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.textColor = .white label.text = "Ad" label.numberOfLines = 1 return label }() lazy var adLabelView: UIView = { let view = UIView() view.backgroundColor = .fromHex("FFCC66") view.layer.cornerRadius = 3 view.clipsToBounds = true view.addSubview(adLabelLbl) adLabelLbl.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 1, left: 3, bottom: 1, right: 3)) return view }() let adMediaView = GADMediaView() let adIconView: UIImageView = { let imageView = UIImageView() imageView.autoSetDimensions(to: CGSize(width: 40, height: 40)) return imageView }() let adHeadLineLbl: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 16) label.numberOfLines = 1 return label }() let adAdvertiserLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14) label.numberOfLines = 1 return label }() let adRatingView = StackLayout().spacing(2) let adBodyLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.numberOfLines = 2 return label }() let adPriceLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.numberOfLines = 1 label.textAlignment = .right return label }() let adStoreLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.numberOfLines = 1 label.textAlignment = .right return label }() let callToActionBtn: UIButton = { let button = UIButton() button.setBackgroundImage(.from(color: .fromHex("#4CBE99")), for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15) button.autoSetDimension(.height, toSize: 30) button.isUserInteractionEnabled = false; return button }() var starIcon: StarIcon { let icon = StarIcon() icon.autoSetDimensions(to: CGSize(width: 15, height: 15)) return icon } var options = NativeAdmobOptions() { didSet { updateOptions() } } let type: NativeAdmobType init(frame: CGRect, type: NativeAdmobType) { self.type = type super.init(frame: frame) setupView() } required init?(coder: NSCoder) { fatalError("No support for interface builder") } func setNativeAd(_ nativeAd: GADNativeAd?) { guard let nativeAd = nativeAd else { return } self.nativeAd = nativeAd // Set the mediaContent on the GADMediaView to populate it with available // video/image asset. adMediaView.mediaContent = nativeAd.mediaContent // Populate the native ad view with the native ad assets. // The headline is guaranteed to be present in every native ad. adHeadLineLbl.text = nativeAd.headline adAdvertiserLbl.text = nativeAd.advertiser if nativeAd.advertiser.isNilOrEmpty { adAdvertiserLbl.isHidden = true } // These assets are not guaranteed to be present. Check that they are before // showing or hiding them. adBodyLbl.text = nativeAd.body if nativeAd.body.isNilOrEmpty { adBodyLbl.isHidden = true } callToActionBtn.setTitle(nativeAd.callToAction, for: .normal) if nativeAd.callToAction.isNilOrEmpty { callToActionBtn.isHidden = true } adIconView.image = nativeAd.icon?.image adIconView.isHidden = nativeAd.icon == nil adRatingView.arrangedSubviews.forEach { view in view.removeFromSuperview() } let numOfStars = Int(truncating: nativeAd.starRating ?? 0) adRatingView.children(Array(0..<numOfStars).map { _ in let icon = self.starIcon icon.color = options.ratingColor return icon }) adRatingView.isHidden = nativeAd.starRating == nil adStoreLbl.text = nativeAd.store if nativeAd.store.isNilOrEmpty { adStoreLbl.isHidden = true } adPriceLbl.text = nativeAd.price if nativeAd.price.isNilOrEmpty { adPriceLbl.isHidden = true } layoutIfNeeded() } } private extension NativeAdView { func setupView() { self.mediaView = adMediaView self.headlineView = adHeadLineLbl self.callToActionView = callToActionBtn self.iconView = adIconView self.bodyView = adBodyLbl self.storeView = adStoreLbl self.priceView = adPriceLbl self.starRatingView = adRatingView self.advertiserView = adAdvertiserLbl switch type { case .full: setupFullLayout() case .banner: setupBannerLayout() } } func setupFullLayout() { adBodyLbl.numberOfLines = 2 let infoLayout = StackLayout().spacing(5).children([ adIconView, StackLayout().direction(.vertical).children([ adHeadLineLbl, StackLayout().children([ adAdvertiserLbl, adRatingView, UIView() ]), ]), ]) callToActionBtn.setContentHuggingPriority(.defaultHigh, for: .horizontal) let actionLayout = StackLayout() .spacing(5) .children([ UIView(), adPriceLbl, adStoreLbl, callToActionBtn ]) adBodyLbl.autoSetDimension(.height, toSize: 20, relation: .greaterThanOrEqual) adLabelLbl.autoSetDimension(.height, toSize: 15, relation: .greaterThanOrEqual) addSubview(adLabelView) adLabelView.autoPinEdge(toSuperviewEdge: .top) adLabelView.autoPinEdge(toSuperviewEdge: .leading) let contentView = UIView() addSubview(contentView) contentView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .top) contentView.autoPinEdge(.top, to: .bottom, of: adLabelView, withOffset: 5) let layout = StackLayout() .direction(.vertical) .spacing(5) .children([ adMediaView, infoLayout, adBodyLbl, actionLayout ]) contentView.addSubview(layout) layout.autoAlignAxis(toSuperviewAxis: .horizontal) layout.autoPinEdge(toSuperviewEdge: .leading) layout.autoPinEdge(toSuperviewEdge: .trailing) layout.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual) layout.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual) } func setupBannerLayout() { adBodyLbl.numberOfLines = 2 callToActionBtn.setContentHuggingPriority(.defaultHigh, for: .horizontal) adLabelLbl.autoSetDimension(.height, toSize: 15, relation: .greaterThanOrEqual) addSubview(adLabelView) adLabelView.autoPinEdge(toSuperviewEdge: .top) adLabelView.autoPinEdge(toSuperviewEdge: .leading) let contentView = UIView() addSubview(contentView) contentView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .top) contentView.autoPinEdge(.top, to: .bottom, of: adLabelView, withOffset: 5) let layout = StackLayout().spacing(5).children([ adIconView, StackLayout().direction(.vertical).children([ adHeadLineLbl, adBodyLbl, StackLayout().children([ adAdvertiserLbl, adRatingView, UIView() ]), ]), callToActionBtn ]) layout.isUserInteractionEnabled = false contentView.addSubview(layout) layout.autoAlignAxis(toSuperviewAxis: .horizontal) layout.autoPinEdge(toSuperviewEdge: .leading) layout.autoPinEdge(toSuperviewEdge: .trailing) layout.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual) layout.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual) } func updateOptions() { adMediaView.isHidden = !options.showMediaContent backgroundColor = options.backgroundColor adLabelLbl.textColor = options.adLabelTextStyle.color if let typeface = options.adLabelTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.adLabelTextStyle.fontSize) { adLabelLbl.font = font } else { adLabelLbl.font = UIFont.systemFont(ofSize: options.adLabelTextStyle.fontSize) } adLabelView.backgroundColor = options.adLabelTextStyle.backgroundColor ?? .fromHex("FFCC66") adLabelView.isHidden = !options.adLabelTextStyle.isVisible if let typeface = options.headlineTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.headlineTextStyle.fontSize) { adHeadLineLbl.font = font } else { adHeadLineLbl.font = UIFont.systemFont(ofSize: options.headlineTextStyle.fontSize) } adHeadLineLbl.textColor = options.headlineTextStyle.color adHeadLineLbl.isHidden = !options.headlineTextStyle.isVisible if let typeface = options.advertiserTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.advertiserTextStyle.fontSize) { adAdvertiserLbl.font = font } else { adAdvertiserLbl.font = UIFont.systemFont(ofSize: options.advertiserTextStyle.fontSize) } adAdvertiserLbl.textColor = options.advertiserTextStyle.color adAdvertiserLbl.isHidden = !options.advertiserTextStyle.isVisible if let typeface = options.bodyTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.bodyTextStyle.fontSize) { adBodyLbl.font = font } else { adBodyLbl.font = UIFont.systemFont(ofSize: options.bodyTextStyle.fontSize) } adBodyLbl.textColor = options.bodyTextStyle.color adBodyLbl.isHidden = !options.bodyTextStyle.isVisible if let typeface = options.storeTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.storeTextStyle.fontSize) { adStoreLbl.font = font } else { adStoreLbl.font = UIFont.systemFont(ofSize: options.storeTextStyle.fontSize) } adStoreLbl.textColor = options.storeTextStyle.color adStoreLbl.isHidden = !options.storeTextStyle.isVisible if let typeface = options.priceTextStyle.iosTypeface, let font = UIFont(name: typeface, size: options.priceTextStyle.fontSize) { adPriceLbl.font = font } else { adPriceLbl.font = UIFont.systemFont(ofSize: options.priceTextStyle.fontSize) } adPriceLbl.textColor = options.priceTextStyle.color adPriceLbl.isHidden = !options.priceTextStyle.isVisible if let typeface = options.callToActionStyle.iosTypeface, let font = UIFont(name: typeface, size: options.callToActionStyle.fontSize) { callToActionBtn.titleLabel?.font = font } else { callToActionBtn.titleLabel?.font = UIFont.systemFont(ofSize: options.callToActionStyle.fontSize) } callToActionBtn.setTitleColor(options.callToActionStyle.color, for: .normal) if let bgColor = options.callToActionStyle.backgroundColor { callToActionBtn.setBackgroundImage(.from(color: bgColor), for: .normal) } callToActionBtn.isHidden = !options.callToActionStyle.isVisible starIcon.color = options.ratingColor } }
35.393352
108
0.615246
3a6adb34ccded3d3cf23a16246f7dfe400812ab1
5,637
import XCTest import OHHTTPStubs @testable import MapboxDirections class SpokenInstructionsTests: XCTestCase { override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } func testInstructions() { let expectation = self.expectation(description: "calculating directions should return results") let queryParams: [String: String?] = [ "alternatives": "false", "geometries": "polyline", "overview": "full", "steps": "true", "continue_straight": "true", "access_token": BogusToken, "voice_instructions": "true", "voice_units": "imperial", "banner_instructions": "true", "waypoint_names": "the hotel;the gym" ] stub(condition: isHost("api.mapbox.com") && containsQueryParams(queryParams)) { _ in let path = Bundle(for: type(of: self)).path(forResource: "instructions", ofType: "json") return OHHTTPStubsResponse(fileAtPath: path!, statusCode: 200, headers: ["Content-Type": "application/json"]) } let startWaypoint = Waypoint(location: CLLocation(latitude: 37.780602, longitude: -122.431373), heading: nil, name: "the hotel") let endWaypoint = Waypoint(location: CLLocation(latitude: 37.758859, longitude: -122.404058), heading: nil, name: "the gym") let options = RouteOptions(waypoints: [startWaypoint, endWaypoint], profileIdentifier: .automobileAvoidingTraffic) options.shapeFormat = .polyline options.includesSteps = true options.includesAlternativeRoutes = false options.routeShapeResolution = .full options.includesSpokenInstructions = true options.distanceMeasurementSystem = .imperial options.includesVisualInstructions = true var route: Route? let task = Directions(accessToken: BogusToken).calculate(options) { (waypoints, routes, error) in XCTAssertNil(error, "Error: \(error!.localizedDescription)") XCTAssertNotNil(routes) XCTAssertEqual(routes!.count, 1) route = routes!.first! expectation.fulfill() } XCTAssertNotNil(task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error, "Error: \(error!.localizedDescription)") XCTAssertEqual(task.state, .completed) } XCTAssertNotNil(route) XCTAssertEqual(route!.routeIdentifier, "cjgy4xps418g17mo7l2pdm734") let leg = route!.legs.first! let step = leg.steps[1] XCTAssertEqual(step.instructionsSpokenAlongStep!.count, 3) let spokenInstructions = step.instructionsSpokenAlongStep! XCTAssertEqual(spokenInstructions[0].distanceAlongStep, 1107.1) XCTAssertEqual(spokenInstructions[0].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Continue on Baker Street for a half mile</prosody></amazon:effect></speak>") XCTAssertEqual(spokenInstructions[0].text, "Continue on Baker Street for a half mile") XCTAssertEqual(spokenInstructions[1].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">In 900 feet, turn left onto Page Street</prosody></amazon:effect></speak>") XCTAssertEqual(spokenInstructions[1].text, "In 900 feet, turn left onto Page Street") XCTAssertEqual(spokenInstructions[2].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Turn left onto Page Street</prosody></amazon:effect></speak>") XCTAssertEqual(spokenInstructions[2].text, "Turn left onto Page Street") let arrivalStep = leg.steps[leg.steps.endIndex - 2] XCTAssertEqual(arrivalStep.instructionsSpokenAlongStep!.count, 1) let arrivalSpokenInstructions = arrivalStep.instructionsSpokenAlongStep! XCTAssertEqual(arrivalSpokenInstructions[0].text, "You have arrived at the gym") XCTAssertEqual(arrivalSpokenInstructions[0].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">You have arrived at the gym</prosody></amazon:effect></speak>") let visualInstructions = step.instructionsDisplayedAlongStep XCTAssertNotNil(visualInstructions) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.text, "Page Street") XCTAssertEqual(visualInstructions?.first?.primaryInstruction.textComponents.first!.text, "Page Street") XCTAssertEqual(visualInstructions?.first?.distanceAlongStep, 1107.1) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.finalHeading, 180.0) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.maneuverType, .turn) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.maneuverDirection, .left) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.textComponents.first?.type, .text) XCTAssertEqual(visualInstructions?.first?.primaryInstruction.textComponents.first?.abbreviation, "Page St") XCTAssertEqual(visualInstructions?.first?.primaryInstruction.textComponents.first?.abbreviationPriority, 0) XCTAssertEqual(visualInstructions?.first?.drivingSide, .right) XCTAssertNil(visualInstructions?.first?.secondaryInstruction) let arrivalVisualInstructions = arrivalStep.instructionsDisplayedAlongStep! XCTAssertEqual(arrivalVisualInstructions.first?.secondaryInstruction?.text, "the gym") } }
53.685714
190
0.67802
90da35b09f329f466f1f55f507709210d238bd8e
3,667
// // LiveMouseView.swift // PixelKit-macOS // // Created by Anton Heestand on 2019-03-15. // #if os(macOS) && !targetEnvironment(macCatalyst) import AppKit public class LiveMouseView: NSView { var mousePoint: CGPoint? var mouseLeft: Bool = false var mouseRight: Bool = false var mouseInView: Bool = false var trackingArea : NSTrackingArea? var mousePointCallbacks: [(CGPoint) -> ()] = [] var mouseLeftCallbacks: [(Bool) -> ()] = [] var mouseRightCallbacks: [(Bool) -> ()] = [] var mouseInViewCallbacks: [(Bool) -> ()] = [] public func listenToMousePoint(_ callback: @escaping (CGPoint) -> ()) { mousePointCallbacks.append(callback) } public func listenToMouseLeft(_ callback: @escaping (Bool) -> ()) { mouseLeftCallbacks.append(callback) } public func listenToMouseRight(_ callback: @escaping (Bool) -> ()) { mouseRightCallbacks.append(callback) } public func listenToMouseInView(_ callback: @escaping (Bool) -> ()) { mouseInViewCallbacks.append(callback) } override public func updateTrackingAreas() { if trackingArea != nil { self.removeTrackingArea(trackingArea!) } let options: NSTrackingArea.Options = [ .mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow ] trackingArea = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil) self.addTrackingArea(trackingArea!) } override public func mouseMoved(with event: NSEvent) { moved(with: event) } override public func mouseDragged(with event: NSEvent) { moved(with: event) } override public func rightMouseDragged(with event: NSEvent) { moved(with: event) } func moved(with event: NSEvent) { let point = convert(event.locationInWindow, to: self) let coord = getCoord(from: point) mousePoint = coord for mousePointCallback in mousePointCallbacks { mousePointCallback(coord) } } override public func mouseDown(with event: NSEvent) { mouseLeft = true for mouseLeftCallback in mouseLeftCallbacks { mouseLeftCallback(true) } } override public func mouseUp(with event: NSEvent) { mouseLeft = false for mouseLeftCallback in mouseLeftCallbacks { mouseLeftCallback(false) } } override public func rightMouseDown(with event: NSEvent) { mouseRight = true for mouseRightCallback in mouseRightCallbacks { mouseRightCallback(true) } } override public func rightMouseUp(with event: NSEvent) { mouseRight = false for mouseRightCallback in mouseRightCallbacks { mouseRightCallback(false) } } override public func mouseEntered(with event: NSEvent) { mouseInView = true for mouseInViewCallback in mouseInViewCallbacks { mouseInViewCallback(true) } } override public func mouseExited(with event: NSEvent) { mouseInView = false for mouseInViewCallback in mouseInViewCallbacks { mouseInViewCallback(false) } } func getCoord(from localPoint: CGPoint) -> CGPoint { let uv = CGPoint(x: localPoint.x / bounds.width, y: localPoint.y / bounds.height) let aspect = bounds.width / bounds.height let point = CGPoint(x: (uv.x - 0.5) * aspect, y: uv.y - 0.5) return point } } #endif
29.103175
89
0.611126
09e8be5ad3b0b927e0531f8b176ebb3f4c987195
9,245
// // AGMedallionView.swift // QuadCurveMenuSWIFT // // Created by Abdullah Al-Ashi on 17/Sep/17. // Copyright © 2017 Abdullah Al-Ashi. All rights reserved. // import Foundation import UIKit class AGMedallionView: UIView { var image: UIImage { didSet { self.setNeedsDisplay() } } var highlightedImage:UIImage var borderColor : UIColor { didSet { self.setNeedsDisplay() } } var borderWidth :CGFloat? var shadowColor : UIColor var shadowOffset : CGSize var shadowBlur :CGFloat var highlighted : Bool var progressColor :UIColor var progress : CGFloat var alphaGradient: CGGradient { let colors : [CGFloat] = [1.0, 0.75, 1.0, 0.0, 0.0, 0.0] let colorStops : [CGFloat] = [1.0, 0.35, 0.0] let grayColorSpace : CGColorSpace = CGColorSpaceCreateDeviceGray() return CGGradient(colorSpace: grayColorSpace, colorComponents: colors, locations: colorStops, count: 3)! } func DEGREES_2_RADIANS(_ x: Double) -> CGFloat{ return CGFloat(0.0174532925 * (x)) } func setBorderWidth(aBorderWidth: CGFloat) -> Void{ if (borderWidth != aBorderWidth) { borderWidth = aBorderWidth self.setNeedsDisplay() } } func setShadowColor(aShadowColor: UIColor) -> Void{ if (shadowColor != aShadowColor) { shadowColor = aShadowColor self.setNeedsDisplay() } } func setShadowOffset(aShadowOffset: CGSize) -> Void{ if (!shadowOffset.equalTo(aShadowOffset)) { shadowOffset.width = aShadowOffset.width; shadowOffset.height = aShadowOffset.height; self.setNeedsDisplay() } } func setShadowBlur(aShadowBlur: CGFloat) -> Void{ if (shadowBlur != aShadowBlur) { shadowBlur = aShadowBlur self.setNeedsDisplay() } } func setProgress(aProgress: CGFloat) -> Void{ if (progress != aProgress) { progress = aProgress self.setNeedsDisplay() } } func setup() -> Void { self.borderColor = UIColor.white self.borderWidth = 5.0 self.shadowColor = UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 0.75) self.shadowOffset = CGSize(width: 0, height: 0) self.shadowBlur = 2.0; self.backgroundColor = UIColor.clear self.progress = 0.0; self.progressColor = UIColor.gray } convenience init() { self.init(frame: CGRect(x: 0.0, y: 0.0, width: 128, height: 128)) } override init(frame: CGRect) { self.image = UIImage() self.highlightedImage = UIImage() self.borderColor = UIColor.white self.borderWidth = 5.0 self.shadowColor = UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 0.75) self.shadowOffset = CGSize(width: 0, height: 0) self.shadowBlur = 2.0; self.progress = 0.0; self.progressColor = UIColor.gray self.highlighted = false super.init(frame: frame) self.backgroundColor = UIColor.clear } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { self.image = UIImage() self.highlightedImage = UIImage() self.borderColor = UIColor.white self.borderWidth = 5.0 self.shadowColor = UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 0.75) self.shadowOffset = CGSize(width: 0, height: 0) self.shadowBlur = 2.0; self.progress = 0.0; self.progressColor = UIColor.gray self.highlighted = false super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } override func draw(_ rect: CGRect){ let imageRect : CGRect = CGRect(x: (self.borderWidth)!, y: (self.borderWidth)!, width: rect.size.width - (self.borderWidth! * 2), height: rect.size.height - (self.borderWidth! * 2)) let maskColorSpaceRef : CGColorSpace = CGColorSpaceCreateDeviceGray(); let mainMaskContextRef : CGContext = CGContext(data: nil, width: Int(rect.size.width), height: Int(rect.size.height), bitsPerComponent: 8, bytesPerRow: Int(rect.size.width), space: maskColorSpaceRef, bitmapInfo: 0)! let shineMaskContextRef : CGContext = CGContext(data: nil, width: Int(rect.size.width), height: Int(rect.size.height), bitsPerComponent: 8, bytesPerRow: Int(rect.size.width), space: maskColorSpaceRef, bitmapInfo: 0)! mainMaskContextRef.setFillColor(UIColor.black.cgColor) shineMaskContextRef.setFillColor(UIColor.black.cgColor) mainMaskContextRef.fill(rect) shineMaskContextRef.fill(rect) mainMaskContextRef.setFillColor(UIColor.white.cgColor) shineMaskContextRef.setFillColor(UIColor.white.cgColor) mainMaskContextRef.move(to: CGPoint(x: 0, y: 0)) mainMaskContextRef.addEllipse(in: imageRect) mainMaskContextRef.fillPath() shineMaskContextRef.translateBy(x: -(rect.size.width / 4), y: rect.size.height / 4 * 3) shineMaskContextRef.rotate(by: -45.0) shineMaskContextRef.move(to: CGPoint(x: 0, y: 0)) shineMaskContextRef.fill(CGRect(x: 0, y: 0, width: rect.size.width / 8 * 5, height: rect.size.height)) let mainMaskImageRef : CGImage = mainMaskContextRef.makeImage()! let shineMaskImageRef : CGImage = shineMaskContextRef.makeImage()! let contextRef : CGContext = UIGraphicsGetCurrentContext()!; contextRef.saveGState(); let currentImage : UIImage = (self.highlighted ? self.highlightedImage : self.image) let imageRef : CGImage = currentImage.cgImage!.masking(mainMaskImageRef)! contextRef.translateBy(x: 0, y: rect.size.height) contextRef.scaleBy(x: 1.0, y: -1.0) contextRef.saveGState() contextRef.draw(imageRef, in: rect) contextRef.restoreGState() contextRef.saveGState() contextRef.clip(to: self.bounds, mask: mainMaskImageRef) contextRef.clip(to: self.bounds, mask: shineMaskImageRef) contextRef.setBlendMode(CGBlendMode.lighten) contextRef.drawLinearGradient(self.alphaGradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: self.bounds.size.height), options: CGGradientDrawingOptions.init(rawValue: 0)) contextRef.restoreGState() contextRef.setLineWidth(self.borderWidth!) contextRef.setStrokeColor(self.borderColor.cgColor) contextRef.move(to: CGPoint(x: 0, y: 0)) contextRef.addEllipse(in: imageRect) contextRef.setShadow(offset: self.shadowOffset, blur: self.shadowBlur, color: self.shadowColor.cgColor); contextRef.strokePath(); contextRef.restoreGState(); contextRef.saveGState(); let centerPoint : CGPoint = CGPoint(x: imageRect.origin.x + imageRect.size.width / 2, y: imageRect.origin.y + imageRect.size.height / 2) if (self.progress != 0.0) { let radius : CGFloat = CGFloat(imageRect.size.height / 2) let endAngle : CGFloat = DEGREES_2_RADIANS( Double(self.progress * 359.9) - 90.0) let startAngle : CGFloat = DEGREES_2_RADIANS(270) let progressPath : CGMutablePath = CGMutablePath() progressPath.addArc(center: centerPoint, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: false) contextRef.setStrokeColor(self.progressColor.cgColor) contextRef.setLineWidth(3.0) contextRef.addPath(progressPath) contextRef.strokePath() } contextRef.restoreGState(); } }
33.618182
186
0.534992
c1f732b336c580abc14aad45002ee179b844ba52
3,200
import Library import Prelude import UIKit final class PledgeExpandableHeaderRewardCell: UITableViewCell, ValueCell { // MARK: - Properties private lazy var amountLabel: UILabel = UILabel(frame: .zero) private lazy var rootStackView: UIStackView = UIStackView(frame: .zero) private lazy var titleLabel: UILabel = UILabel(frame: .zero) private let viewModel: PledgeExpandableHeaderRewardCellViewModelType = PledgeExpandableHeaderRewardCellViewModel() // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.configureViews() self.bindViewModel() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self |> \.selectionStyle .~ .none |> \.separatorInset .~ .init(leftRight: CheckoutConstants.PledgeView.Inset.leftRight) _ = self.amountLabel |> UILabel.lens.contentHuggingPriority(for: .horizontal) .~ .required |> \.adjustsFontForContentSizeCategory .~ true _ = self.rootStackView |> rootStackViewStyle(self.traitCollection.preferredContentSizeCategory > .accessibilityLarge) _ = self.titleLabel |> titleLabelStyle } // MARK: - View model override func bindViewModel() { super.bindViewModel() self.amountLabel.rac.attributedText = self.viewModel.outputs.amountAttributedText self.viewModel.outputs.labelText .observeForUI() .observeValues { [weak self] titleText in self?.titleLabel.text = titleText self?.titleLabel.setNeedsLayout() } } // MARK: - Configuration func configureWith(value: PledgeExpandableHeaderRewardCellData) { self.viewModel.inputs.configure(with: value) self.contentView.layoutIfNeeded() } private func configureViews() { _ = (self.rootStackView, self.contentView) |> ksr_addSubviewToParent() |> ksr_constrainViewToEdgesInParent() _ = ([self.titleLabel, self.amountLabel], self.rootStackView) |> ksr_addArrangedSubviewsToStackView() } } // MARK: - Styles private let titleLabelStyle: LabelStyle = { label in label |> \.font .~ UIFont.ksr_subhead().bolded |> \.textColor .~ .ksr_dark_grey_500 |> \.numberOfLines .~ 0 } private func rootStackViewStyle(_ isAccessibilityCategory: Bool) -> (StackViewStyle) { let alignment: UIStackView.Alignment = (isAccessibilityCategory ? .leading : .top) let axis: NSLayoutConstraint.Axis = (isAccessibilityCategory ? .vertical : .horizontal) let distribution: UIStackView.Distribution = (isAccessibilityCategory ? .equalSpacing : .fill) let spacing: CGFloat = (isAccessibilityCategory ? Styles.grid(1) : 0) return { (stackView: UIStackView) in stackView |> \.alignment .~ alignment |> \.axis .~ axis |> \.distribution .~ distribution |> \.spacing .~ spacing |> \.isLayoutMarginsRelativeArrangement .~ true |> \.layoutMargins .~ .init( topBottom: Styles.grid(3), leftRight: CheckoutConstants.PledgeView.Inset.leftRight ) } }
29.357798
100
0.703125
e0045de86f1a3ec9d53e192de64689a3a1917cd9
413
// // VNDetectRectanglesRequest+Rx.swift // RxVision // // Created by Maxim Volgin on 02/10/2018. // Copyright (c) RxSwiftCommunity. All rights reserved. // import Vision import RxSwift @available(iOS 11.0, *) extension Reactive where Base: VNDetectRectanglesRequest { public static func request<T>() -> RxVNDetectRectanglesRequest<T> { return RxVNDetectRectanglesRequest<T>() } }
20.65
71
0.702179
754b2b701b8c412d9110992a8cb29bc483b9f099
561
// // CollectionGameCell.swift // DYZB // // Created by Andy on 2020/6/22. // Copyright © 2020 Andy. All rights reserved. // import UIKit class CollectionGameCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! var group : AnchorGroup? { didSet{ titleLabel.text = group?.tag_name let iconURL = URL(string: group?.icon_url ?? "") iconImageView.kf.setImage(with: iconURL,placeholder: UIImage(named: "home_more_btn")) } } }
22.44
97
0.645276